Repository navigation
TUN inbound: Add autoSystemDNS on Linux (to TUN's gateway) - #6773
Conversation
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.
|
|
|
Thanks for working on this. I reviewed Standards1. Medium: interface addressing now implicitly takes over system DNSLocation: The existing TUN contract says:
On the self-created TUN path, configuring an IPv4 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 interfaceLocation: Both methods return 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. Spec1. High: routing to gateway + 1 does not establish a DNS service thereThe PR states:
The current data path does not guarantee this:
For example, with 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 recommendationThis PR already uses D-Bus indirectly:
The resolved Manager API provides Important caveats:
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. VerificationAll 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). |
|
Thanks for the detailed review — the Spec #1 finding is correct, and I had misstated the guarantee. I traced the three paths you cited ( Plan to address all three findings:
On the D-Bus recommendation: I agree it is the better control plane and would remove the 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.
|
Pushed the fixes from my earlier reply. Spec #1 (High) — reproduced first, then fixedI was able to reproduce the failure you described. With
The same config on the revised version: Host DNS is left alone and the TUN still comes up. With the routing rule present, verification passes and the path is
What changed
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. |
|
Thanks for the follow-up. I re-reviewed the full PR at The explicit opt-in/default-off behavior, updated prerequisites, and removal of the always- Standards1. Medium: the verification context does not satisfy the documented routing contract
&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 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
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. Spec1. High: a DNS outbound can still depend on the resolver being taken overThe 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: 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 routeThe same promise, “only applied when it actually works”, is not met by the source-less probe. Prepending a rule for source 3. Medium: failed rollback loses pending-cleanup stateThe stated behavior is “A failure part-way through the sequence reverts”. At 4. Medium: the promised end-to-end regression test is still missingThe 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 runsThis 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 Each matrix started and ended with a healthy control and fresh test processes. The DNS probe was
Additional observations:
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.
|
Pushed three commits. Status of each finding, then the real-machine results. Standards #1 / Spec #2 — the probe was source-lessReproduced your case first: with a Spec #1 — the loopReproduced too. With no There are two shapes of the same problem, and only one is visible from outside
The second needed a small read-only accessor, so this adds Spec #3 — rollback stateA 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 #2The two recording helpers are merged into one with an optional failing subcommand. Spec #4 — not done yetYou 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 Real-machine resultsFour cases on the host, each starting and stopping its own instance, with the patched binary (
Reasons from the logs, for the three refusals: and the control: 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 establishThis is weaker than your setup, and I want to be explicit rather than imply otherwise:
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.
|
Spec #4 is covered in
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. |
|
Thanks for the three commits and the explicit clarification of their scope. I retested Confirmed fixes
Please keep the small New counterexample: mixed independent and system-resolver upstreamsStarting 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
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 Source ports: the limitation you already disclosedI acknowledge your statement that the representative source port cannot predict the real query's port. The live consequence is reproducible: with source port 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 limitsDeferring godbus is fine. Fixture duplication and missing full TUN E2E coverage are not additional observed functional failures. The remaining 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. |
|
|
|
|
|
AGI 时代 Xray 的核心价值大概是理念:“CDN、网盘等不算滥用”以及各种默认/强制的安全策略等,这些还是得靠维护者来决定 以及 VLESS 相关协议标准:将天马行空的想法设计为标准,并提供两端可互联的预构建 core,下载就能直接运行、节点可分享 还有 VLESS Encryption 这种最好是由人来写、相对一劳永逸的核心加密, |
|
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.
|
Pushed Mixed independent and system-resolver upstreamsFixed, and the root cause is the one you identified. It is now Flipping the predicate back to the old "all" semantics fails exactly the mixed subtest and nothing else. Refusals now cover: no Source portsAdded 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 Error chainingCorrect — Evidence limitsNoted, 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. |
|
Updated after real TUN validation on The mixed- Local DoH bootstrap: now confirmed on the real pathWith 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
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: This is not just a missing interface setting: kernel My recommendation: defer the runtime improvementFor 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 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 limitsThe 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 |
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.
|
Pushed 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: 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 |
|
@RPRX ,合并吧。 |
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]>
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]>
|
Real-host validation of Environment — Ubuntu 26.04.1 LTS, kernel 7.0.0-34-generic, systemd 259, bare metal ( Configuration — the TUN inbound with The takeover happened and the three commands landed The system resolver's query entered the TUN, and the answer came back through the proxy The 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:
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 Runs — three in total, all consistent. The first used a VLESS/Reality/xhttp node, the second and third the VLESS/Reality/ Teardown — verified independently after each run: the interface is gone, the Limits of this run
|
autoSystemDNS on Linux (to TUN's gateway)
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:
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.
@RPRXsuggested this approach in #6454:@yiguodevtested it on macOS and found it did not work there (实测无效), and noted Linux was unverified:This PR covers that Linux case. It works here because systemd-resolved has a
default-routeflag that makes the interface's resolver the system default, whichscutil --dnson 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.goreadsoptions.DNSand 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:resolvectl dns <iface> <addr>resolvectl revert <iface>resolvectl domain <iface> "~."resolvectl default-route <iface> trueThe address handed to systemd-resolved
It is the first IPv4 gateway incremented by one — for
gateway: ["192.168.100.1/30"]that is192.168.100.2.That address belongs to the TUN and is answered inside Xray, so lookups actually travel the tunnel:
Passing the configured resolvers from
options.DNSverbatim — as Windows does — would not work here:resolvectl dns <iface> 1.1.1.1makes systemd-resolved query1.1.1.1:53directly 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:
resolvectlabsent (non-systemd host) →exec.ErrNotFound→ logged, skippedsetSystemDNS/unsetSystemDNSare idempotent via asystemDNSSetflag;ifaceName()guards a nil linkPlatform scope: systemd-resolved only
This change depends entirely on
resolvectl, so it actually takes over system DNS only when all of the following hold:resolvectlis inPATHsystemd-resolvedis enabled and actually managing DNS (installed but not running has no effect)default-routesubcommand is available from 240 onwardWhen 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.
resolvectl→ skippedresolvectl→ skipped/etc/resolv.confresolvectlcannot reach itdnsmay succeed,default-routefails → partial takeoverCovering non-systemd systems would require writing
resolv.confdirectly, 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.DNSandGatewayalready exist and are already plumbed throughinfra/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:gofmtandgo vetclean. Cross-compiles for all common Linux targets:Tested live on Ubuntu 24.04 with systemd-resolved + NetworkManager. systemd-resolved accepts the D-Bus writes:
resolvectl statusconfirms 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, 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.mdOut of scope
resolvectl, so the code skips and the leak remains (see Platform scope above). Would need directresolv.confwrites or dnsmasq/unbound adapters.@RPRXnoted in tun模式存在dns泄漏 #6454, the leak is系统层面的而非应用层面的; closing that would need the nftables hijack deliberately left out of this change.SIGKILLcleanup: a process cannot handleSIGKILL, so an abrupt kill leaves the entry untilresolvectl revertruns. That needs an external supervisor and is not part of this change.