Skip to content

TUN inbound: Add autoSystemDNS on Linux (to TUN's gateway) - #6773

Merged
RPRX merged 8 commits into
XTLS:mainfrom
youugiuhiuh:feat/tun-linux-system-dns
Sep 27, 2026
Merged

RPRX merged 8 commits into
XTLS:mainfrom
youugiuhiuh:feat/tun-linux-system-dns

Conversation

@youugiuhiuh

@youugiuhiuh youugiuhiuh commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Why

The Linux TUN inbound never configures system DNS, so name lookups keep going out over the physical link even while all routing is redirected into the TUN. That is the leak reported in #6454.

This is not a new behaviour being introduced. Windows has been doing exactly this for a while:

// proxy/tun/tun_windows.go
185:  err = t.luid.SetDNS(family, dns, nil)      // Start
229:  t.luid.FlushDNS(windows.AF_INET)          // Close

Linux simply lacked the equivalent, which is why the two platforms behave differently. This change brings Linux in line with Windows rather than adding a capability that does not exist elsewhere.

@RPRX suggested this approach in #6454:

或许修改系统 DNS 为 TUN 的 gateway(直接发给 Xray)可以解决问题?

@yiguodev tested it on macOS and found it did not work there (实测无效), and noted Linux was unverified:

  1. Linux 可通过 D-Bus 接管系统 DNS,未验证。

This PR covers that Linux case. It works here because systemd-resolved has a default-route flag that makes the interface's resolver the system default, which scutil --dns on macOS does not provide.

Worth noting separately: the README states Linux and macOS do not configure system DNS from the dns field, but Windows does not follow that either — tun_windows.go reads options.DNS and pushes it to the adapter. The README wording is inaccurate for Windows. I left it untouched here to keep the diff focused.

What

Start() points systemd-resolved at the TUN interface, Close() hands DNS back:

Start Close
resolvectl dns <iface> <addr> resolvectl revert <iface>
resolvectl domain <iface> "~."
resolvectl default-route <iface> true

The address handed to systemd-resolved

It is the first IPv4 gateway incremented by one — for gateway: ["192.168.100.1/30"] that is 192.168.100.2.

That address belongs to the TUN and is answered inside Xray, so lookups actually travel the tunnel:

$ ip route get 192.168.100.2
192.168.100.2 dev xray_tun src 192.168.100.1

Passing the configured resolvers from options.DNS verbatim — as Windows does — would not work here: resolvectl dns <iface> 1.1.1.1 makes systemd-resolved query 1.1.1.1:53 directly over the physical link, which is the very leak this is meant to close. Hence the gateway-derived address rather than the configured one.

Failure handling

Configuring DNS is best-effort and never blocks startup:

  • resolvectl absent (non-systemd host) → exec.ErrNotFound → logged, skipped
  • no IPv4 gateway → skipped
  • command error → logged, TUN still comes up
  • setSystemDNS / unsetSystemDNS are idempotent via a systemDNSSet flag; ifaceName() guards a nil link

Platform scope: systemd-resolved only

This change depends entirely on resolvectl, so it actually takes over system DNS only when all of the following hold:

  • the system is a systemd distribution and resolvectl is in PATH
  • systemd-resolved is enabled and actually managing DNS (installed but not running has no effect)
  • systemd-resolved version ≥ 240 — the default-route subcommand is available from 240 onward

When any of these is not met, the code takes the degraded path and skips safely (logs, does not block TUN startup) — but the DNS leak remains. This is fail-safe, not portable.

Environment Behaviour
Ubuntu / Debian / Fedora / RHEL (systemd-resolved enabled) ✅ takes over
Arch / Gentoo (systemd-resolved installed and enabled manually) ✅ takes over
Alpine, Void, Devuan, OpenRC-based ❌ no resolvectl → skipped
OpenWrt (dnsmasq) ❌ no resolvectl → skipped
DNS managed by dnsmasq / unbound / BIND / static /etc/resolv.conf ❌ resolvectl cannot reach it
NetworkManager managing DNS directly (not via resolved) ❌ no effect
Containers (no systemd-resolved daemon) ❌ no effect
systemd < 240 ⚠️ dns may succeed, default-route fails → partial takeover

Covering non-systemd systems would require writing resolv.conf directly, or adapting to dnsmasq / unbound. Covering applications that bring their own DoH would require nftables DNAT hijacking of port 53 (more general, since it does not depend on the upper DNS manager). Neither is in this patch.

Change scope

Single file for the implementation, plus its test file. No config or proto changes: options.DNS and Gateway already exist and are already plumbed through infra/conf.

No nftables DNAT hijack is included. Windows does not do one either (it uses WFP), so adding one here would exceed parity with the existing Windows behaviour.

Verification

proxy/tun/tun_linux_dns_test.go — 7 tests covering address derivation, argument construction, idempotency, and the missing-resolvectl / no-gateway / nil-link paths:

--- PASS: TestHandlerCountsTunConnectionTraffic
--- PASS: TestSetSystemDNSNoGateway
--- PASS: TestSetSystemDNSMissingResolvectl
--- PASS: TestSetSystemDNSCallsResolvectl
--- PASS: TestUnsetSystemDNSReverts
--- PASS: TestSystemDNSAddress
--- PASS: TestBuildResolvectlArgs
ok  github.com/xtls/xray-core/proxy/tun

gofmt and go vet clean. Cross-compiles for all common Linux targets:

GOOS=linux GOARCH=amd64 / arm64 / 386 / arm   # all OK

Tested live on Ubuntu 24.04 with systemd-resolved + NetworkManager. systemd-resolved accepts the D-Bus writes:

systemd-resolved: xray_tun: Bus client set DNS server list to: 192.168.100.2
systemd-resolved: xray_tun: Bus client set search domain list to: ~.
systemd-resolved: xray_tun: Bus client set default route setting: yes

resolvectl status confirms the interface claimed DNS, and after shutdown the interface is removed and DNS reverts to the physical link.

DNS leak test (browserleaks), before → after:

before (leaking) after (fixed)
leaking fixed

Before, a run of local ISP (China) resolvers appears alongside the overseas ones. After, the resolvers are exclusively overseas (Google LLC US / Cloudflare US) — the local resolvers are gone. Full verification notes: docs/2026-09-14-tun-linux-system-dns.md

Out of scope

  • Non-systemd systems: no resolvectl, so the code skips and the leak remains (see Platform scope above). Would need direct resolv.conf writes or dnsmasq/unbound adapters.
  • Application-level DoH: an app with its own hardcoded DoH endpoint still bypasses the system resolver. As @RPRX noted in tun模式存在dns泄漏 #6454, the leak is 系统层面的而非应用层面的; closing that would need the nftables hijack deliberately left out of this change.
  • SIGKILL cleanup: a process cannot handle SIGKILL, so an abrupt kill leaves the entry until resolvectl revert runs. That needs an external supervisor and is not part of this change.

The Linux TUN implementation never touched system DNS, so name lookups
continued to go out over the physical link even while routing was
redirected into the TUN. Windows has configured system DNS from the
`dns`/gateway settings for a while (tun_windows.go SetDNS/FlushDNS);
Linux simply lacked the equivalent, which left DNS leaking.

Point systemd-resolved at the TUN interface on Start and hand it back on
Close. The address handed over is the first IPv4 gateway incremented by
one: that address belongs to the TUN and is answered inside Xray, so
lookups actually travel the tunnel. Passing the configured public
resolvers instead would leave the system querying them directly over the
physical link, which is the leak this is meant to close.

Failure to configure is non-fatal. Hosts without resolvectl, or without
an IPv4 gateway, keep the previous behaviour instead of failing to start.
@RPRX
RPRX requested review from LjhAUMEM and yiguodev September 17, 2026 20:22
@LjhAUMEM

Copy link
Copy Markdown
Contributor

为啥request我
这相当于默认修改系统DNS还不加配置项
@yiguodev 你来看吧

@yiguodev

Copy link
Copy Markdown
Collaborator

Thanks for working on this. I reviewed 321494da against its merge-base c412e77a, and checked the D-Bus approach against upstream systemd v255 and godbus v5.2.2.

Standards

1. Medium: interface addressing now implicitly takes over system DNS

Location: tun_linux.go:112–123 and Start():302–308.

The existing TUN contract says:

system DNS remains managed by the OS or distribution-specific network services

On the self-created TUN path, configuring an IPv4 gateway now also changes the link's DNS server, routing domain to ~., and DNS default-route setting, without a separate opt-in. An option previously used to assign interface addresses therefore gains a host-wide DNS-routing side effect. The externally supplied FD path is unchanged and is not part of this finding.

Please preserve OS-managed DNS by default, introduce an explicit opt-in, and update the README to explain the takeover conditions and cleanup behavior.

2. Low: possible speculative generality in the error interface

Location: setSystemDNS / unsetSystemDNS and the new rollback branch in Start().

Both methods return nil on every path, including command failures, but Start() has a full rollback branch for a non-nil setSystemDNS() error. That branch cannot currently execute.

This is a maintainability/code-smell judgment, not a hard style-rule violation. Under the stated best-effort policy, these internal methods could return no value, with the unreachable rollback branch removed.

Spec

1. High: routing to gateway + 1 does not establish a DNS service there

The PR states:

That address belongs to the TUN and is answered inside Xray

The current data path does not guarantee this:

For example, with gateway: ["192.168.100.1/30"], a default proxy outbound, and no DNS-specific routing rule, the newly redirected queries are forwarded toward 192.168.100.2:53 on the proxy side, rather than answered by an internal DNS service. This can break previously working system resolution. Setting options.DNS does not help this new path, because it is not used here.

An explicit DNS outbound/routing rule can supply the missing path, but the PR neither declares nor validates that prerequisite. Before changing system DNS, ensure that the advertised address actually has a working DNS handling path; otherwise leave system DNS unchanged. Please add an end-to-end DNS-query test, not only command-argument assertions.

Non-systemd hosts, application DoH, and SIGKILL cleanup are explicitly out of scope and are not counted as missing features.

D-Bus / godbus recommendation

This PR already uses D-Bus indirectly: resolvectl is a client of systemd-resolved. If Core is to manage DNS, I would prefer an optional backend using github.com/godbus/dbus/v5 directly:

  • It is native Go and removes the CLI executable/PATH dependency and subprocess creation.
  • It provides structured D-Bus errors and CallWithContext for call deadlines.
  • It adds a Go dependency and requires explicit connection/lifecycle management. ConnectSystemBus() gives the component its own connection; do not close the shared connection returned by SystemBus().

The resolved Manager API provides SetLinkDNS, SetLinkDomains, SetLinkDefaultRoute, and RevertLink, using the interface index, not its name. The CLI's ~. becomes the D-Bus domain record (".", true), not the literal string "~.". Basic SetLinkDNS is sufficient for the bare IP addresses used here; v255's CLI also supports the extended SetLinkDNSEx method.

Important caveats:

  1. Authorization is not solved by changing libraries. An ordinary exec child does not automatically retain a non-root Core's effective file capabilities (capabilities(7)). Direct calls avoid that exec boundary, but do not assume CAP_NET_ADMIN guarantees resolved authorization. In v255, sender privilege checks reject /proc-augmented capabilities for authorization; normal system-bus credentials do not reliably provide the effective-capability set. Actual bus/polkit policy still needs deployment-specific verification.
  2. This is not a drop-in replacement for every CLI behavior. For example, v255 resolvectl can fall back to systemd-networkd on LinkBusy. Preserve that behavior or explicitly narrow the supported backend. D-Bus does not automatically add support for unrelated DNS managers.
  3. Calls are not a transaction. Track partial application and define failure/exit cleanup. A context timeout does not prove that the server did not apply a change. Closing the bus connection does not undo DNS settings, and RevertLink resets per-link settings to defaults rather than restoring an arbitrary previous snapshot.

Direct godbus calls would improve the control-plane implementation, but would not create the missing DNS data path or replace explicit opt-in and cleanup.

Verification

All six new top-level DNS tests, including their table-driven cases, passed with the command runner mocked or skipped. I did not perform live DNS takeover/leak tests or authorization tests on a deployed system. The data-path finding above is based on source tracing, not a claimed packet-capture reproduction.

Review summary: Standards: 2 findings, worst medium (DNS ownership/compatibility contract). Spec: 1 finding, worst high (no guaranteed DNS service at the advertised address).

@youugiuhiuh

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review — the Spec #1 finding is correct, and I had misstated the guarantee.

I traced the three paths you cited (stack_gvisor.go preserves the destination, handler.go hands it to DispatchLink, and dispatcher/default.go falls back to the default outbound when PickRoute fails), and confirmed it against my own test config: it only worked because that config happened to carry inboundTag: [tun], port: 53 → outboundTag: dns together with a protocol: dns outbound. Without that rule the queries would have gone to the proxy. The PR neither declared nor validated that prerequisite, and the description's claim was wrong.

Plan to address all three findings:

  1. Opt-in — take over system DNS only when explicitly enabled in the TUN config; otherwise leave OS-managed DNS alone, preserving the documented contract.
  2. Validate the data path before changing anything — confirm a dns-protocol outbound is actually registered; if it is not, skip and log instead of redirecting resolution into an address nothing answers.
  3. Document the prerequisite — README to state the required routing rule and the cleanup behaviour.
  4. Standards fallbacks在核心内部不通过tcp或者domainsocket传输的可能性? #2 — drop the always-nil returns and the unreachable rollback branch in Start().
  5. End-to-end test — assert a real query reaches the internal DNS path, not only the command arguments.

On the D-Bus recommendation: I agree it is the better control plane and would remove the resolvectl PATH and subprocess dependency. I would prefer to handle that as a follow-up so this PR stays reviewable, unless you would rather it land here. Noted on (".", true) for the domain record, link index vs name, and RevertLink resetting to defaults rather than restoring an arbitrary snapshot — plus the point that changing libraries does not by itself solve authorization.

I will push the fixes above to this branch.

The previous revision pointed systemd-resolved at the interface whenever an
IPv4 gateway was configured, with no opt-in and no check that the address
actually answered. Both are wrong: a config that never asked for host DNS
changes would be affected, and since the interface's own routes and the
routing rules are separate things, pointing the system resolver at an address
with no DNS handling path breaks resolution outright.

Gate the takeover behind a new autoSystemDNS field, default false, and verify
the data path first: a query to the derived address is routed through the
configured rules, and host DNS is only changed when the result is a
DNS-capable outbound. Otherwise the option does nothing and DNS is left to
the OS.

The call moves to the inbound handler, which has the context the routing
check needs, reached through an optional interface so the Tun interface and
the other platforms are untouched. A failure part-way through reverts rather
than leaving a half-configured resolver.

Also drops the always-nil returns flagged in review, and documents the
prerequisites, platform coverage and cleanup behaviour in the README.
@youugiuhiuh

Copy link
Copy Markdown
Contributor Author

Pushed the fixes from my earlier reply.

Spec #1 (High) — reproduced first, then fixed

I was able to reproduce the failure you described. With gateway: ["192.168.100.1/30"], no DNS routing rule, and the previous revision, the takeover still happened and the queries were forwarded on the proxy side:

Link 7 (xray_dnstest)
Current DNS Server: 192.168.100.2

app/dispatcher: default route for udp:192.168.100.2:53
proxy/freedom: connection opened to udp:192.168.100.2:53
from udp:192.168.100.1:xxxxx accepted udp:192.168.100.2:53 [tun >> direct]

[tun >> direct] is exactly the case you called out — nothing answers that address, so resolution breaks outright. The previous revision also did this with no opt-in at all, so a config that never asked for host DNS changes was affected too.

The same config on the revised version:

proxy/tun: [tun] system DNS not configured >
           no DNS path at 192.168.100.2:53 >
           no route for 192.168.100.2:53 >
           common: not enough information for making a decision
proxy/tun: xray_dnstest up

Host DNS is left alone and the TUN still comes up. With the routing rule present, verification passes and the path is [tun -> dns] → proxy/dns: handling DNS traffic → app/dns: UDP:1.1.1.1:53 got answer, so the redirect is only applied when it actually works.

previous revised
opt-in none autoSystemDNS, default false
pre-check none route the derived address, require a DNS outbound
no DNS route takes over, queries go [tun >> direct] skips, host DNS untouched
with DNS route works works

What changed

  • autoSystemDNS (bool, default false) gates the takeover. A new field rather than reusing dns, because existing configs already set dns and would otherwise start changing host DNS implicitly.
  • Before touching host DNS, a query to the derived address is routed via Router.PickRoute with the inbound tag and target. The takeover proceeds only when the chosen outbound's ProxySettings().Type is the DNS config; otherwise it skips.
  • The call moved to the inbound handler, which has the context the routing check needs, reached through an optional interface — the Tun interface and the other platforms are untouched.
  • Standards fallbacks在核心内部不通过tcp或者domainsocket传输的可能性? #2: the always-nil returns are gone. The methods now report real failures, and they are meaningful — the skip shown above is exactly a returned error that the caller logs and continues past, rather than an unreachable rollback branch.
  • A failure part-way through the sequence reverts instead of leaving a half-applied resolver.
  • README documents the opt-in, the prerequisites (including the required routing rule), platform coverage and cleanup behaviour.

Verification: 7 tests covering gating, the verification skip, idempotency, rollback and the degrade paths; cross-compiled for linux amd64/arm64/386/arm plus darwin/windows/freebsd; and the live runs above on Ubuntu 24.04 with systemd-resolved.

Still open, as noted before: the godbus backend. I would prefer to do that as a follow-up rather than grow this diff further, unless you would rather it land here.

@yiguodev

Copy link
Copy Markdown
Collaborator

Thanks for the follow-up. I re-reviewed the full PR at ecec2d8d578bc621796030d5f57e7632622af30e, against merge-base c412e77a9b712082ac9ebf27fa793951cb5a7d85, and then ran the real Linux DNS path twice.

The explicit opt-in/default-off behavior, updated prerequisites, and removal of the always-nil error interface address the previous Standards findings. The no-DNS-route case is now guarded, but the broader guarantee that an accepted configuration has a working DNS path remains incomplete. Deferring godbus to a follow-up is fine; I am not counting it as a missing requirement.

Standards

1. Medium: the verification context does not satisfy the documented routing contract

tun_linux.go:118–123 constructs only:

&session.Inbound{Name: "tun", Tag: inboundTag}

The README contract says the advertised address must actually answer and takeover is verified first. However, real TUN requests include Source, whereas this probe does not. A source-specific rule before the generic TUN/53 rule can therefore select a different outbound for the real request. This is now reproduced on the actual data path, not just inferred from source.

Please make the verification representative of the routing inputs that actual system queries use, or decline takeover when that guarantee cannot be established.

2. Low, non-blocking: possible Duplicated Code in the command fixtures

tun_linux_dns_test.go:35–62 repeats the save/install/record/restore sequence in two helpers, including calls = append(calls, append([]string{name}, args...)) and the t.Cleanup restoration. Only the failure condition differs.

A single recorder with an optional failing subcommand would avoid maintaining both copies. This is a code-smell judgment, not a hard repository-rule violation.

Spec

1. High: a DNS outbound can still depend on the resolver being taken over

The revised promise is “the redirect is only applied when it actually works”.

The protocol-type check does not establish an independent resolver. Without top-level DNS configuration, Core installs localdns. The DNS outbound's A/AAAA lookup then uses the system resolver, producing this dependency cycle in a resolved-stub deployment:

resolved → TUN → Xray DNS outbound → system resolver stub → resolved

Please require/check an upstream path independent of the resolver being changed; otherwise leave system DNS untouched.

2. High: the preflight route can differ from the actual query route

The same promise, “only applied when it actually works”, is not met by the source-less probe.

Prepending a rule for source 169.254.231.1/32 → blackhole, before TUN/53 → DNS, let preflight pass while the real system query selected blackhole. Please guarantee the actual DNS handling path, not merely one synthetic route, and cover source-dependent routing in regression tests.

3. Medium: failed rollback loses pending-cleanup state

The stated behavior is “A failure part-way through the sequence reverts”.

At tun_linux.go:177–195, revert errors are discarded and systemDNSSet remains false after partial application, so subsequent cleanup skips it. Track partial/dirty state, report rollback failure, and retain a retry opportunity.

4. Medium: the promised end-to-end regression test is still missing

The plan explicitly included “assert a real query reaches the internal DNS path”.

Your manual live check is useful, but the committed tests replace the verifier itself. Their command assertions cannot catch the above false positives. Please add automated request/routing/response coverage for these cases.

Real-system validation: two consecutive runs

This used Linux ARM64, systemd-resolved 259, and the pinned PR binary built with Go 1.27.1, CGO disabled. I derived the test configurations from a working VLESS/XHTTP configuration, retaining its real outbounds and independent DNS upstream for the controls.

The tests exercised real TUN/gVisor traffic, the actual router and DNS outbound, real resolvectl subprocesses, and a real resolved daemon—no mocked routing verifier or command runner.

To avoid breaking the host's DNS, the test used private mount/PID namespaces, a private system bus, and a separate resolved instance. It shared the host network namespace for real external connectivity. Only the test processes used the private stub 127.0.0.67; the test TUN had 169.254.231.1/30, advertising 169.254.231.2, with no default IP-route takeover.

Each matrix started and ended with a healthy control and fresh test processes. The DNS probe was dig example.com A +time=4 +tries=1 through the namespace's default resolver configuration.

Case Run 1 Run 2
Keep independent DNS + TUN/53 → DNS NOERROR, 2 answers NOERROR, 2 answers
Remove only the global DNS section Takeover accepted; timeout at 4.011 s Takeover accepted; timeout at 4.013 s
Prepend source-IP → blackhole rule Takeover accepted; actual route was blackhole; timeout at 4.013 s Same, timeout at 4.008 s
Deny default-route and revert via private-bus ACLs Core reports DNS not configured, but DNS address and ~. remain installed Same
Restore healthy control NOERROR, 2 answers NOERROR, 2 answers

Additional observations:

  • In the system-resolver case, actual traffic reached the DNS outbound, and the Core logged lookups of the test domain through 127.0.0.67:53 failing with i/o timeout. This corroborates the dependency cycle; it is not a claim of unlimited packet amplification.
  • The rollback case used genuine D-Bus access denials deliberately injected into the private bus policy, not a fake resolvectl executable. DNS/domain writes succeeded. Each run recorded one rejected default-route call and one rejected revert call across the complete case, including shutdown; no later revert retry was observed. The partial settings remained while Core was running. Removing its TUN on exit removed the per-link state; I am not claiming permanent DNS damage after shutdown.
  • All healthy controls also returned HTTPS 204 through a loopback SOCKS inbound using the original proxy outbound. That checks proxy connectivity; it is not a full-tunnel HTTP test.
  • The approximately four-second failures are the probe's client timeout. All ten test Core instances remained alive during their query checks and subsequently exited 0. Test TUNs disappeared, and before/after checks confirmed the original host DNS configuration, routes/rules, source configuration and existing processes were preserved.

The nine top-level DNS unit tests also passed, but they do not replace the above data-path checks. These results concern this pinned revision and these scenarios; they do not establish authorization against the host's normal polkit/file-capability policy, non-systemd behavior, or general DNS-leak coverage. Private configurations, credentials and raw endpoint-bearing logs are intentionally not included.

Review summary: Standards: 2 findings, worst medium (documented verification contract). Spec: 4 findings, worst high (accepted takeover can still break resolution). The three behavioral findings reproduced in both real-system runs.

…back

Three findings from review:

The preflight probe was source-less, so a rule matching a source address could
select a different outbound for the real queries than it did for the probe.
The probe now carries the interface address as its source, which is what a real
query from this interface presents.

Without a DNS section Core installs a resolver that forwards to the system
resolver. Pointing the system resolver at the TUN then closes a loop through
the DNS outbound and resolution stops, but the old probe passed anyway because
the system resolver was still healthy at probe time. The takeover is now
refused when the DNS feature is that system-resolver client.

A failed revert was discarded and the state flag cleared, so partially applied
per-link settings could outlive the attempt to remove them. A dirty flag now
records that, is reported, and is retried before the next takeover.

Also merges the two duplicated test-record helpers.
Callers about to redirect the system resolver need to know whether the DNS
feature would then resolve through it and loop back. That is the case both when
no name server is configured at all and when every configured one is the local
client, but only the first shape is visible from outside the package.

The TUN preflight now uses it, so a `dns` section without name servers is
refused the same way a missing section already was.
@youugiuhiuh

Copy link
Copy Markdown
Contributor Author

Pushed three commits. Status of each finding, then the real-machine results.

Standards #1 / Spec #2 — the probe was source-less

Reproduced your case first: with a source 192.168.100.1/32 -> block rule ahead of tun:53 -> dns, the old probe passed while the real queries went to block. The probe now carries the interface address as its source, which is what a real query from this interface presents, and it takes a representative ephemeral port. A source-port-matching rule is still not reproducible ahead of time; I say so below.

Spec #1 — the loop

Reproduced too. With no dns section, Core installs a client that forwards to the system resolver, so redirecting the system resolver at the TUN closes a loop through the DNS outbound — and the old probe passed anyway, because at probe time the system resolver was still healthy. The takeover is now refused when the DNS feature is that client.

There are two shapes of the same problem, and only one is visible from outside app/dns:

  • no dns section at all → Core installs localdns, detectable directly;
  • a dns section with no name servers → app/dns falls back to the same thing internally.

The second needed a small read-only accessor, so this adds app/dns.DNS.UsesSystemResolver() (and one test for it). Both shapes are now refused. Adding a package is a scope change, so flagging it explicitly — if you would rather keep the change inside proxy/tun, say so and I will drop the second shape.

Spec #3 — rollback state

A failed revert was discarded and the state flag cleared, so partially applied per-link settings could outlive the attempt to remove them. There is now a dirty flag: a failed rollback is recorded rather than swallowed, it is reported, and the next takeover retries the revert before applying anything.

Standards #2

The two recording helpers are merged into one with an optional failing subcommand.

Spec #4 — not done yet

You are right that the committed tests replace the verifier, so they cannot catch these false positives. I am adding coverage that builds a real instance with core.New() and real routing rules and asserts what the verifier decides, rather than substituting the verifier itself. That is in progress; this push does not contain it.

Real-machine results

Four cases on the host, each starting and stopping its own instance, with the patched binary (e17f18d + accessor):

Case Expectation Result
dns section + tun:53 -> dns takeover applied, resolution answered, reverted on stop
no dns section refuse refused, host DNS untouched
source -> block ahead of tun:53 -> dns refuse refused, host DNS untouched
dns section with no name servers refuse refused, host DNS untouched

Reasons from the logs, for the three refusals:

no dns section:      no DNS path at 192.168.100.2:53 > DNS feature is the system resolver, takeover would loop
source -> block:     no DNS path at 192.168.100.2:53 > outbound block does not handle DNS
dns section empty:   no DNS path at 192.168.100.2:53 > DNS feature is the system resolver, takeover would loop

and the control:

[tun] system DNS set to 192.168.100.2 on xray_dnstest
app/dispatcher: taking detour [dns] for [udp:192.168.100.2:53]
app/dns: UDP:1.1.1.1:53 got answer: example.com. TypeA -> [104.20.23.154 172.66.147.243]

The TUN came up in all four cases, including the refusals, so a refusal does not block startup. Afterwards the interface was gone and the host resolver was back to its original configuration.

What this does not establish

This is weaker than your setup, and I want to be explicit rather than imply otherwise:

  • No mount/PID namespaces, no private bus, no separate resolved. I ran against the host resolver, which is why the cases are limited to ones that cannot leave the host in a changed state — a refusable configuration, or a takeover that is reverted on stop.
  • The ACL-denial case (Spec v2ray-core中为什么移除xtls #3) is not reproduced with real D-Bus denials. That logic is covered by unit tests only. Your run remains the authoritative evidence for it.
  • No authorization testing against polkit/file-capability policy, as you noted.

Thanks for the two real-system runs and for the concrete reproductions; they made the two High findings unambiguous.

The existing tests replace verifyDNSRouting, so they pass whatever it decides.
That is precisely why the two false positives the reviewer found were invisible
to them: a source-less probe and a DNS feature that resolves through the system
resolver both looked fine to assertions on the resolvectl arguments.

This drives the real function against a real, unstarted instance built with
core.New: real feature lookup, real router, real routing rules. It asserts the
decision for an independent upstream, for both shapes that fall back to the
system resolver, for a rule that only matches because a source is present, for
a rule on an unrelated address, and for no matching rule at all.

Dropping the source from the probe makes exactly the source-rule case fail, so
the coverage is not tautological.
@youugiuhiuh

Copy link
Copy Markdown
Contributor Author

Spec #4 is covered in 71b7021.

TestVerifyDNSRoutingDecisions drives the real verifyDNSRouting against a real but unstarted instance built with core.New() — real feature lookup, real router, real routing rules — instead of replacing the verifier. It asserts the decision for: an independent upstream (accepted); no dns section and a dns section without name servers (both refused as the system resolver); a rule that only matches because the probe carries a source (refused, not a DNS outbound); an unrelated source rule (accepted); and no matching rule (refused, no route).

Checked that it is not tautological: dropping the source from the probe fails exactly the source-rule case and nothing else.

No TUN device, root, or running resolver is needed, so it runs in normal CI.

@yiguodev

Copy link
Copy Markdown
Collaborator

Thanks for the three commits and the explicit clarification of their scope. I retested 71b70211daf9ebe25500f64d8f8634be32fd2c3d with four real Linux matrices, nine scenarios each. This follow-up focuses on functional behavior rather than style.

Confirmed fixes

  • No dns section, an empty DNS configuration, and the gateway-source-IP → blackhole case now correctly refuse takeover while system resolution remains usable.
  • The dirty-state fix works: real private-bus ACL denials cause another revert attempt at shutdown. After restoring the private policy, I captured successful Revert method-return replies, correlated by caller and serial—not merely the absence of an error log. With permission still denied, the retry receives an error and the per-link state disappears with the TUN on exit.

Please keep the small app/dns accessor; covering the empty-server case is justified. The real-router tests are also useful, CI-friendly regression coverage. They test decisions rather than DNS responses, but that does not negate their value.

New counterexample: mixed independent and system-resolver upstreams

Starting from the working independent-upstream configuration, add this DNS server:

{
  "address": "localhost",
  "domains": ["full:example.com"],
  "finalQuery": true,
  "skipFallback": true
}

The takeover is accepted, but example.com times out in 4/4 runs. Queries reach the DNS outbound, and logs show lookups returning to the private system stub and timing out. An unrelated domain resolves successfully before and after the failing query in the same instance.

UsesSystemResolver() returns false as soon as any upstream is non-local, whereas the domain-specific selection can still choose only localhost. This is an additional configuration case, not a claim that your no/empty-DNS fixes failed.

A conservative fix would refuse takeover when a selectable resolution path may depend on the system resolver, rather than checking whether all clients do. A MayUseSystemResolver-style check and a mixed-server regression case would make that distinction explicit; do not silently remove the user's local resolver.

Source ports: the limitation you already disclosed

I acknowledge your statement that the representative source port cannot predict the real query's port. The live consequence is reproducible: with source port 49152 → DNS and remaining TUN/53 traffic → blackhole, preflight accepts takeover; real queries from 49152 answer, while 49153 and the system resolver's actual ephemeral ports fail, in all four runs.

Could the README explicitly require a source-port-independent DNS path and clarify whether unsupported configurations should be refused? We should avoid presenting the synthetic check as a guarantee for arbitrary routing rules. I am not asking for a general Router redesign in this PR.

Scope and evidence limits

Deferring godbus is fine. Fixture duplication and missing full TUN E2E coverage are not additional observed functional failures. The remaining .Base(err).Base(cause) overwrite is a diagnostic improvement, not evidence that cleanup is skipped.

The real TUN/gVisor, DNS and resolvectl path ran inside private mount/PID namespaces with a private bus/resolved. This does not establish normal-host authorization or general leak coverage. Four seconds is the client's timeout limit.

One supplementary rollback-recovery run also had a DNS timeout before policy restoration; Revert succeeded and the next identical run answered normally. That failure is retained and unexplained—not attributed to rollback or dismissed as proven network noise.

All 36 Core instances exited 0, their TUNs disappeared automatically, and all four host-preservation audits passed.

@RPRX

RPRX commented Sep 20, 2026

Copy link
Copy Markdown
Member

这不能是两个 AI 在对话吧

@yiguodev

Copy link
Copy Markdown
Collaborator

实际上,是的。 除开最后这条 edge case,功能上是没什么问题了。

@RPRX

RPRX commented Sep 21, 2026

Copy link
Copy Markdown
Member

Xray-core 可以更名 Xray-vibe 了,不是,我看隔壁 3x-ui 天天 vibe 也是挺香的,AI 越来越强了,要不拿赞助费充 GPT-6 Astra

AGI 时代 Xray 的核心价值大概是理念:“CDN、网盘等不算滥用”以及各种默认/强制的安全策略等,这些还是得靠维护者来决定

以及 VLESS 相关协议标准:将天马行空的想法设计为标准,并提供两端可互联的预构建 core,下载就能直接运行、节点可分享

还有 VLESS Encryption 这种最好是由人来写、相对一劳永逸的核心加密,至于其它的非核心代码,说实话 vibe 一个月要啥有啥

@therealtunge

Copy link
Copy Markdown

yet again, ai code

…tem resolver

UsesSystemResolver asked whether *every* name server resolved through the system
resolver, so a configuration holding both an independent upstream and one
pointed at localhost answered false and the takeover proceeded. Name servers can
be selected per domain, so the local one is still chosen for whichever domains
it is scoped to, and those names then loop back through the system resolver:
example.com timed out on every run of a real setup with

  { "address": "localhost", "domains": ["full:example.com"],
    "finalQuery": true, "skipFallback": true }

It is now MayUseSystemResolver, which asks whether *any* configured name server
could reach the system resolver, and the takeover is refused on that basis. The
refusal is deliberately broader than the case that was observed, because the
alternative would be to drop a name server the user configured.

Also stop discarding the revert failure: Base overwrites rather than chains, so
the rollback path now combines the revert error with the original cause.
…sals

The preflight queries from one representative ephemeral source port, so it
cannot predict a rule that matches on the source port, and it should not be
presented as a guarantee for arbitrary routing rules. Say so, and state the
requirement the check actually assumes: the interface's port 53 reaches a dns
outbound regardless of its source.

The upstream requirement now also covers a name server pointed at localhost and
a dns section that lists none, alongside the existing no-dns-section case.
@youugiuhiuh

youugiuhiuh commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed 8f7c97d0.

Mixed independent and system-resolver upstreams

Fixed, and the root cause is the one you identified. UsesSystemResolver asked whether every name server resolved through the system resolver, so a configuration holding an independent upstream and {"address": "localhost", ...} answered false and the takeover proceeded, while the domain-scoped rule still selects the local server for the domains it covers.

It is now MayUseSystemResolver, asking whether any configured name server could reach the system resolver, and the takeover is refused on that basis. I kept the check broader than the observed failure for the reason you gave: the alternative is dropping a name server the user configured. TestMayUseSystemResolver covers the mixed shape, and TestVerifyDNSRoutingDecisions now has the matching case (independent upstream plus localhost) asserting refusal.

Flipping the predicate back to the old "all" semantics fails exactly the mixed subtest and nothing else.

Refusals now cover: no dns section, a dns section with no name servers, and a localhost upstream in any position. Independent upstreams only are still accepted.

Source ports

Added to the README as a requirement rather than a caveat. The check sends its query from a representative ephemeral source port, so it cannot predict a source-port-matching rule, and the supported configuration is one where the interface's port 53 reaches a dns outbound regardless of source. It no longer reads as a guarantee for arbitrary routing rules.

Error chaining

Correct — Base sets rather than chains, so .Base(err).Base(cause) kept only cause. Now errors.Combine(err, cause).

Evidence limits

Noted, and thank you for stating them plainly. The namespace-private run does not establish normal-host authorization and I am not claiming it does. I am also leaving your pre-restoration DNS timeout unexplained rather than filing it under flakiness.

@yiguodev

yiguodev commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Updated after real TUN validation on 8f7c97d0. My personal recommendation is to leave this corner case for a follow-up optimization, with an explicit configuration limitation for now—not to require a runtime fix before merging this PR.

The mixed-localhost refusal and preservation of both rollback error messages pass the additional probes. The source-port-independent routing requirement is also clear.

Local DoH bootstrap: now confirmed on the real path

With autoSystemDNS enabled and TUN/53 routed to the DNS outbound, https+local://dns.google/dns-query can depend on system DNS to resolve its own hostname. The local DoH path calls DialSystem with that hostname, while MayUseSystemResolver() does not recognize this indirect dependency.

I ran two eight-case matrices, 16 fresh Core/TUN instances on Linux ARM64/systemd-resolved 259, with real TUN/gVisor, routing, DNS outbound, resolvectl, private D-Bus/resolved and public DoH. No product functions or commands were stubbed. All four outbounds, including the DNS outbound, carried sockopt.interface in the bound cases.

Case Run 1 Run 2
Independent upstream, interface-bound, DNS takeover NOERROR; SOCKS HTTPS 204 NOERROR; SOCKS HTTPS 204
Hostname DoH, interface-bound, no DNS takeover; query the real TUN DNS address directly NOERROR, 0.161 s NOERROR, 0.156 s
Same DoH, interface-bound, DNS takeover Timeout, 4.012 s Timeout, 4.013 s
Same Core configuration, only add a private OS hosts entry for the DoH hostname NOERROR, 0.233 s NOERROR, 0.217 s
DNS takeover, interface-bound, additionally enable autoOutboundsInterface Timeout, 4.011 s Timeout, 4.012 s
Same configuration, only add the private OS hosts entry NOERROR, 0.235 s NOERROR, 0.219 s
DNS takeover without either interface-binding setting Timeout, 4.011 s Timeout, 4.011 s
Fresh independent-upstream/interface-bound recheck NOERROR; SOCKS HTTPS 204 NOERROR; SOCKS HTTPS 204

Packet capture showed the DoH hostname's bootstrap queries reaching the private system stub and then the TUN DNS address. Core logs corroborated the path:

resolved -> TUN -> DNS outbound -> DoH hostname bootstrap -> resolved

This is not just a missing interface setting: kernel INET_DIAG observations of the owned Core sockets confirmed ordinary proxy connections were bound. Local DoH did not inherit ordinary outbound sockopt.interface; with independent hosts bootstrap, enabling autoOutboundsInterface did produce a bound DoH TCP connection and successful answers. In the failing case, bootstrap failed before any DoH TCP connection was established. Only the private system /etc/hosts entry changed between each failing case and its corresponding successful hosts control; TLS verification remained enabled.

My recommendation: defer the runtime improvement

For this PR, I would document that upstream resolution including bootstrap must remain independent of the resolver path being redirected, and that preflight detects specific known dependencies rather than proving all indirect paths safe. I am comfortable leaving the implementation improvement to a follow-up; a general DNS dependency analyzer is not required here.

For that follow-up, my suggested direction is Go's default resolver with interface binding in the DNS-query dialing path, for example through net.Resolver.Dial, taking inspiration from Mihomo's interface-aware DNS dialer and separate bootstrap resolver. Mihomo uses its own resolver in the inspected code; using Go's default resolver here is a proposed adaptation, not a description of Mihomo's implementation.

The binding needs to concern bootstrap DNS transport, not merely the later DoH TCP socket. Independent bootstrap-server selection must also be considered: binding traffic that still targets the redirected loopback stub does not by itself remove this dependency. This is a proposed direction, not a fix implemented or validated by these experiments. I'll leave the implementation choice to you.

Evidence and cleanup limits

The approximately four-second values are the client's timeout limit, not an unlimited server timeout or packet-amplification measurement. Both matrices used private mount/PID namespaces and a private resolver while sharing the host network; host DNS/default IP routes were not taken over. This validates DNS through TUN, not full-tunnel HTTP or normal-host polkit authorization.

All 16 Core instances exited 0, TUNs disappeared automatically, and all host-preservation audits passed. Successful Revert replies were captured for all 14 takeover instances. Private configurations and raw endpoint-bearing logs are not included. The earlier one-off timeout on 71b70211 remains unexplained; these results do not retroactively explain it.

A hostname-based upstream that bootstraps through system DNS depends on the
resolver path indirectly: https+local:// resolves its own hostname with
DialSystem, so once the takeover is in place the bootstrap goes
resolved -> TUN -> DNS outbound -> bootstrap -> resolved and times out. The
preflight inspects the dns clients, not their bootstrap, so it does not catch
this and cannot catch indirect dependencies in general.

Say so in the prerequisites and next to the source-port limitation, so the
check is not read as a proof that every indirect path is safe. Upstream
resolution, bootstrap included, has to stay independent of the resolver path
being redirected.
@youugiuhiuh

Copy link
Copy Markdown
Contributor Author

Pushed fbab2193, documentation only.

I took the deferral. The preflight now states that it covers the dependencies it knows about and is not a proof that no indirect one exists, using the same path you traced as the example: DialSystem on https+local://'s own hostname, and with the takeover in place resolved -> TUN -> DNS outbound -> bootstrap -> resolved. Upstream resolution, bootstrap included, is now a prerequisite rather than something the check enforces.

I deliberately did not add a runtime guard for it. Extending the check to local DoH would still only be a list of recognized shapes, and letting the preflight accept or refuse on that basis would imply it validates the path when it does not — the reading you asked to avoid. The limitation is documented instead, and your follow-up direction is recorded in this thread.

Two cautions from that direction I would keep in view for the follow-up work: binding the bootstrap DNS transport rather than the later DoH TCP socket, and the fact that binding traffic which still targets the redirected loopback stub does not by itself remove the dependency.

Evidence limits noted as before: private namespaces, host routes not taken over, and the ~4 s figures are the client's timeout rather than a server-side measurement. The earlier one-off on 71b70211 stays unexplained.

@yiguodev

Copy link
Copy Markdown
Collaborator

@RPRX ,合并吧。

patterniha pushed a commit to patterniha/Xray-core that referenced this pull request Sep 26, 2026
Early merge of XTLS#6773 (PR head fbab219), squashed, ahead of
it landing upstream: XTLS#6773

Co-Authored-By: Claude Opus 5.5 <[email protected]>
patterniha added a commit to patterniha/PattN that referenced this pull request Sep 26, 2026
The Xray tun inbound, used when TUN is on and legacy protect is off, now
sets "autoSystemDNS": true. On Linux with systemd-resolved, Xray-core
(XTLS/Xray-core#6773, in patterniha/Xray-core v26.9.26 and later) then
points the system resolver at the tun, so system DNS goes through Xray
and the tun's port 53 rule to the dns outbound instead of leaking to the
DNS server of the main interface. On Windows the tun's dns list already
sends system DNS there, and Windows and macOS ignore the option.

Xray-core checks before taking over and leaves DNS alone when a query to
the tun on port 53 would not reach a dns outbound, or when its own DNS
could resolve through the system resolver ("localhost", which DHCP DNS
becomes). A normal shutdown reverts it; if the core is killed, the tun
goes away and systemd-resolved drops its settings with it. Older cores
ignore the field.

A test checks the flag and what the takeover depends on: an IPv4
gateway, the tun port 53 rule and the dns outbound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@youugiuhiuh

youugiuhiuh commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Real-host validation of fbab2193. This is meant to address the evidence gap from the last round, where the private mount/PID namespaces and private bus did not establish normal-host authorization.

Environment — Ubuntu 26.04.1 LTS, kernel 7.0.0-34-generic, systemd 259, bare metal (systemd-detect-virt reports none), host net:[4026531833] and pid:[4026531836], real system bus. Not a namespace, not a container.

Configuration — the TUN inbound with autoSystemDNS: true, autoSystemRoutingTable: ["0.0.0.0/1", "128.0.0.0/1"], gateway: ["172.19.0.1/30"], a tun:53 -> dns rule ahead of the rest, and a VLESS/Reality outbound. No nameserver pointed at localhost and no empty dns section, so the preflight was expected to accept.

The takeover happened and the three commands landed

proxy/tun: xray_tuntest created
proxy/tun: [tun] system DNS set to 172.19.0.2 on xray_tuntest
proxy/tun: xray_tuntest up
Link 20 (xray_tuntest)
    Current Scopes: DNS
Current DNS Server: 172.19.0.2
       DNS Servers: 172.19.0.2
        DNS Domain: ~.
     Default Route: yes

The system resolver's query entered the TUN, and the answer came back through the proxy

proxy/tun: processing from udp:172.19.0.1:39821 to udp:172.19.0.2:53
proxy/tun: processing from udp:172.19.0.1:45203 to udp:172.19.0.2:53
app/dns: DOH//dns.google          got answer: browserleaks.com TypeA -> [104.236.69.55]
app/dispatcher: sniffed domain: browserleaks.com
app/dispatcher: default route for tcp:browserleaks.com:443
app/dispatcher: taking detour [dns] for [udp:172.19.0.2:53]
app/dispatcher: taking detour [dns] for [udp:172.19.0.2:53]
app/dispatcher: taking detour [dns] for [udp:172.19.0.2:53]

The 8.8.8.8-style server in other runs of the same config is the dns outbound's own upstream reached through the proxy, not a host query to a public resolver: the only queries the host made were the udp:172.19.0.1:* -> udp:172.19.0.2:53 ones, and the TUN advertised address is what systemd-resolved was pointed at. The taking detour [dns] lines are the runtime dispatch of those queries, as opposed to the preflight's synthetic probe.

Egress moved off the direct path, measured from the same host before and after. The direct-path address and its country are withheld here rather than published:

before after
ifconfig.me (withheld) 56.68.104.36
api.ipify.org (withheld) 56.68.104.36
browserleaks.com/ip (withheld) 56.68.104.36

The after column is the proxy node's own address, so the useful part of the comparison is that it is a different address from the direct one in every row. The node is in MY; that was confirmed out of band because the in-run ipinfo.io/country lookup was rate-limited.

Runs — three in total, all consistent. The first used a VLESS/Reality/xhttp node, the second and third the VLESS/Reality/xtls-rprx-vision/tcp node above, so the takeover was observed under two different outbound transports.

Teardown — verified independently after each run: the interface is gone, the /1 and host routes are gone, the default route is back on the original uplink, systemd-resolved is back to the pre-existing per-link server, and the direct path again measures the same address it did before the run.

Limits of this run

  • fakedns was removed from the configuration so that the DNS path under test was the takeover itself rather than synthetic-address rewriting.
  • Traffic capture needed a manual ip route add <server>/32 via <router> for the proxy server, because autoSystemRoutingTable takes a list of CIDRs and offers no way to exempt the outbound address the way sing-box's auto_route does. That is an upstream TUN gap and is independent of this change; the takeover behaved correctly with it worked around.
  • This confirms the normal-host resolvectl path only. It says nothing about the source-port dependence or the https+local bootstrap dependency already documented in the README.

@RPRX RPRX changed the title proxy/tun: configure system DNS on Linux TUN inbound TUN inbound: Configure system DNS on Linux Sep 27, 2026
@RPRX RPRX changed the title TUN inbound: Configure system DNS on Linux TUN inbound: Add autoSystemDNS on Linux (to TUN's gateway) Sep 27, 2026
@RPRX
RPRX merged commit 47a2c2f into XTLS:main Sep 27, 2026
40 checks passed
@RPRX RPRX mentioned this pull request Sep 27, 2026
5 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants