feat(xray): update xray-core to v26.9.30 and adapt panel

Bump xtls/xray-core to b26a91de4f (v26.9.30) and the three binary pins
(DockerInit.sh, release.yml Linux + Windows) in lockstep. No deleted
symbols; the sing and sing-shadowsocks indirect deps drop out with the
SS2022 rewrite.

XDNS finalmask (#6718) replaced its string lists with objects: domains
are {name, types, edns0, lenLimit, labelLimit} and client resolvers
{type, settings.addr}. The loader no longer parses the old lists, so a
single stored xdns mask keeps the whole core from starting. The new leaf
package internal/util/maskcompat converts them: "name[:type]" becomes a
domain and "name[:type]+udp://addr" a domain plus a udp resolver. A bare
name maps to TXT, the type legacy clients queried by default, and each
converted domain keeps the 1232-byte EDNS0 the old code always used
(without it the server caps answers at 512). It runs from:
- the XdnsFinalmaskObjectsFix seeder, over inbound streams, hosts, the
  xray template, the global sub-JSON mask and cached subscription
  outbounds;
- inbound save (normalizeStreamSettings) and GetXrayConfig, for rows
  that never went through the seeder;
- both link importers, since fm= from an older panel carries the lists.
The finalmask form edits the object shape (every key needs a registered
field, or the finalmask watch drops it on save) and lifts legacy masks
on open. The udp-mask golden fixture moves to the object shape, which
TestGoldenStreamFixturesBuildInXray now builds through the core. The
wire format changed as well, so pre-upgrade clients need the new core.

WireGuard outbound (#6771) dropped settings.domainStrategy and the
remoteDNS "local" mode. The endpoint lookup now follows
sockopt.domainStrategy and in-tunnel targets the outbound's
targetStrategy. The old key is silently ignored, which undid the
IPv4-first endpoint lookup the WARP outbound depends on (#5205), and
"local" now panics the core at startup because remoteDNS goes through
netip.MustParseAddr. The WireguardDomainStrategyFix seeder moves a stored
family preference to both keys (a value already set wins) and turns
"local" into targetStrategy; the outbound form lifts legacy rows the same
way and drops its select, the WARP modal writes the new placement, and
the inbound form loses a field the server never read.
ValidateOutboundConfig now refuses a non-IP remoteDNS entry, which
conf.Build() lets through, on template save and for outbound
subscriptions.

Noise finalmask items accept type "exp" (#6862), a tag expression. The
form offers it for noise items only: header-custom items go through the
core's PraseByteSlice, which refuses it.

TUN gained autoSystemDnsToGateway (Linux) and autoSystemWfpBlockLeak
(Windows). Both pass through the settings schema so a value set in JSON
survives the next form save.

MASQUE (inbound, outbound, transport) and the XDRIVE transport are new
protocols the panel does not offer yet; their new loader refusals only
cover configs the panel never generates. The FakeDNS IPv6 pool default,
the SS2022 rewrite (same gRPC account; emails are now deduped
case-insensitively, as the panel already does), the restored udphop
interval default and the rest change no panel-facing config.
This commit is contained in:
MHSanaei
2026-09-30 17:27:10 +02:00
parent 99047c0a63
commit 62423cacd1
38 changed files with 1487 additions and 165 deletions
+234 -1
View File
@@ -23,6 +23,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/config"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
"github.com/mhsanaei/3x-ui/v3/internal/util/maskcompat"
"github.com/mhsanaei/3x-ui/v3/internal/util/random"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
@@ -1280,7 +1281,7 @@ func runSeeders(isUsersEmpty bool) error {
}
if empty && isUsersEmpty {
seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix2", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "FreedomFinalRulesPrivateEgressBlock", "UppercaseFreedomFinalRulesFix", "InboundRealityFinalmaskTcpStrip", "ApiTokensHash", "LegacyProxySettingsCleanup", "OutboundRemovedKeysFix", "FreedomDomainStrategyFix", "DNSOutboundLegacyKeysFix", "DNSOutboundQTypeZeroFix", "WireguardPeersToClients", "MtprotoSecretsToClients", "NodeInboundsAdopted", "ResetIpLimitNoFail2ban"}
seeders := []string{"UserPasswordHash", "ClientsTable", "InboundClientsArrayFix", "InboundClientTgIdFix2", "InboundClientSubIdFix", "FreedomFinalRulesReverseFix", "FreedomFinalRulesPrivateEgressBlock", "UppercaseFreedomFinalRulesFix", "InboundRealityFinalmaskTcpStrip", "ApiTokensHash", "LegacyProxySettingsCleanup", "OutboundRemovedKeysFix", "FreedomDomainStrategyFix", "DNSOutboundLegacyKeysFix", "DNSOutboundQTypeZeroFix", "WireguardDomainStrategyFix", "XdnsFinalmaskObjectsFix", "WireguardPeersToClients", "MtprotoSecretsToClients", "NodeInboundsAdopted", "ResetIpLimitNoFail2ban"}
for _, name := range seeders {
if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil {
return err
@@ -1415,6 +1416,18 @@ func runSeeders(isUsersEmpty bool) error {
}
}
if !slices.Contains(seedersHistory, "WireguardDomainStrategyFix") {
if err := migrateWireguardDomainStrategy(); err != nil {
return err
}
}
if !slices.Contains(seedersHistory, "XdnsFinalmaskObjectsFix") {
if err := migrateXdnsFinalmaskObjects(); err != nil {
return err
}
}
if !slices.Contains(seedersHistory, "NodeInboundsAdopted") {
if err := seedNodeInboundsAdopted(); err != nil {
return err
@@ -1815,6 +1828,226 @@ var freedomDomainStrategies = map[string]bool{
"forceipv6": true, "forceipv4v6": true, "forceipv6v4": true,
}
func migrateWireguardDomainStrategy() error {
var setting model.Setting
err := db.Model(model.Setting{}).Where("key = ?", "xrayTemplateConfig").First(&setting).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return db.Create(&model.HistoryOfSeeders{SeederName: "WireguardDomainStrategyFix"}).Error
}
if err != nil {
return err
}
updated, changed, rErr := rewriteWireguardDomainStrategy(setting.Value)
if rErr != nil {
log.Printf("WireguardDomainStrategyFix: skip (invalid xrayTemplateConfig json): %v", rErr)
return db.Create(&model.HistoryOfSeeders{SeederName: "WireguardDomainStrategyFix"}).Error
}
return db.Transaction(func(tx *gorm.DB) error {
if changed {
if err := tx.Model(&model.Setting{}).Where("key = ?", "xrayTemplateConfig").
Update("value", updated).Error; err != nil {
return err
}
}
return tx.Create(&model.HistoryOfSeeders{SeederName: "WireguardDomainStrategyFix"}).Error
})
}
// rewriteWireguardDomainStrategy splits the settings.domainStrategy xray-core 26.9.30 (#6771)
// ignores: sockopt.domainStrategy now picks the endpoint's family, targetStrategy the targets'.
func rewriteWireguardDomainStrategy(raw string) (string, bool, error) {
if strings.TrimSpace(raw) == "" {
return raw, false, nil
}
var cfg map[string]any
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
return raw, false, err
}
outbounds, ok := cfg["outbounds"].([]any)
if !ok {
return raw, false, nil
}
changed := false
for _, ob := range outbounds {
obj, ok := ob.(map[string]any)
if !ok {
continue
}
if proto, _ := obj["protocol"].(string); !strings.EqualFold(proto, "wireguard") {
continue
}
settings, _ := obj["settings"].(map[string]any)
legacy, hasLegacy := settings["domainStrategy"]
remoteDNS, _ := settings["remoteDNS"].([]any)
localDNS := len(remoteDNS) == 1 && remoteDNS[0] == "local"
if !hasLegacy && !localDNS {
continue
}
delete(settings, "domainStrategy")
strategy, _ := legacy.(string)
if !wireguardFamilyStrategies[strings.ToLower(strategy)] {
strategy = ""
}
if strategy != "" {
if sockopt := outboundSockopt(obj, true); !strategyIsSet(sockopt["domainStrategy"]) {
sockopt["domainStrategy"] = strategy
}
}
if localDNS {
delete(settings, "remoteDNS")
if strategy == "" {
strategy = "ForceIP"
}
}
if strategy != "" && !strategyIsSet(obj["targetStrategy"]) {
obj["targetStrategy"] = strategy
}
changed = true
}
if !changed {
return raw, false, nil
}
out, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return raw, false, err
}
return string(out), true, nil
}
// wireguardFamilyStrategies are the old wireguard values that pinned an address family;
// plain ForceIP pinned none, and any other value already failed the old core's load.
var wireguardFamilyStrategies = map[string]bool{
"forceipv4": true, "forceipv6": true, "forceipv4v6": true, "forceipv6v4": true,
}
func strategyIsSet(value any) bool {
s, _ := value.(string)
return s != "" && !strings.EqualFold(s, "asis")
}
// migrateXdnsFinalmaskObjects upgrades every stored xdns mask to the object shape
// xray-core 26.9.30 requires, wherever the panel keeps a finalmask.
func migrateXdnsFinalmaskObjects() error {
return db.Transaction(func(tx *gorm.DB) error {
var inbounds []model.Inbound
if err := tx.Select("id", "stream_settings").Find(&inbounds).Error; err != nil {
return err
}
for _, inbound := range inbounds {
if updated, changed := upgradeLegacyXdnsJSON(inbound.StreamSettings, streamFinalmask, false); changed {
if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
Update("stream_settings", updated).Error; err != nil {
return err
}
}
}
var hosts []model.Host
if err := tx.Select("id", "final_mask").Find(&hosts).Error; err != nil {
return err
}
for _, host := range hosts {
if updated, changed := upgradeLegacyXdnsJSON(host.FinalMask, wholeFinalmask, false); changed {
if err := tx.Model(&model.Host{}).Where("id = ?", host.Id).
Update("final_mask", updated).Error; err != nil {
return err
}
}
}
var subs []model.OutboundSubscription
if err := tx.Select("id", "last_fetched_outbounds").Find(&subs).Error; err != nil {
return err
}
for _, sub := range subs {
if updated, changed := upgradeLegacyXdnsJSON(sub.LastFetchedOutbounds, outboundListFinalmasks, false); changed {
if err := tx.Model(&model.OutboundSubscription{}).Where("id = ?", sub.Id).
Update("last_fetched_outbounds", updated).Error; err != nil {
return err
}
}
}
for _, stored := range []struct {
key string
locate func(any) []any
indent bool
}{
{"xrayTemplateConfig", templateFinalmasks, true},
{"subJsonFinalMask", wholeFinalmask, false},
} {
var setting model.Setting
err := tx.Where("key = ?", stored.key).First(&setting).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
continue
}
if err != nil {
return err
}
if updated, changed := upgradeLegacyXdnsJSON(setting.Value, stored.locate, stored.indent); changed {
if err := tx.Model(&model.Setting{}).Where("key = ?", stored.key).
Update("value", updated).Error; err != nil {
return err
}
}
}
return tx.Create(&model.HistoryOfSeeders{SeederName: "XdnsFinalmaskObjectsFix"}).Error
})
}
// upgradeLegacyXdnsJSON rewrites the finalmasks locate finds in one stored JSON document,
// leaving the document byte-for-byte alone when nothing in it is legacy.
func upgradeLegacyXdnsJSON(raw string, locate func(any) []any, indent bool) (string, bool) {
if strings.TrimSpace(raw) == "" {
return raw, false
}
var doc any
if err := json.Unmarshal([]byte(raw), &doc); err != nil {
return raw, false
}
changed := false
for _, mask := range locate(doc) {
if maskcompat.UpgradeLegacyXdns(mask) {
changed = true
}
}
if !changed {
return raw, false
}
var out []byte
var err error
if indent {
out, err = json.MarshalIndent(doc, "", " ")
} else {
out, err = json.Marshal(doc)
}
if err != nil {
return raw, false
}
return string(out), true
}
func wholeFinalmask(doc any) []any { return []any{doc} }
func streamFinalmask(doc any) []any {
stream, _ := doc.(map[string]any)
return []any{stream["finalmask"]}
}
func outboundListFinalmasks(doc any) []any {
list, _ := doc.([]any)
finalmasks := make([]any, 0, len(list))
for _, entry := range list {
obj, _ := entry.(map[string]any)
finalmasks = append(finalmasks, streamFinalmask(obj["streamSettings"])...)
}
return finalmasks
}
func templateFinalmasks(doc any) []any {
cfg, _ := doc.(map[string]any)
return append(outboundListFinalmasks(cfg["inbounds"]), outboundListFinalmasks(cfg["outbounds"])...)
}
// migrateDNSOutboundLegacyKeys rewrites stored dns outbounds once, because the
// core logs nonIPQuery/blockTypes as deprecated on every config load.
func migrateDNSOutboundLegacyKeys() error {
@@ -0,0 +1,147 @@
package database
import (
"encoding/json"
"strings"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/config"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
const wgTestKeys = `"secretKey":"yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=","peers":[{"publicKey":"xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=","endpoint":"engage.cloudflareclient.com:2408"}]`
func TestRewriteWireguardDomainStrategy(t *testing.T) {
tests := []struct {
name string
outbound string
wantChanged bool
wantRoot string
wantSockopt string
wantDNS bool
}{
{
name: "the WARP default moves to both places the core now reads",
outbound: `{"protocol":"wireguard","tag":"warp","settings":{"domainStrategy":"ForceIPv4v6",` + wgTestKeys + `}}`,
wantChanged: true, wantRoot: "ForceIPv4v6", wantSockopt: "ForceIPv4v6",
},
{
name: "values the admin already set win over the legacy key",
outbound: `{"protocol":"wireguard","tag":"wg","targetStrategy":"UseIPv6","streamSettings":{"sockopt":{"domainStrategy":"UseIPv4"}},"settings":{"domainStrategy":"forceipv6",` + wgTestKeys + `}}`,
wantChanged: true, wantRoot: "UseIPv6", wantSockopt: "UseIPv4",
},
{
name: "plain ForceIP had no family preference, so only the key goes",
outbound: `{"protocol":"wireguard","tag":"wg","settings":{"domainStrategy":"ForceIP",` + wgTestKeys + `}}`,
wantChanged: true,
},
{
name: "remoteDNS local becomes targetStrategy, which resolves with the built-in DNS",
outbound: `{"protocol":"wireguard","tag":"wg","settings":{"domainStrategy":"ForceIPv4","remoteDNS":["local"],` + wgTestKeys + `}}`,
wantChanged: true, wantRoot: "ForceIPv4", wantSockopt: "ForceIPv4",
},
{
name: "remoteDNS local without a strategy resolves any family",
outbound: `{"protocol":"wireguard","tag":"wg","settings":{"remoteDNS":["local"],` + wgTestKeys + `}}`,
wantChanged: true, wantRoot: "ForceIP",
},
{
name: "a strategy the old core refused is dropped rather than moved",
outbound: `{"protocol":"wireguard","tag":"wg","settings":{"domainStrategy":"UseIPv4",` + wgTestKeys + `}}`,
wantChanged: true,
},
{
name: "IP remoteDNS entries stay",
outbound: `{"protocol":"wireguard","tag":"wg","settings":{"remoteDNS":["1.1.1.1"],` + wgTestKeys + `}}`,
wantChanged: false, wantDNS: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
updated, changed, err := rewriteWireguardDomainStrategy(`{"outbounds":[` + tc.outbound + `]}`)
if err != nil {
t.Fatalf("rewrite: %v", err)
}
if changed != tc.wantChanged {
t.Fatalf("changed = %v, want %v", changed, tc.wantChanged)
}
var cfg struct {
Outbounds []json.RawMessage `json:"outbounds"`
}
if err := json.Unmarshal([]byte(updated), &cfg); err != nil || len(cfg.Outbounds) != 1 {
t.Fatalf("rewritten template unreadable (%v): %s", err, updated)
}
var got struct {
TargetStrategy string `json:"targetStrategy"`
StreamSettings struct {
Sockopt struct {
DomainStrategy string `json:"domainStrategy"`
} `json:"sockopt"`
} `json:"streamSettings"`
Settings map[string]any `json:"settings"`
}
if err := json.Unmarshal(cfg.Outbounds[0], &got); err != nil {
t.Fatal(err)
}
if got.TargetStrategy != tc.wantRoot {
t.Errorf("targetStrategy = %q, want %q", got.TargetStrategy, tc.wantRoot)
}
if got.StreamSettings.Sockopt.DomainStrategy != tc.wantSockopt {
t.Errorf("sockopt.domainStrategy = %q, want %q", got.StreamSettings.Sockopt.DomainStrategy, tc.wantSockopt)
}
if _, kept := got.Settings["domainStrategy"]; kept {
t.Errorf("settings.domainStrategy survived the rewrite: %s", cfg.Outbounds[0])
}
if _, kept := got.Settings["remoteDNS"]; kept != tc.wantDNS {
t.Errorf("remoteDNS kept = %v, want %v", kept, tc.wantDNS)
}
if err := xray.ValidateOutboundConfig(cfg.Outbounds[0]); err != nil {
t.Fatalf("xray-core refuses the rewritten outbound: %v", err)
}
})
}
}
func TestWireguardDomainStrategySeederRewritesStoredTemplateOnce(t *testing.T) {
t.Setenv("XUI_DB_FOLDER", t.TempDir())
if err := InitDB(config.GetDBPath()); err != nil {
if strings.Contains(err.Error(), "CGO_ENABLED=0") {
t.Skipf("sqlite needs cgo: %v", err)
}
t.Fatalf("init db: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
legacy := `{"outbounds":[{"protocol":"wireguard","tag":"warp","settings":{"domainStrategy":"ForceIPv4v6",` + wgTestKeys + `}}]}`
seedTemplate(t, legacy)
if err := db.Where("seeder_name = ?", "WireguardDomainStrategyFix").
Delete(&model.HistoryOfSeeders{}).Error; err != nil {
t.Fatalf("clear seeder history: %v", err)
}
if err := runSeeders(false); err != nil {
t.Fatalf("runSeeders: %v", err)
}
var cfg struct {
Outbounds []struct {
TargetStrategy string `json:"targetStrategy"`
Settings map[string]any `json:"settings"`
} `json:"outbounds"`
}
if err := json.Unmarshal([]byte(storedTemplate(t)), &cfg); err != nil || len(cfg.Outbounds) != 1 {
t.Fatalf("stored template unreadable (%v)", err)
}
if _, kept := cfg.Outbounds[0].Settings["domainStrategy"]; kept || cfg.Outbounds[0].TargetStrategy != "ForceIPv4v6" {
t.Fatalf("stored outbound was not rewritten: %+v", cfg.Outbounds[0])
}
// The history gate keeps a hand-edited template from being rewritten on every restart.
seedTemplate(t, legacy)
if err := runSeeders(false); err != nil {
t.Fatalf("runSeeders: %v", err)
}
if got := storedTemplate(t); got != legacy {
t.Errorf("a completed seeder rewrote the template again: %s", got)
}
}
@@ -0,0 +1,116 @@
package database
import (
"encoding/json"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
const legacyXdnsFinalmask = `{"udp":[{"type":"xdns","settings":{"domains":["t.example.com"]}}]}`
// assertXdnsUpgraded fails unless the finalmask's xdns domains are objects, the only
// shape xray-core 26.9.30 parses.
func assertXdnsUpgraded(t *testing.T, where string, finalmask any) {
t.Helper()
fm, _ := finalmask.(map[string]any)
udp, _ := fm["udp"].([]any)
if len(udp) != 1 {
t.Fatalf("%s: udp masks = %v, want one", where, fm["udp"])
}
mask, _ := udp[0].(map[string]any)
settings, _ := mask["settings"].(map[string]any)
domains, _ := settings["domains"].([]any)
if len(domains) != 1 {
t.Fatalf("%s: domains = %v, want one entry", where, settings["domains"])
}
domain, ok := domains[0].(map[string]any)
if !ok || domain["name"] != "t.example.com" {
t.Fatalf("%s: domain = %#v, want an object named t.example.com", where, domains[0])
}
}
func TestXdnsFinalmaskSeederUpgradesEveryStoredMask(t *testing.T) {
initMigrateDB(t)
ib := seedInboundWithStream(t, "xdns-in", 5353,
`{"network":"kcp","security":"none","finalmask":`+legacyXdnsFinalmask+`}`)
host := &model.Host{InboundId: ib.Id, Remark: "h", Address: "cdn.example.com", Port: 53, FinalMask: legacyXdnsFinalmask}
if err := GetDB().Create(host).Error; err != nil {
t.Fatalf("create host: %v", err)
}
seedTemplate(t, `{"outbounds":[{"protocol":"vless","tag":"dns-tunnel","settings":{},"streamSettings":{"network":"kcp","finalmask":`+legacyXdnsFinalmask+`}}]}`)
if err := GetDB().Create(&model.Setting{Key: "subJsonFinalMask", Value: legacyXdnsFinalmask}).Error; err != nil {
t.Fatalf("seed subJsonFinalMask: %v", err)
}
sub := &model.OutboundSubscription{
Remark: "donor", Url: "https://donor.example.com/sub",
LastFetchedOutbounds: `[{"protocol":"vless","tag":"sub-1","settings":{},"streamSettings":{"network":"kcp","finalmask":` + legacyXdnsFinalmask + `}}]`,
}
if err := GetDB().Create(sub).Error; err != nil {
t.Fatalf("create outbound subscription: %v", err)
}
if err := GetDB().Where("seeder_name = ?", "XdnsFinalmaskObjectsFix").
Delete(&model.HistoryOfSeeders{}).Error; err != nil {
t.Fatalf("clear seeder history: %v", err)
}
if err := runSeeders(false); err != nil {
t.Fatalf("runSeeders: %v", err)
}
var stored model.Inbound
if err := GetDB().First(&stored, ib.Id).Error; err != nil {
t.Fatalf("reload inbound: %v", err)
}
var stream map[string]any
if err := json.Unmarshal([]byte(stored.StreamSettings), &stream); err != nil {
t.Fatalf("inbound stream is not JSON: %v", err)
}
assertXdnsUpgraded(t, "inbound stream", stream["finalmask"])
var storedHost model.Host
if err := GetDB().First(&storedHost, host.Id).Error; err != nil {
t.Fatalf("reload host: %v", err)
}
var hostMask any
if err := json.Unmarshal([]byte(storedHost.FinalMask), &hostMask); err != nil {
t.Fatalf("host finalMask is not JSON: %v", err)
}
assertXdnsUpgraded(t, "host finalMask", hostMask)
var template struct {
Outbounds []struct {
StreamSettings struct {
Finalmask any `json:"finalmask"`
} `json:"streamSettings"`
} `json:"outbounds"`
}
if err := json.Unmarshal([]byte(storedTemplate(t)), &template); err != nil || len(template.Outbounds) != 1 {
t.Fatalf("stored template unreadable (%v)", err)
}
assertXdnsUpgraded(t, "template outbound", template.Outbounds[0].StreamSettings.Finalmask)
var subMask model.Setting
if err := GetDB().Where("key = ?", "subJsonFinalMask").First(&subMask).Error; err != nil {
t.Fatalf("reload subJsonFinalMask: %v", err)
}
var subFinalmask any
if err := json.Unmarshal([]byte(subMask.Value), &subFinalmask); err != nil {
t.Fatalf("subJsonFinalMask is not JSON: %v", err)
}
assertXdnsUpgraded(t, "subJsonFinalMask", subFinalmask)
var storedSub model.OutboundSubscription
if err := GetDB().First(&storedSub, sub.Id).Error; err != nil {
t.Fatalf("reload outbound subscription: %v", err)
}
var cached []struct {
StreamSettings struct {
Finalmask any `json:"finalmask"`
} `json:"streamSettings"`
}
if err := json.Unmarshal([]byte(storedSub.LastFetchedOutbounds), &cached); err != nil || len(cached) != 1 {
t.Fatalf("cached subscription outbounds unreadable (%v)", err)
}
assertXdnsUpgraded(t, "cached subscription outbound", cached[0].StreamSettings.Finalmask)
}
+3
View File
@@ -15,6 +15,8 @@ import (
"strconv"
"strings"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/util/maskcompat"
)
// Outbound is the minimal shape we emit for each parsed link.
@@ -766,6 +768,7 @@ func applyFinalMask(stream map[string]any, p url.Values) {
var parsed any
if json.Unmarshal([]byte(fm), &parsed) == nil {
sanitizeFinalMaskQuicParams(parsed)
maskcompat.UpgradeLegacyXdns(parsed)
stream["finalmask"] = parsed
}
}
+19
View File
@@ -87,6 +87,25 @@ func TestParseVlessLink_FinalMaskQuicParamsSanitized(t *testing.T) {
}
}
// A panel older than xray-core 26.9.30 shares its xdns mask in the string lists the
// core no longer parses; imported verbatim, the outbound would fail the whole config.
func TestParseLink_UpgradesLegacyXdnsFinalMask(t *testing.T) {
fm := url.QueryEscape(`{"udp":[{"type":"xdns","settings":{"resolvers":["t.example.com+udp://8.8.8.8:53"]}}]}`)
res, err := ParseLink("vless://uuid@1.2.3.4:53?type=kcp&security=none&fm=" + fm + "#dns")
if err != nil {
t.Fatalf("parse vless with fm: %v", err)
}
stream, _ := res.Outbound["streamSettings"].(map[string]any)
got, err := json.Marshal(stream["finalmask"])
if err != nil {
t.Fatalf("marshal finalmask: %v", err)
}
want := `{"udp":[{"settings":{"domains":[{"edns0":1232,"name":"t.example.com","types":[16]}],"resolvers":[{"settings":{"addr":"8.8.8.8:53"},"type":"udp"}]},"type":"xdns"}]}`
if string(got) != want {
t.Fatalf("imported finalmask\n got: %s\nwant: %s", got, want)
}
}
func TestSanitizeFinalMaskQuicParams_ClampsAndRejects(t *testing.T) {
cases := []struct {
name string
+107
View File
@@ -0,0 +1,107 @@
package maskcompat
import "strings"
// legacyXdnsEDNS0 is the EDNS0 payload the pre-26.9.30 xdns always negotiated;
// the object shape makes it opt-in and caps every answer at 512 bytes without it.
const legacyXdnsEDNS0 = 1232
var legacyXdnsRecordTypes = map[string]int{"": 16, "txt": 16, "a": 1, "aaaa": 28}
// UpgradeLegacyXdns rewrites xdns masks from the string lists xray-core 26.9.30
// (#6718) no longer parses into its object lists; one legacy mask fails the whole config.
func UpgradeLegacyXdns(finalmask any) bool {
fm, _ := finalmask.(map[string]any)
masks, _ := fm["udp"].([]any)
changed := false
for _, entry := range masks {
mask, _ := entry.(map[string]any)
if maskType, _ := mask["type"].(string); !strings.EqualFold(maskType, "xdns") {
continue
}
if settings, ok := mask["settings"].(map[string]any); ok && upgradeLegacyXdnsSettings(settings) {
changed = true
}
}
return changed
}
// upgradeLegacyXdnsSettings maps a bare name to TXT, the type legacy clients queried by
// default, and drops entries the old core refused instead of keeping them to fail again.
func upgradeLegacyXdnsSettings(settings map[string]any) bool {
rawDomains, _ := settings["domains"].([]any)
rawResolvers, _ := settings["resolvers"].([]any)
if !hasLegacyXdnsEntry(rawDomains) && !hasLegacyXdnsEntry(rawResolvers) {
return false
}
domains := make([]any, 0, len(rawDomains)+len(rawResolvers))
listed := map[string]bool{}
addDomain := func(domain map[string]any) {
key, _ := domain["name"].(string)
key = strings.ToLower(key)
if key != "" && listed[key] {
return
}
listed[key] = true
domains = append(domains, domain)
}
for _, entry := range rawDomains {
switch value := entry.(type) {
case map[string]any:
addDomain(value)
case string:
if domain, ok := legacyXdnsDomain(value); ok {
addDomain(domain)
}
}
}
resolvers := make([]any, 0, len(rawResolvers))
for _, entry := range rawResolvers {
spec, ok := entry.(string)
if !ok {
resolvers = append(resolvers, entry)
continue
}
head, addr, found := strings.Cut(spec, "+udp://")
addr = strings.TrimSpace(addr)
domain, valid := legacyXdnsDomain(head)
if !found || addr == "" || !valid {
continue
}
addDomain(domain)
resolvers = append(resolvers, map[string]any{
"type": "udp",
"settings": map[string]any{"addr": addr},
})
}
settings["domains"] = domains
if len(resolvers) > 0 {
settings["resolvers"] = resolvers
} else {
delete(settings, "resolvers")
}
return true
}
// legacyXdnsDomain parses the "name[:txt|a|aaaa]" spec both legacy lists used.
func legacyXdnsDomain(spec string) (map[string]any, bool) {
name, method := strings.TrimSpace(spec), ""
if i := strings.LastIndex(name, ":"); i >= 0 {
name, method = name[:i], strings.ToLower(name[i+1:])
}
name = strings.Trim(name, ".")
recordType, known := legacyXdnsRecordTypes[method]
if name == "" || !known {
return nil, false
}
return map[string]any{"name": name, "types": []any{recordType}, "edns0": legacyXdnsEDNS0}, true
}
func hasLegacyXdnsEntry(values []any) bool {
for _, value := range values {
if _, ok := value.(string); ok {
return true
}
}
return false
}
+101
View File
@@ -0,0 +1,101 @@
package maskcompat
import (
"encoding/json"
"testing"
"github.com/xtls/xray-core/infra/conf"
)
// buildXdnsSettings runs an xdns mask's settings through conf.XDNS, the loader
// the core calls at startup, so the test's verdict is the core's verdict.
func buildXdnsSettings(t *testing.T, settings any) error {
t.Helper()
raw, err := json.Marshal(settings)
if err != nil {
t.Fatalf("marshal xdns settings: %v", err)
}
var mask conf.XDNS
if err := json.Unmarshal(raw, &mask); err != nil {
return err
}
_, err = mask.Build()
return err
}
func TestUpgradeLegacyXdns(t *testing.T) {
tests := []struct {
name string
mask string
want string
}{
{
name: "bare server domain becomes TXT with the legacy EDNS0 size",
mask: `{"type":"xdns","settings":{"domains":["t.example.com"]}}`,
want: `{"domains":[{"edns0":1232,"name":"t.example.com","types":[16]}]}`,
},
{
name: "method suffixes map to their record types",
mask: `{"type":"xdns","settings":{"domains":["a.example.com:a","q.example.com:AAAA","t.example.com:txt"]}}`,
want: `{"domains":[{"edns0":1232,"name":"a.example.com","types":[1]},{"edns0":1232,"name":"q.example.com","types":[28]},{"edns0":1232,"name":"t.example.com","types":[16]}]}`,
},
{
name: "client resolver splits into its domain and a udp resolver",
mask: `{"type":"XDNS","settings":{"resolvers":["t.example.com:a+udp://8.8.8.8:53"]}}`,
want: `{"domains":[{"edns0":1232,"name":"t.example.com","types":[1]}],"resolvers":[{"settings":{"addr":"8.8.8.8:53"},"type":"udp"}]}`,
},
{
name: "a resolver for an already listed domain adds no duplicate",
mask: `{"type":"xdns","settings":{"domains":["t.example.com"],"resolvers":["T.example.com+udp://1.1.1.1:53"]}}`,
want: `{"domains":[{"edns0":1232,"name":"t.example.com","types":[16]}],"resolvers":[{"settings":{"addr":"1.1.1.1:53"},"type":"udp"}]}`,
},
{
name: "entries the old core refused are dropped",
mask: `{"type":"xdns","settings":{"domains":["t.example.com","m.example.com:mx"],"resolvers":["1.1.1.1:53"]}}`,
want: `{"domains":[{"edns0":1232,"name":"t.example.com","types":[16]}]}`,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var mask map[string]any
if err := json.Unmarshal([]byte(tc.mask), &mask); err != nil {
t.Fatalf("unmarshal mask: %v", err)
}
if err := buildXdnsSettings(t, mask["settings"]); err == nil {
t.Fatal("the core accepted the legacy string shape; the upgrade is no longer needed")
}
finalmask := map[string]any{"udp": []any{mask}}
if !UpgradeLegacyXdns(finalmask) {
t.Fatal("UpgradeLegacyXdns reported no change for a legacy mask")
}
got, err := json.Marshal(mask["settings"])
if err != nil {
t.Fatalf("marshal upgraded settings: %v", err)
}
if string(got) != tc.want {
t.Fatalf("upgraded settings\n got: %s\nwant: %s", got, tc.want)
}
if err := buildXdnsSettings(t, mask["settings"]); err != nil {
t.Fatalf("the core refuses the upgraded settings: %v", err)
}
})
}
}
func TestUpgradeLegacyXdnsLeavesCurrentShapeAlone(t *testing.T) {
const current = `{"udp":[{"type":"xdns","settings":{"domains":[{"name":"t.example.com","types":[16,28],"edns0":1232}],"resolvers":[{"type":"tcp","settings":{"addr":"8.8.8.8:53"}}],"extraPoll":2}},{"type":"salamander","settings":{"password":"x"}}]}`
var finalmask map[string]any
if err := json.Unmarshal([]byte(current), &finalmask); err != nil {
t.Fatalf("unmarshal finalmask: %v", err)
}
if UpgradeLegacyXdns(finalmask) {
t.Fatal("UpgradeLegacyXdns rewrote a mask that is already in the object shape")
}
var want map[string]any
_ = json.Unmarshal([]byte(current), &want)
got, _ := json.Marshal(finalmask)
wantJSON, _ := json.Marshal(want)
if string(got) != string(wantJSON) {
t.Fatalf("finalmask changed\n got: %s\nwant: %s", got, wantJSON)
}
}
+22
View File
@@ -23,6 +23,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/mtproto"
"github.com/mhsanaei/3x-ui/v3/internal/tuic"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/util/maskcompat"
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
@@ -654,6 +655,27 @@ func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
return
}
inbound.StreamSettings = canonicalizeStreamNetworkKey(inbound.StreamSettings)
inbound.StreamSettings = canonicalizeLegacyXdnsMasks(inbound.StreamSettings)
}
// canonicalizeLegacyXdnsMasks stores an xdns mask posted in the pre-26.9.30 string
// lists in the object shape the core parses, as GetXrayConfig would heal it anyway.
func canonicalizeLegacyXdnsMasks(streamSettings string) string {
if streamSettings == "" {
return streamSettings
}
var stream map[string]any
if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
return streamSettings
}
if !maskcompat.UpgradeLegacyXdns(stream["finalmask"]) {
return streamSettings
}
out, err := json.MarshalIndent(stream, "", " ")
if err != nil {
return streamSettings
}
return string(out)
}
// canonicalizeStreamNetworkKey rewrites a streamSettings JSON that names its
@@ -0,0 +1,91 @@
package service
import (
"encoding/json"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
const legacyXdnsStream = `{"network":"kcp","security":"none","kcpSettings":{"mtu":900},"finalmask":{"udp":[{"type":"xdns","settings":{"domains":["t.example.com"]}}]}}`
func firstXdnsDomain(t *testing.T, stream map[string]any) any {
t.Helper()
finalmask, _ := stream["finalmask"].(map[string]any)
udp, _ := finalmask["udp"].([]any)
if len(udp) != 1 {
t.Fatalf("finalmask.udp = %v, want one mask", finalmask["udp"])
}
mask, _ := udp[0].(map[string]any)
settings, _ := mask["settings"].(map[string]any)
domains, _ := settings["domains"].([]any)
if len(domains) != 1 {
t.Fatalf("xdns domains = %v, want one", settings["domains"])
}
return domains[0]
}
// An API client can still post the pre-26.9.30 string lists; stored as sent they would
// reach the sub links and the form in a shape the core no longer parses.
func TestAddInbound_StoresXdnsMaskInObjectShape(t *testing.T) {
setupConflictDB(t)
in := &model.Inbound{
Tag: "in-45300-kcp", Enable: true, Listen: "0.0.0.0", Port: 45300, Protocol: model.VLESS,
Settings: `{"clients":[],"decryption":"none"}`, StreamSettings: legacyXdnsStream,
}
if _, _, err := (&InboundService{}).AddInbound(in); err != nil {
t.Fatalf("AddInbound: %v", err)
}
var stored model.Inbound
if err := database.GetDB().Where("tag = ?", "in-45300-kcp").First(&stored).Error; err != nil {
t.Fatalf("reload: %v", err)
}
var stream map[string]any
if err := json.Unmarshal([]byte(stored.StreamSettings), &stream); err != nil {
t.Fatalf("stored stream is not JSON: %v", err)
}
domain, ok := firstXdnsDomain(t, stream).(map[string]any)
if !ok || domain["name"] != "t.example.com" {
t.Fatalf("stored xdns domain = %#v, want an object named t.example.com", firstXdnsDomain(t, stream))
}
}
// A row that never went through the save path (restored backup, node sync, direct DB
// edit) must still reach the core in a shape it builds, or it keeps every inbound down.
func TestGetXrayConfig_UpgradesLegacyXdnsMask(t *testing.T) {
setupConflictDB(t)
seedInboundConflict(t, "in-45301-kcp", "127.0.0.1", 45301, model.VLESS,
legacyXdnsStream, `{"clients":[],"decryption":"none"}`)
var legacy map[string]any
if err := json.Unmarshal([]byte(`{"tag":"in-45301-kcp","listen":"127.0.0.1","port":45301,"protocol":"vless",
"settings":{"clients":[],"decryption":"none"},"streamSettings":`+legacyXdnsStream+`}`), &legacy); err != nil {
t.Fatalf("decode legacy inbound: %v", err)
}
if err := buildGoldenInbound(t, legacy); err == nil {
t.Fatal("xray-core accepted the legacy xdns lists; the heal is no longer needed")
}
cfg, err := (&XrayService{}).GetXrayConfig()
if err != nil {
t.Fatalf("GetXrayConfig: %v", err)
}
for i := range cfg.InboundConfigs {
if cfg.InboundConfigs[i].Tag != "in-45301-kcp" {
continue
}
raw, err := json.Marshal(cfg.InboundConfigs[i])
if err != nil {
t.Fatalf("marshal emitted inbound: %v", err)
}
var emitted map[string]any
if err := json.Unmarshal(raw, &emitted); err != nil {
t.Fatalf("decode emitted inbound: %v", err)
}
assertXrayAccepts(t, "the healed xdns inbound", buildGoldenInbound(t, emitted))
return
}
t.Fatal("inbound in-45301-kcp not found in the generated config")
}
+4
View File
@@ -17,6 +17,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
"github.com/mhsanaei/3x-ui/v3/internal/util/maskcompat"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
"go.uber.org/atomic"
@@ -366,6 +367,9 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
logger.Warningf("Inbound %q: dropping %d XMC finalmask mask(s) without complete Minecraft profiles — reconfigure them to restore the obfuscation (see XTLS/Xray-core#6487)", inbound.Tag, dropped)
}
// A row that skipped the save path can still carry the pre-26.9.30 xdns lists.
maskcompat.UpgradeLegacyXdns(stream["finalmask"])
// xray-core v26.6.22 (#6258) renamed the XHTTP session keys and
// kept no fallback. Lift legacy sessionPlacement/sessionKey onto the
// new names here so inbounds stored before the rename keep working
+28 -2
View File
@@ -9,6 +9,7 @@ import (
"fmt"
"math"
"net"
"net/netip"
"os"
"path/filepath"
"regexp"
@@ -182,8 +183,33 @@ func ValidateOutboundConfig(outbound []byte) error {
if err := json.Unmarshal(outbound, detour); err != nil {
return err
}
_, err := detour.Build()
return err
built, err := detour.Build()
if err != nil {
return err
}
return validateWireguardRemoteDNS(built.ProxySettings)
}
// validateWireguardRemoteDNS refuses what conf.Build() lets through but the core feeds to
// netip.MustParseAddr at startup: a non-IP remoteDNS entry, like "local" before 26.9.30.
func validateWireguardRemoteDNS(settings *serial.TypedMessage) error {
if settings == nil {
return nil
}
instance, err := settings.GetInstance()
if err != nil {
return nil
}
device, ok := instance.(*wireguard.DeviceConfig)
if !ok || !device.IsClient {
return nil
}
for _, server := range device.DNS {
if _, err := netip.ParseAddr(server); err != nil {
return common.NewErrorf("wireguard remoteDNS entry %q is not an IP address", server)
}
}
return nil
}
// AddOutbound adds a new outbound configuration to the Xray core via gRPC.
+25
View File
@@ -40,3 +40,28 @@ func TestValidateOutboundConfig_RejectsUnencryptedPublicVless(t *testing.T) {
t.Fatalf("a TLS-secured public vless outbound must stay valid, got: %v", err)
}
}
// The core feeds remoteDNS to netip.MustParseAddr when it creates the outbound, so a
// non-IP entry ("local" until 26.9.30) panics it at startup; conf.Build() lets it through.
func TestValidateOutboundConfig_RejectsWireguardRemoteDNSThatIsNotAnIP(t *testing.T) {
outbound := func(remoteDNS string) []byte {
return []byte(`{
"protocol": "wireguard",
"settings": {
"secretKey": "yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=",
"address": ["10.0.0.2/32"],
"peers": [{"publicKey": "xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=", "endpoint": "162.159.192.1:2408"}],
"remoteDNS": ` + remoteDNS + `
}
}`)
}
for _, rejected := range []string{`["local"]`, `["1.1.1.1", "dns.google"]`} {
err := ValidateOutboundConfig(outbound(rejected))
if err == nil || !strings.Contains(err.Error(), "remoteDNS") {
t.Errorf("remoteDNS %s: want a remoteDNS refusal, got %v", rejected, err)
}
}
if err := ValidateOutboundConfig(outbound(`["1.1.1.1", "2606:4700:4700::1111"]`)); err != nil {
t.Fatalf("IP remoteDNS entries must stay valid, got: %v", err)
}
}