diff --git a/docs/options/amneziaWg.md b/docs/options/amneziaWg.md index 50709a4..3616e72 100644 --- a/docs/options/amneziaWg.md +++ b/docs/options/amneziaWg.md @@ -65,6 +65,7 @@ Part of the [proxy-suite options reference](./index.md). - [vpn](#services-proxy-suite-amneziawg-profiles-name-vpn) - [vpnContainer](#services-proxy-suite-amneziawg-profiles-name-vpncontainer) - [vpnFile](#services-proxy-suite-amneziawg-profiles-name-vpnfile) + - [serverUdpPorts](#services-proxy-suite-amneziawg-serverudpports) - [toolsPackage](#services-proxy-suite-amneziawg-toolspackage) - [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage) - [wireproxyPackage](#services-proxy-suite-amneziawg-wireproxypackage) @@ -536,6 +537,18 @@ File with a vpn:// export\. **Type:** null or string\ **Default:** `null` + +## services\.proxy-suite\.amneziaWg\.serverUdpPorts + +UDP ports of services on this host that others reach, whose packets a global profile +leaves on the host’s own routes\. A reply from a socket bound to every address would +otherwise leave through the tunnel, from the tunnel’s address\. The UDP inbound listeners +and, on NixOS, the ports the firewall opens are included already\. + +**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]±\[0-9]+)\ +**Default:** `[ ]`\ +**Example:** `[ 3478 "49152-65535" ]` + ## services\.proxy-suite\.amneziaWg\.toolsPackage diff --git a/docs/options/index.md b/docs/options/index.md index 8977685..50a1412 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -43,6 +43,7 @@ services.proxy-suite = { enable = false; kernelModulePackage = ‹amneziawg from boot.kernelPackages on NixOS, null elsewhere›; profiles = { }; + serverUdpPorts = [ ]; toolsPackage = ‹proxy-suite's patched amneziawg-tools (pkgs/amneziawg.nix)›; userspacePackage = ‹proxy-suite's patched amneziawg-go (pkgs/amneziawg.nix)›; wireproxyPackage = ‹proxy-suite's wireproxy-awg (pkgs/wireproxy-awg.nix)›; @@ -313,6 +314,7 @@ services.proxy-suite = { warp = { asAmneziaWg = false; asOutbound = null; + autostart = false; configFile = null; enable = false; endpoint = null; diff --git a/docs/options/warp.md b/docs/options/warp.md index a6dddbb..25f2d0d 100644 --- a/docs/options/warp.md +++ b/docs/options/warp.md @@ -10,6 +10,7 @@ Part of the [proxy-suite options reference](./index.md). - [enable](#services-proxy-suite-warp-enable) - [asAmneziaWg](#services-proxy-suite-warp-asamneziawg) - [asOutbound](#services-proxy-suite-warp-asoutbound) + - [autostart](#services-proxy-suite-warp-autostart) - [configFile](#services-proxy-suite-warp-configfile) - [endpoint](#services-proxy-suite-warp-endpoint) - [generatorUrl](#services-proxy-suite-warp-generatorurl) @@ -44,6 +45,15 @@ Add WARP as an outbound tagged “warp”\. **Type:** null or one of “singBox”, “userspace”, “interface”\ **Default:** `null` + +## services\.proxy-suite\.warp\.autostart + +Bring the “warp” AmneziaWG profile up at boot, as ` autostart ` of an ` amneziaWg ` profile +does\. Needs ` asAmneziaWg `\. Only one global mode can autostart\. + +**Type:** boolean\ +**Default:** `false` + ## services\.proxy-suite\.warp\.configFile diff --git a/docs/usage/amneziawg.md b/docs/usage/amneziawg.md index 16a9d7a..0f47396 100644 --- a/docs/usage/amneziawg.md +++ b/docs/usage/amneziawg.md @@ -33,6 +33,11 @@ proxy-ctl awg off Only one global tunnel runs at a time: an AmneziaWG profile, TUN or TProxy. Starting one stops the others. +Connections made to this machine from elsewhere (SSH, a web server, inbound listeners) are +still answered the way they came in, not through the tunnel. For UDP that takes knowing the +port: the inbound listeners and, on NixOS, the firewall's open ports are known; add others to +`amneziaWg.serverUdpPorts`. + ## As an outbound ```nix diff --git a/docs/usage/chains.md b/docs/usage/chains.md index ab14a05..405f25f 100644 --- a/docs/usage/chains.md +++ b/docs/usage/chains.md @@ -86,7 +86,8 @@ services.proxy-suite = { still pin them. - autoProxy tries your exits, WARP included, for each blocked site and keeps the first one that works. -- WARP can also run as a global VPN instead, through AmneziaWG: `warp.asAmneziaWg`. +- WARP can also run as a global VPN instead, through AmneziaWG: `warp.asAmneziaWg`, with + `warp.autostart` to bring it up at boot. ## See also diff --git a/modules/proxy-suite/amnezia-wg-inbounds.nix b/modules/proxy-suite/amnezia-wg-inbounds.nix index 2240039..dbe6531 100644 --- a/modules/proxy-suite/amnezia-wg-inbounds.nix +++ b/modules/proxy-suite/amnezia-wg-inbounds.nix @@ -143,10 +143,15 @@ let '') sysctl )} - # Diverted packets are for the local XRay sockets, whatever their destination. + # Diverted packets are for the local XRay sockets, whatever their destination. Only as + # they come in: with src_valid_mark on (awg-quick turns it on for a global profile and + # leaves it), the kernel checks a packet's source by its mark too, and the local route + # here would make every client's IPv4 address a martian. ${lib.concatMapStrings (family: '' ${ip} ${family} route replace local default dev lo table ${toString awgInboundRouteTable} - ${ip} ${family} rule add pref ${toString awgInboundRulePriority} fwmark ${toString awgInboundFwmark} table ${toString awgInboundRouteTable} + ${lib.concatMapStrings (listener: '' + ${ip} ${family} rule add pref ${toString awgInboundRulePriority} iif ${lib.escapeShellArg listener.interface} fwmark ${toString awgInboundFwmark} table ${toString awgInboundRouteTable} + '') listeners} '') ([ "-4" ] ++ lib.optional ipv6 "-6")} ${nft} -f ${nftRulesFile} diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index fb0c07a..ddcaa35 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -11,7 +11,12 @@ let profiles = awgCfg.profiles; profileNames = builtins.attrNames profiles; globalProfileNames = builtins.attrNames derived.awgGlobalProfiles; - inherit (derived.constants) awgGlobalFwmark awgGlobalGroup; + inherit (derived.constants) + awgGlobalFwmark + awgGlobalGroup + awgOutboundRulePriority + awgServerUdpRulePriority + ; killSwitchUnit = "proxy-suite-killswitch.service"; # Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick. tunnelOutbounds = derived.awgTunnelOutbounds; @@ -128,6 +133,95 @@ let } ''; + # An outbound interface runs with Table=off. A socket bound to it reaches IPv4 without a + # route (the kernel takes the destination as on-link), but IPv6 is unreachable, so the + # interface gets a table of its own, which only sockets bound to it look up. + outboundRuleCleanup = name: profile: '' + for family in -4 -6; do + while ${pkgs.iproute2}/bin/ip "$family" rule del pref ${toString awgOutboundRulePriority} oif ${lib.escapeShellArg profile.interfaceName} 2>/dev/null; do :; done + ${pkgs.iproute2}/bin/ip "$family" route flush table ${toString (outboundRouteTable name)} 2>/dev/null || true + done + ''; + outboundRoutesUp = name: profile: '' + ${outboundRuleCleanup name profile} + for family in -4 -6; do + if [[ -n $(${pkgs.iproute2}/bin/ip "$family" -o addr show dev ${lib.escapeShellArg profile.interfaceName} scope global) ]]; then + ${pkgs.iproute2}/bin/ip "$family" route replace default dev ${lib.escapeShellArg profile.interfaceName} table ${toString (outboundRouteTable name)} + ${pkgs.iproute2}/bin/ip "$family" rule add pref ${toString awgOutboundRulePriority} oif ${lib.escapeShellArg profile.interfaceName} table ${toString (outboundRouteTable name)} + fi + done + ''; + outboundRouteTable = + name: (lib.findFirst (ob: ob.name == name) null derived.awgInterfaceOutbounds).routeTable; + + # A global profile sends everything without its fwmark into the tunnel, replies to + # connections made to this host from elsewhere (SSH, a web server, inbound listeners) + # included, which then never reach the client. Those connections get the fwmark, so + # their packets take the main table and leave the way they came. Before the + # reverse-path filter, which then finds the route back as well. + # + # A UDP socket bound to every address is routed before any packet exists to mark, so the + # tunnel's address would become its source. The ports the host serves UDP on are sent to + # the main table by rule instead, which the kernel checks before it picks the source. + repliesTable = profile: "proxy-suite-awg-${profile.interfaceName}"; + serverUdpPorts = lib.unique ( + map toString (awgCfg.serverUdpPorts ++ derived.proxyInboundFirewallUdpPorts) + ++ cfg.host.openUdpPorts + ); + serverUdpRulesDown = '' + for family in -4 -6; do + while ${pkgs.iproute2}/bin/ip "$family" rule del pref ${toString awgServerUdpRulePriority} 2>/dev/null; do :; done + done + ''; + serverUdpRulesUp = '' + ${serverUdpRulesDown} + for family in -4 -6; do + for port in ${lib.escapeShellArgs serverUdpPorts}; do + # IPv6 may be off. + ${pkgs.iproute2}/bin/ip "$family" rule add pref ${toString awgServerUdpRulePriority} ipproto udp sport "$port" lookup main \ + || [[ $family == -6 ]] + done + done + ''; + repliesUp = profile: '' + fwmark=$(${awgCfg.toolsPackage}/bin/awg show ${lib.escapeShellArg profile.interfaceName} fwmark) + # Off when the profile routes nothing by default (a table of its own, or Table=off). + if [[ "$fwmark" != off ]]; then + ${serverUdpRulesUp} + ${pkgs.nftables}/bin/nft -f - </dev/null || true + ${serverUdpRulesDown} + ''; + + # awg-quick turns src_valid_mark on for a default route and never back off; left on, it + # changes how the kernel checks every marked packet's source. Put back as it was. + srcValidMark = "/proc/sys/net/ipv4/conf/all/src_valid_mark"; + savedSrcValidMark = name: "${runtimeDir name}/src_valid_mark"; + saveSrcValidMark = name: '' + [[ -e ${savedSrcValidMark name} ]] || cat ${srcValidMark} > ${savedSrcValidMark name} + ''; + restoreSrcValidMark = name: '' + if [[ -s ${savedSrcValidMark name} ]]; then + cat ${savedSrcValidMark name} > ${srcValidMark} || true + rm -f ${savedSrcValidMark name} + fi + ''; + # `ping` for the handshake probe. An outbound interface has no route to the probe address, so # the probe is bound to it. pingVia = @@ -220,6 +314,12 @@ let fi ${cfg.host.resolvconfPackage}/bin/resolvconf -d "${profile.interfaceName}" -f 2>/dev/null || true ${pkgs.iproute2}/bin/ip link delete dev ${lib.escapeShellArg profile.interfaceName} 2>/dev/null || true + ${ + if outbound then + outboundRuleCleanup name profile + else + repliesDown profile + restoreSrcValidMark name + } } trap cleanup ERR @@ -227,7 +327,9 @@ let read -r implementation probe _ < <(${pkgs.python3}/bin/python3 ${configTool} \ --inspect ${lib.escapeShellArg configPath}) + ${lib.optionalString (!outbound) (saveSrcValidMark name)} ${awgCommon.awgQuickUp "$implementation" (lib.escapeShellArg configPath)} + ${if outbound then outboundRoutesUp name profile else repliesUp profile} ${mkHandshakeHelpers profile} # A handshake is retried every 5 seconds: each retry after the first gets a new port. @@ -246,8 +348,16 @@ let false ''; stop = pkgs.writeShellScript "proxy-suite-awg" '' - set -euo pipefail - exec ${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath} + set -uo pipefail + status=0 + ${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath} || status=$? + ${ + if outbound then + outboundRuleCleanup name profile + else + repliesDown profile + restoreSrcValidMark name + } + exit "$status" ''; in ( diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 55fbd07..4157e4b 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -152,6 +152,8 @@ let # (only sing-box listens on directPort). tunnelPort = awgTunnelBasePort + 2 * index; directPort = awgTunnelBasePort + 1 + 2 * index; + # Only an "interface" one routes by it. + routeTable = constants.awgOutboundRouteTableBase + index; } ) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles)); awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds; @@ -424,6 +426,12 @@ let # (an Endpoint's name) get past the kill switch. awgGlobalFwmark = 51820; awgGlobalGroup = "proxy-suite-awg"; + # An "interface" AmneziaWG outbound's table (the base plus its index) and the rule + # sending sockets bound to the interface there, clear of the tables above. + awgOutboundRouteTableBase = 110; + awgOutboundRulePriority = 8991; + # A global AmneziaWG profile's rules keeping the host's UDP services on the main table. + awgServerUdpRulePriority = 8989; # sing-box's fake IP caches, one per TUN config; the start script hands it to the backend. fakeIpCacheDir = "${stateDir}/fakeip"; # Downloaded proxy.routing.ruleSets, one file each, written by the service user. diff --git a/modules/proxy-suite/hosts/nixos.nix b/modules/proxy-suite/hosts/nixos.nix index 09180f1..fe8f710 100644 --- a/modules/proxy-suite/hosts/nixos.nix +++ b/modules/proxy-suite/hosts/nixos.nix @@ -30,6 +30,17 @@ in inherit (config.networking) enableIPv6; inherit (config.boot) kernelPackages; firewallPackage = config.networking.firewall.package; + openUdpPorts = + let + firewall = config.networking.firewall; + in + lib.unique ( + lib.concatMap ( + open: + map toString open.allowedUDPPorts + ++ map (range: "${toString range.from}-${toString range.to}") open.allowedUDPPortRanges + ) ([ firewall ] ++ lib.attrValues firewall.interfaces) + ); resolvconfPackage = config.networking.resolvconf.package; }; # NixOS's place for helper functions; set even while disabled, so a config can diff --git a/modules/proxy-suite/options/amnezia-wg.nix b/modules/proxy-suite/options/amnezia-wg.nix index fff82f1..9d56869 100644 --- a/modules/proxy-suite/options/amnezia-wg.nix +++ b/modules/proxy-suite/options/amnezia-wg.nix @@ -51,6 +51,21 @@ in description = "AWG 3.1 kernel module package. `null`: userspace only."; }; + serverUdpPorts = mkOption { + type = types.listOf (types.either types.port (types.strMatching "[0-9]+-[0-9]+")); + default = [ ]; + description = '' + UDP ports of services on this host that others reach, whose packets a global profile + leaves on the host's own routes. A reply from a socket bound to every address would + otherwise leave through the tunnel, from the tunnel's address. The UDP inbound listeners + and, on NixOS, the ports the firewall opens are included already. + ''; + example = [ + 3478 + "49152-65535" + ]; + }; + profiles = mkOption { type = types.attrsOf t.profileType; default = { }; diff --git a/modules/proxy-suite/options/host.nix b/modules/proxy-suite/options/host.nix index 780a079..7d0be86 100644 --- a/modules/proxy-suite/options/host.nix +++ b/modules/proxy-suite/options/host.nix @@ -43,6 +43,8 @@ in enableIPv6 = internalOption types.bool true; kernelPackages = internalOption (types.nullOr types.raw) null; firewallPackage = internalOption (types.nullOr types.package) null; + # UDP ports the host's firewall opens, as "port" or "from-to". + openUdpPorts = internalOption (types.listOf types.str) [ ]; resolvconfPackage = internalOption (types.nullOr types.package) null; }; diff --git a/modules/proxy-suite/options/warp.nix b/modules/proxy-suite/options/warp.nix index 5662a8d..30fdc6e 100644 --- a/modules/proxy-suite/options/warp.nix +++ b/modules/proxy-suite/options/warp.nix @@ -67,5 +67,14 @@ in `amneziaWg.enable`. Cannot be used with `asOutbound`. ''; }; + + autostart = mkOption { + type = types.bool; + default = false; + description = '' + Bring the "warp" AmneziaWG profile up at boot, as `autostart` of an `amneziaWg` profile + does. Needs `asAmneziaWg`. Only one global mode can autostart. + ''; + }; }; } diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index a4a7ca2..0176dfb 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -204,6 +204,9 @@ let (requireEnabled ( cfg.warp.enable && cfg.warp.asAmneziaWg ) cfg.amneziaWg.enable "proxy-suite: warp.asAmneziaWg requires amneziaWg.enable = true") + (requireEnabled (cfg.warp.enable && cfg.warp.autostart) cfg.warp.asAmneziaWg + "proxy-suite: warp.autostart starts the global AmneziaWG profile and requires warp.asAmneziaWg = true" + ) (requireEnabled proxyCfg.autoProxy.enable proxyEnabled "proxy-suite: proxy.autoProxy.enable requires proxy.enable = true" ) diff --git a/modules/proxy-suite/warp.nix b/modules/proxy-suite/warp.nix index b23751b..4b4b6c9 100644 --- a/modules/proxy-suite/warp.nix +++ b/modules/proxy-suite/warp.nix @@ -96,6 +96,7 @@ in configFile = w.profilePath; inherit (w) endpoint; asOutbound = lib.mkIf viaAmneziaWg w.asOutbound; + autostart = lib.mkIf w.autostart true; }; }; diff --git a/nix/checks/amnezia-wg-outbound.nix b/nix/checks/amnezia-wg-outbound.nix index 84cab8c..a29f9ea 100644 --- a/nix/checks/amnezia-wg-outbound.nix +++ b/nix/checks/amnezia-wg-outbound.nix @@ -29,6 +29,10 @@ let amneziaWg = { enable = true; kernelModulePackage = null; + serverUdpPorts = [ + 3478 + "49152-65535" + ]; profiles = { de = { asOutbound = "interface"; @@ -58,6 +62,10 @@ let deStart = generated.readDerivation de.serviceConfig.ExecStart; plainTunnel = generated.readDerivation services.proxy-suite-awg-plain.serviceConfig.ExecStart; dnsServer = dnsServerByTag (mkTProxyConfig singBox) "awg-dns-de"; + home = services.proxy-suite-awg-home; + homeStart = generated.readDerivation home.serviceConfig.ExecStart; + homeStop = generated.readDerivation home.serviceConfig.ExecStop; + deStop = generated.readDerivation de.serviceConfig.ExecStop; warpInterface = mkProxySuite { enable = true; @@ -112,6 +120,38 @@ in assert (mkProxyCtlDerived singBox).awgProfiles == [ "home" ]; true ) + # IPv6 needs a route for sockets bound to the interface: a table of its own, looked up + # only by them, and gone with the unit. + ( + assert hasInfix "route replace default dev awg-de table 110" deStart; + assert hasInfix "rule add pref 8991 oif awg-de table 110" deStart; + assert hasInfix "rule del pref 8991 oif awg-de" deStop; + assert !(hasInfix "fib daddr type local" deStart); + true + ) + # A global profile answers connections to this host the way they came, not through itself. + ( + assert hasInfix + ''ct state new iifname != { "lo", "awg-home" } fib daddr type local ct mark set $fwmark'' + homeStart; + assert hasInfix "type route hook output priority mangle - 5" homeStart; + assert hasInfix "nft delete table inet proxy-suite-awg-awg-home" homeStop; + assert !(hasInfix "oif awg-home" homeStart); + # UDP services answer from the right address even on a socket bound to every address. + assert hasInfix "for port in 3478 49152-65535" homeStart; + assert hasInfix ''rule add pref 8989 ipproto udp sport "$port" lookup main'' homeStart; + assert hasInfix "rule del pref 8989" homeStop; + # src_valid_mark goes back to what it was before awg-quick turned it on. + assert hasInfix + "cat /proc/sys/net/ipv4/conf/all/src_valid_mark > /run/proxy-suite-awg-home/src_valid_mark" + homeStart; + assert hasInfix + "cat /run/proxy-suite-awg-home/src_valid_mark > /proc/sys/net/ipv4/conf/all/src_valid_mark" + homeStop; + assert !(hasInfix "src_valid_mark" deStart); + assert !(hasInfix "pref 8989" deStart); + true + ) # "singBox": a tunnel unit behind a loopback SOCKS hop, fed the prepared profile. ( assert hasInfix ''"server":"127.0.0.1","server_port":18602,"tag":"plain","type":"socks"'' diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index 6f6b313..93681f0 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -901,7 +901,11 @@ let (ok (builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).wants)) (ok (!(relayFixture.config.systemd.services ? "proxy-suite-inbounds-awg"))) ( - assert lib.hasInfix "rule add pref 8990 fwmark 20 table 103" (awgStartScript awgFixture); + # Scoped to the listener's interface, so src_valid_mark cannot make clients martians. + assert lib.hasInfix "rule add pref 8990 iif awgi-home fwmark 20 table 103" ( + awgStartScript awgFixture + ); + assert !(lib.hasInfix "rule add pref 8990 fwmark 20" (awgStartScript awgFixture)); assert lib.hasInfix "awg_inbound.py prepare" (awgStartScript awgFixture); true ) diff --git a/nix/checks/warp.nix b/nix/checks/warp.nix index 22d5f4c..243710c 100644 --- a/nix/checks/warp.nix +++ b/nix/checks/warp.nix @@ -83,6 +83,17 @@ let }; }; + amneziaWgAutostart = mkProxySuite { + enable = true; + amneziaWg.enable = true; + warp = { + enable = true; + configFile = profile; + asAmneziaWg = true; + autostart = true; + }; + }; + amneziaWgEndpoint = mkProxySuite { enable = true; amneziaWg.enable = true; @@ -144,6 +155,17 @@ let }; proxy.enable = true; } + # autostart is the global profile's; an outbound always runs. + { + enable = true; + warp = { + enable = true; + configFile = profile; + asOutbound = "singBox"; + autostart = true; + }; + proxy.enable = true; + } # Tag collision with a declared outbound. { enable = true; @@ -268,6 +290,15 @@ in assert !(amneziaWg.config.systemd.services ? "proxy-suite-warp-tunnel"); true ) + # The global profile starts on demand (proxy-ctl awg on warp), or at boot with autostart. + ( + assert + amneziaWg.config.systemd.services."proxy-suite-awg-warp".wantedBy == [ ] + && + builtins.elem "multi-user.target" + amneziaWgAutostart.config.systemd.services."proxy-suite-awg-warp".wantedBy; + true + ) # endpoint replaces the profile's Endpoint at conversion; the sing-box tunnel gets it quoted. ( assert