From f7036f60755c20c798ede2b01fa1f338da579141 Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Fri, 18 Sep 2026 08:36:45 +0500 Subject: [PATCH] fix: tun/tproxy routing --- docs/options/perAppRouting.md | 2 +- modules/proxy-suite/nftables.nix | 51 ++++++++++++++----- .../proxy-suite/options/per-app-routing.nix | 2 +- .../service/per-app-routing/user-rules.nix | 5 +- nix/checks/per-app-routing-tun.nix | 18 +++++++ pkgs/proxy-ctl/proxy_ctl.py | 29 +++++++++++ pkgs/proxy-ctl/test_proxy_ctl.py | 27 ++++++++++ 7 files changed, 117 insertions(+), 17 deletions(-) diff --git a/docs/options/perAppRouting.md b/docs/options/perAppRouting.md index caa5828..cbe9719 100644 --- a/docs/options/perAppRouting.md +++ b/docs/options/perAppRouting.md @@ -308,7 +308,7 @@ string ## services\.proxy-suite\.perAppRouting\.tun\.localSubnets -Subnets wrapped apps reach directly\. +Subnets wrapped apps reach directly (DNS excepted)\. *Type:* list of string diff --git a/modules/proxy-suite/nftables.nix b/modules/proxy-suite/nftables.nix index 484693c..d387a54 100644 --- a/modules/proxy-suite/nftables.nix +++ b/modules/proxy-suite/nftables.nix @@ -50,6 +50,22 @@ let ${ipFamily cidr} daddr ${cidr} udp dport != 53 return '') subnets; + # Skipping interception for these ranges excepts DNS, as localSubnets does: a resolver + # living in one of them (a router on 10.0.0.1, CGNAT, 100.100.100.100) would otherwise + # answer every name outside the proxy. Loopback is the exception to the exception - + # taking the stub resolver would bypass its cache, split-DNS and mDNS, and its own + # upstream queries pass through here anyway. + reservedLines = '' + ip daddr 127.0.0.0/8 return + ip6 daddr ::1/128 return + ip daddr $RESERVED_IP tcp dport != 53 return + ip daddr $RESERVED_IP udp dport != 53 return + ip daddr $RESERVED_IP meta l4proto != { tcp, udp } return + ip6 daddr $RESERVED_IP6 tcp dport != 53 return + ip6 daddr $RESERVED_IP6 udp dport != 53 return + ip6 daddr $RESERVED_IP6 meta l4proto != { tcp, udp } return + ''; + tproxyLocalSubnetLines = mkLocalSubnetLines globalTproxy.localSubnets; perAppTproxyLocalSubnetLines = mkLocalSubnetLines perAppTproxy.localSubnets; @@ -68,10 +84,10 @@ let table inet singbox { chain prerouting { type filter hook prerouting priority mangle; policy accept; - ip daddr $RESERVED_IP return - ip6 daddr $RESERVED_IP6 return + ${reservedLines} # Connections to this host itself (inbounds, sshd on a public address) - # are served here, not taken by the tproxy socket. + # are served here, not taken by the tproxy socket. A resolver this host + # runs for the LAN is one of them. fib daddr type local return # Packets re-entering via loopback after output marking should not # be skipped just because the host has an RFC1918 source address. @@ -82,8 +98,7 @@ let } chain output { type route hook output priority mangle; policy accept; - ip daddr $RESERVED_IP return - ip6 daddr $RESERVED_IP6 return + ${reservedLines} ${tproxyLocalSubnetLines} meta mark ${toString globalTproxy.proxyMark} return # Replies to connections from outside, and proxy-suite's own daemons (the @@ -100,8 +115,7 @@ let table inet proxy_suite_per_app_tproxy { chain prerouting { type filter hook prerouting priority mangle; policy accept; - ip daddr $RESERVED_IP return - ip6 daddr $RESERVED_IP6 return + ${reservedLines} iifname != "lo" ip saddr $RESERVED_IP return iifname != "lo" ip6 saddr $RESERVED_IP6 return # This host's own addresses are served here, not detoured through the proxy. @@ -116,8 +130,7 @@ let chain output { type route hook output priority mangle; policy accept; - ip daddr $RESERVED_IP return - ip6 daddr $RESERVED_IP6 return + ${reservedLines} ${perAppTproxyLocalSubnetLines} meta mark ${toString globalTproxy.proxyMark} return ct direction reply return @@ -145,16 +158,28 @@ let perAppTunChainFile = pkgs.writeText "proxy-suite-routing" '' ${reservedIpBlock} table inet proxy_suite_per_app_tun { + # The per-user cgroup mark rules are added here at runtime; `output` reaches it + # by two paths, so they are written once. Defined first: a jump only resolves + # to a chain nft has already read. + chain app_mark { + } chain output { type route hook output priority mangle; policy accept; - ip daddr $RESERVED_IP return - ${lib.concatMapStrings (cidr: '' - ${ipFamily cidr} daddr ${cidr} return - '') perAppTun.localSubnets} # Replies to connections from outside leave the way they came, not through the TUN. ct direction reply return ct mark ${toString perAppTun.fwmark} meta mark set ${toString perAppTun.fwmark} meta mark ${toString perAppTun.fwmark} return + # A wrapped app's DNS goes through the TUN even when its resolver sits on a + # local or reserved address, as the global TUN's dport 53 ip rules do: + # otherwise names resolve outside the proxy, fake DNS never sees them, and + # domain rules match nothing. + meta l4proto { tcp, udp } th dport 53 goto app_mark + ip daddr $RESERVED_IP return + ip6 daddr $RESERVED_IP6 return + ${lib.concatMapStrings (cidr: '' + ${ipFamily cidr} daddr ${cidr} return + '') perAppTun.localSubnets} + goto app_mark } } ''; diff --git a/modules/proxy-suite/options/per-app-routing.nix b/modules/proxy-suite/options/per-app-routing.nix index be5d0b7..2ef0374 100644 --- a/modules/proxy-suite/options/per-app-routing.nix +++ b/modules/proxy-suite/options/per-app-routing.nix @@ -66,7 +66,7 @@ in enable = mkEnableOption "the per-app TUN backend"; fwmark = int 16 "Mark that steers wrapped apps into routeTable."; routeTable = int 101 "Policy-routing table of the per-app TUN."; - localSubnets = localSubnets "Subnets wrapped apps reach directly."; + localSubnets = localSubnets "Subnets wrapped apps reach directly (DNS excepted)."; interface = mkOption { type = types.str; diff --git a/modules/proxy-suite/service/per-app-routing/user-rules.nix b/modules/proxy-suite/service/per-app-routing/user-rules.nix index 4b8c0bc..7c257fb 100644 --- a/modules/proxy-suite/service/per-app-routing/user-rules.nix +++ b/modules/proxy-suite/service/per-app-routing/user-rules.nix @@ -86,7 +86,8 @@ let name = "per-app-tun"; nftFamily = "inet"; nftTable = "proxy_suite_per_app_tun"; - nftChain = "output"; + # Not "output": both of that chain's paths into the marking rules jump here. + nftChain = "app_mark"; sliceName = perAppTunSliceName; sliceLabel = "app TUN"; markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}"; @@ -95,7 +96,7 @@ let name = "per-app-tun"; nftFamily = "inet"; nftTable = "proxy_suite_per_app_tun"; - nftChain = "output"; + nftChain = "app_mark"; }; perAppTproxyUserRuleStart = mkUserRuleStart { diff --git a/nix/checks/per-app-routing-tun.nix b/nix/checks/per-app-routing-tun.nix index d3fca38..ee23222 100644 --- a/nix/checks/per-app-routing-tun.nix +++ b/nix/checks/per-app-routing-tun.nix @@ -172,6 +172,24 @@ in true ) + # -- perAppRouting: wrapped apps' DNS reaches the app TUN even when the resolver sits on + # a local or reserved address, and their local IPv6 still leaves directly -- + ( + let + beforeReserved = builtins.head ( + pkgs.lib.splitString "ip daddr $RESERVED_IP return" perAppRoutingTunNftRules + ); + in + assert pkgs.lib.hasInfix "meta l4proto { tcp, udp } th dport 53 goto app_mark" beforeReserved; + assert pkgs.lib.hasInfix "ip6 daddr $RESERVED_IP6 return" perAppRoutingTunNftRules; + assert pkgs.lib.hasInfix "goto app_mark" ( + builtins.elemAt (pkgs.lib.splitString "192.168.0.0/16 return" perAppRoutingTunNftRules) 1 + ); + # The mark rules live in the jumped-to chain, which both paths reach. + assert pkgs.lib.hasInfix "proxy_suite_per_app_tun app_mark" perAppRoutingTunUserStartScript; + true + ) + # -- perAppRouting: app TUN enables nftables -- ( assert perAppRoutingTunFixture.config.networking.nftables.enable; diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 76a1a48..e11b24e 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -2752,6 +2752,34 @@ def _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, backend_svc): systemctl("stop", backend_svc) +def _stub_resolver_nameservers(path="/etc/resolv.conf"): + """The resolvers /etc/resolv.conf names, if every one of them is a local stub.""" + try: + found = [ + line.split()[1] + for line in lines(read_text(path)) + if line.split()[:1] == ["nameserver"] and len(line.split()) > 1 + ] + except OSError: + return [] + stub = [x for x in found if x.startswith("127.") or x in ("::1", "localhost")] + return stub if found and len(stub) == len(found) else [] + + +def _warn_stub_resolver(route): + """A wrapped app asking a local stub resolver leaks its names: the stub answers from + its own process, which is outside the app's cgroup and so outside the app's route.""" + stub = _stub_resolver_nameservers() + if not stub: + return + print( + f"warning: {stub[0]} is this host's only resolver, and it answers from outside the " + f"wrapped app's cgroup, so names resolve outside route={route}. Point the app at a " + "resolver of its own to keep its DNS in the tunnel.", + file=sys.stderr, + ) + + def _wrap_slice(slice_base, profile, backend_svc, cmd): """Runs cmd in a user scope inside the route's slice, then stops what went idle.""" uid = os.getuid() @@ -2823,6 +2851,7 @@ def cmd_apps_run(profile="", *cmd): _check_no_global_proxy(route) if env(enabled) != "1": die(f"Profile '{profile}' uses route={route}, but {option} is false.") + _warn_stub_resolver(route) _wrap_slice(slice_base, profile, f"{slice_base}.service", list(cmd)) else: die(f"Route backend '{route}' is not implemented.") diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index 4a780fb..2bf1ac8 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -44,6 +44,33 @@ def ok(fn, *args): return out +class StubResolverTest(unittest.TestCase): + def resolv(self, content): + tmp = tempfile.NamedTemporaryFile("w", suffix=".conf", delete=False) + tmp.write(content) + tmp.close() + self.addCleanup(os.unlink, tmp.name) + return tmp.name + + def test_only_stub_nameservers_are_reported(self): + path = self.resolv("nameserver 127.0.0.53\noptions edns0\n") + assert ctl._stub_resolver_nameservers(path) == ["127.0.0.53"] + + def test_a_real_resolver_alongside_the_stub_is_not_a_leak(self): + path = self.resolv("nameserver 127.0.0.53\nnameserver 192.168.1.1\n") + assert ctl._stub_resolver_nameservers(path) == [] + + def test_missing_resolv_conf_is_quiet(self): + assert ctl._stub_resolver_nameservers("/nonexistent/resolv.conf") == [] + + def test_wrap_warns_once_on_the_stub(self): + with mock.patch.object(ctl, "_stub_resolver_nameservers", return_value=["127.0.0.53"]): + status, out, err = run(ctl._warn_stub_resolver, "tun") + assert status == 0, (status, out, err) + assert "route=tun" in err + assert "127.0.0.53" in err + + class EnvTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory()