diff --git a/README.md b/README.md index e413d8f..9f2ce53 100644 --- a/README.md +++ b/README.md @@ -74,13 +74,18 @@ services.proxy-suite = { enable = true; profiles.home.configFile = "/run/secrets/home-amneziawg.conf"; profiles.work.vpnFile = "/run/secrets/work-amnezia.vpn"; + # An outbound tagged "de" instead: the proxy binds to its interface, which gets no routes. + profiles.de = { + asOutbound = "interface"; # or "singBox": plain WireGuard inside sing-box + configFile = "/run/secrets/de-amneziawg.conf"; + }; }; # Registers with wgcf on first start. The exit is Cloudflare, but geolocated to your own country. warp = { enable = true; - asOutbound = true; # tag "warp" - asAmneziaWg = true; # proxy-ctl awg on warp + asOutbound = "singBox"; # tag "warp"; "interface" runs it as an AmneziaWG profile + # asAmneziaWg = true; # or a global profile instead: proxy-ctl awg on warp }; tgWsProxy = { diff --git a/docs/options/amneziaWg.md b/docs/options/amneziaWg.md index e218d01..30d29e2 100644 --- a/docs/options/amneziaWg.md +++ b/docs/options/amneziaWg.md @@ -10,6 +10,7 @@ Part of the [proxy-suite options reference](./index.md). - [profiles](#services-proxy-suite-amneziawg-profiles) - `` - [allowConfigHooks](#services-proxy-suite-amneziawg-profiles-name-allowconfighooks) + - [asOutbound](#services-proxy-suite-amneziawg-profiles-name-asoutbound) - [autostart](#services-proxy-suite-amneziawg-profiles-name-autostart) - [configFile](#services-proxy-suite-amneziawg-profiles-name-configfile) - [interfaceName](#services-proxy-suite-amneziawg-profiles-name-interfacename) @@ -131,6 +132,29 @@ boolean false ``` + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.asOutbound + +Make the profile a proxy outbound tagged with its name instead of a global profile\. It then +always runs, leaves the host’s routes and resolver alone, and is not listed by +` proxy-ctl awg `\. Requires proxy\.enable\. + + - “singBox”: a WireGuard endpoint in its own sing-box process, reached as a loopback SOCKS + hop\. sing-box speaks plain WireGuard: AmneziaWG obfuscation is dropped with a warning\. + - “interface”: the AmneziaWG interface comes up without routes (Table = off), and the + outbound binds to it, so obfuscation works\. With the sing-box backend its DNS goes + through the interface too (proxy\.dns\.remote); XRay resolves as usual\. + Either way the tunnel itself reaches the peer over the uplink, past TUN and TProxy\. + +*Type:* +null or one of “singBox”, “interface” + +*Default:* + +```nix +null +``` + ## services\.proxy-suite\.amneziaWg\.profiles\.\\.autostart diff --git a/docs/options/index.md b/docs/options/index.md index 0d09572..6f35fc9 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -255,7 +255,7 @@ services.proxy-suite = { }; warp = { asAmneziaWg = false; - asOutbound = false; + asOutbound = null; configFile = null; enable = false; generatorUrl = null; diff --git a/docs/options/warp.md b/docs/options/warp.md index fff7907..f131666 100644 --- a/docs/options/warp.md +++ b/docs/options/warp.md @@ -49,25 +49,30 @@ false ## services\.proxy-suite\.warp\.asOutbound -Add WARP as an outbound tagged “warp”: a SOCKS hop to proxy-suite-warp-tunnel, which -runs WARP as a sing-box WireGuard endpoint on 127\.0\.0\.1:18538, as the proxy-suite-daemon user\. -The tunnel starts again on a new source port when WARP does not answer within 15 seconds -of a start, or misses three probes later on, unless the uplink itself is down\. +Add WARP as an outbound tagged “warp”\. + + - “singBox”: a SOCKS hop to proxy-suite-warp-tunnel, which runs WARP as a sing-box WireGuard + endpoint on 127\.0\.0\.1:18538, as the proxy-suite-daemon user\. The tunnel starts again on a + new source port when WARP does not answer within 15 seconds of a start, or misses three + probes later on, unless the uplink itself is down\. + - “interface”: an AmneziaWG profile named “warp” with asOutbound = “interface”, which honours + the AmneziaWG lines of the profile\. Requires amneziaWg\.enable\. *Type:* -boolean +null or one of “singBox”, “interface” *Default:* ```nix -false +null ``` ## services\.proxy-suite\.warp\.configFile Runtime path to a WireGuard profile for WARP, as written by ` wgcf register && wgcf generate `\. -AmneziaWG lines (Jc, S1-S4, H1-H4, I1-I5, AWG 3 timing) are honoured by the AmneziaWG profile only\. +AmneziaWG lines (Jc, S1-S4, H1-H4, I1-I5, AWG 3 timing) are honoured by the AmneziaWG profile +(asAmneziaWg, asOutbound = “interface”) only\. When null, proxy-suite-warp registers a device with wgcf (accepting Cloudflare’s terms) into /var/lib/proxy-suite/warp, through the local proxy when proxy\.enable is set, and diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index 0ba2526..4f49b1c 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -4,17 +4,23 @@ lib, pkgs, cfg, + derived, }: let awgCfg = cfg.amneziaWg; profiles = awgCfg.profiles; profileNames = builtins.attrNames profiles; + globalProfileNames = builtins.attrNames derived.awgGlobalProfiles; + singBoxOutbounds = builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds; serviceName = name: "proxy-suite-awg-${name}"; - serviceNames = map serviceName profileNames; + globalServiceNames = map serviceName globalProfileNames; allProfileConflicts = name: - map (other: "${serviceName other}.service") (builtins.filter (other: other != name) profileNames); + map (other: "${serviceName other}.service") ( + builtins.filter (other: other != name) globalProfileNames + ); + inherit (import ./wg-tunnel.nix { inherit lib pkgs cfg derived; }) mkTunnel; sourceCount = profile: builtins.length ( @@ -100,16 +106,31 @@ let } ''; + # `ping` for the handshake probe. An outbound interface has no route to the probe address, so + # the probe is bound to it. + pingVia = + profile: + "${pkgs.iputils}/bin/ping -n -c 1" + + lib.optionalString (profile.asOutbound == "interface") " -I ${lib.escapeShellArg profile.interfaceName}"; + + # An outbound interface keeps the host's routes and resolver, and marks its packets so TUN and + # TProxy let them past. + prepareCommand = profile: output: '' + ${pkgs.python3}/bin/python3 ${configTool} \ + --manifest ${lib.escapeShellArg (toString (manifestFor profile))} \ + --output ${output}${ + lib.optionalString (profile.asOutbound == "interface") " --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}" + } + ''; + mkService = name: profile: let - manifest = manifestFor profile; + outbound = profile.asOutbound == "interface"; configPath = runtimeConfig name profile; prepare = pkgs.writeShellScript "proxy-suite-awg" '' set -euo pipefail - ${pkgs.python3}/bin/python3 ${configTool} \ - --manifest ${lib.escapeShellArg (toString manifest)} \ - --output ${lib.escapeShellArg configPath} + ${prepareCommand profile (lib.escapeShellArg configPath)} ''; proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" '' set -euo pipefail @@ -176,7 +197,7 @@ let ${mkHandshakeHelpers profile} # A handshake is retried every 5 seconds: each retry after the first gets a new port. for attempt in $(${pkgs.coreutils}/bin/seq 1 20); do - ${pkgs.iputils}/bin/ping -n -c 1 -W 1 "$probe" >/dev/null 2>&1 || true + ${pingVia profile} -W 1 "$probe" >/dev/null 2>&1 || true if (( $(handshake_age) < 1000000 )); then trap - ERR exit 0 @@ -194,24 +215,38 @@ let exec ${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath} ''; in - { - description = "proxy-suite AmneziaWG client profile ${name}"; - # Start the local proxy before AWG takes the default route, so HTTP_PROXY clients - # do not race it. - after = [ - "network-online.target" - "proxy-suite-zapret.service" - ] - ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; - wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; - wantedBy = lib.optionals profile.autostart [ "multi-user.target" ]; - conflicts = allProfileConflicts name ++ [ - "proxy-suite-tun.service" - "proxy-suite-tproxy.service" - "proxy-suite-zapret.service" - "proxy-suite-per-app-zapret.service" - "proxy-suite-zapret-vm-exempt.service" - ]; + ( + if outbound then + { + description = "proxy-suite AmneziaWG interface behind the ${name} outbound"; + # Nothing waits for it: a slow handshake must not hold up the proxy. + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + startLimitIntervalSec = 0; + } + else + { + description = "proxy-suite AmneziaWG client profile ${name}"; + # Start the local proxy before AWG takes the default route, so HTTP_PROXY clients + # do not race it. + after = [ + "network-online.target" + "proxy-suite-zapret.service" + ] + ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; + wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; + wantedBy = lib.optionals profile.autostart [ "multi-user.target" ]; + conflicts = allProfileConflicts name ++ [ + "proxy-suite-tun.service" + "proxy-suite-tproxy.service" + "proxy-suite-zapret.service" + "proxy-suite-per-app-zapret.service" + "proxy-suite-zapret-vm-exempt.service" + ]; + } + ) + // { path = [ awgCfg.toolsPackage awgCfg.userspacePackage @@ -237,15 +272,35 @@ let ProtectKernelLogs = true; RestrictRealtime = true; RestrictSUIDSGID = true; - ExecStartPre = [ prepare ] ++ lib.optionals cfg.proxy.enable [ proxyBypassUp ]; + ExecStartPre = [ prepare ] ++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ]; ExecStart = start; ExecStop = stop; } - // lib.optionalAttrs cfg.proxy.enable { + // lib.optionalAttrs (cfg.proxy.enable && !outbound) { ExecStopPost = proxyBypassDown; + } + # A failed handshake leaves no routes behind here, so try again later. + // lib.optionalAttrs outbound { + Restart = "on-failure"; + RestartSec = 30; }; }; + mkSingBoxService = + ob: + let + profile = profiles.${ob.name}; + in + mkTunnel { + description = "proxy-suite AmneziaWG tunnel behind the ${ob.name} outbound"; + unit = serviceName ob.name; + inherit (ob) tag tunnelPort directPort; + profile = '' + profile="$RUNTIME_DIRECTORY/profile.conf" + ${prepareCommand profile ''"$profile"''} + ''; + }; + # Runs alongside a started profile. Its pings keep traffic flowing, and traffic makes # WireGuard rekey every RekeyAfterTime (120 seconds by default); a handshake older than that # on two checks in a row is a rekey that is not getting through, so the interface moves to @@ -264,7 +319,7 @@ let ${mkHandshakeHelpers profile} stale=0 while sleep 15; do - ${pkgs.iputils}/bin/ping -n -c 1 -W 2 "$probe" >/dev/null 2>&1 || true + ${pingVia profile} -W 2 "$probe" >/dev/null 2>&1 || true if (( $(handshake_age) <= rekey + 10 )); then stale=0 elif (( ++stale >= 2 )); then @@ -323,6 +378,18 @@ let assertion = profile.vpnContainer == null || profile.vpn != null || profile.vpnFile != null; message = "proxy-suite: AmneziaWG profile '${name}': vpnContainer requires vpn or vpnFile"; } + { + assertion = profile.asOutbound == null || cfg.proxy.enable; + message = "proxy-suite: AmneziaWG profile '${name}': asOutbound requires proxy.enable = true"; + } + { + assertion = profile.asOutbound == null || !profile.autostart; + message = "proxy-suite: AmneziaWG profile '${name}': an outbound always runs; leave autostart off"; + } + { + assertion = profile.asOutbound != "interface" || settings == null || settings.table == null; + message = "proxy-suite: AmneziaWG profile '${name}': an outbound interface has no routes; leave settings.table unset"; + } { assertion = settings == null || settings.addresses != [ ]; message = "proxy-suite: AmneziaWG profile '${name}': declarative settings require at least one address"; @@ -353,7 +420,7 @@ let ) profileNames; interfaceNames = map (name: profiles.${name}.interfaceName) profileNames; - autostartProfiles = builtins.filter (name: profiles.${name}.autostart) profileNames; + autostartProfiles = builtins.filter (name: profiles.${name}.autostart) globalProfileNames; globalAutostartCount = builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0); in { @@ -366,18 +433,24 @@ in awgCfg.kernelModulePackage ]; + # Replies to the proxy's sockets come in on an interface the host has no route through. + networking.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: '' + iifname "${ob.interface}" accept + '') derived.awgInterfaceOutbounds; + systemd.services = lib.mkMerge [ - (lib.mapAttrs' ( - name: profile: lib.nameValuePair (serviceName name) (mkService name profile) - ) profiles) + (lib.mapAttrs' (name: profile: lib.nameValuePair (serviceName name) (mkService name profile)) ( + lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles + )) (lib.mapAttrs' ( name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile) - ) profiles) + ) (lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles)) + (lib.listToAttrs (map (ob: lib.nameValuePair (serviceName ob.name) (mkSingBoxService ob)) singBoxOutbounds)) (lib.mkIf cfg.proxy.tun.enable { - proxy-suite-tun.conflicts = map (name: "${name}.service") serviceNames; + proxy-suite-tun.conflicts = map (name: "${name}.service") globalServiceNames; }) (lib.mkIf cfg.proxy.tproxy.enable { - proxy-suite-tproxy.conflicts = map (name: "${name}.service") serviceNames; + proxy-suite-tproxy.conflicts = map (name: "${name}.service") globalServiceNames; }) ]; diff --git a/modules/proxy-suite/config-templates/sing-box.nix b/modules/proxy-suite/config-templates/sing-box.nix index 4a7567a..b67a43c 100644 --- a/modules/proxy-suite/config-templates/sing-box.nix +++ b/modules/proxy-suite/config-templates/sing-box.nix @@ -37,12 +37,21 @@ let mkDnsConfig = { localDetour ? null, + useOutboundRoutingMark ? false, }: { servers = [ (mkDnsServer "remote" proxyCfg.dns.remote "proxy") (mkDnsServer "local" proxyCfg.dns.local localDetour) - ]; + ] + ++ map ( + ob: + mkDnsServer (constants.awgDnsServerTag ob.tag) proxyCfg.dns.remote null + // { + bind_interface = ob.interface; + } + // lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; } + ) derived.awgInterfaceOutbounds; rules = lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) { rule_set = [ "geosite-google" ]; @@ -93,6 +102,7 @@ let dns = mkDnsConfig { localDetour = if forceLocalDnsViaProxy then "proxy" else null; + inherit useOutboundRoutingMark; }; inbounds = diff --git a/modules/proxy-suite/default.nix b/modules/proxy-suite/default.nix index b780332..a319e63 100644 --- a/modules/proxy-suite/default.nix +++ b/modules/proxy-suite/default.nix @@ -183,6 +183,7 @@ in lib pkgs cfg + derived ; } )) diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index b63f4aa..7cb032f 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -48,7 +48,28 @@ let directPort = 18539; }; warpOutboundTag = "warp"; - warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound; + # The sing-box tunnel; asOutbound = "interface" comes in through the AmneziaWG profile list. + warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound == "singBox"; + + # AmneziaWG profiles are either global (proxy-ctl awg on) or outbounds tagged with their name. + awgProfiles = lib.optionalAttrs cfg.amneziaWg.enable cfg.amneziaWg.profiles; + awgGlobalProfiles = lib.filterAttrs (_: profile: profile.asOutbound == null) awgProfiles; + awgOutbounds = lib.imap0 ( + index: name: + let + profile = awgProfiles.${name}; + in + { + inherit name; + tag = name; + kind = profile.asOutbound; + interface = profile.interfaceName; + # Loopback listeners of a "singBox" tunnel, as warpCfg.tunnelPort/directPort. + tunnelPort = 18540 + 2 * index; + directPort = 18541 + 2 * index; + } + ) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles)); + awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds; proxyInboundsCfg = cfg.inbounds; proxyInboundsEnabled = proxyInboundsCfg.enable; @@ -130,13 +151,18 @@ let effectiveOutboundTags = outboundTags ++ lib.optional sshProxyOutboundEnabled sshProxyOutboundTag - ++ lib.optional warpOutboundEnabled warpOutboundTag; + ++ lib.optional warpOutboundEnabled warpOutboundTag + ++ map (ob: ob.tag) awgOutbounds; subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions; hasStaticOutbounds = proxyCfg.outbounds != [ ]; hasSubscriptions = proxyCfg.subscriptions != [ ]; hasAvailableOutbounds = - hasStaticOutbounds || hasSubscriptions || sshProxyOutboundEnabled || warpOutboundEnabled; + hasStaticOutbounds + || hasSubscriptions + || sshProxyOutboundEnabled + || warpOutboundEnabled + || awgOutbounds != [ ]; collapseNamedOutbounds = selectionMode == "first"; # Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode. clashApiEnabled = singBoxEnabled; @@ -220,6 +246,9 @@ let outboundTestPort = 18537; inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json"; + # sing-box DNS server resolving through an "interface" AmneziaWG outbound. + awgDnsServerTag = tag: "awg-dns-${tag}"; + tunAutoRouteTableIndex = 2022; tunAutoRouteRulePriority = 9000; xrayTunPerAppTproxyRulePriority = 8996; @@ -289,6 +318,9 @@ in warpCfg warpOutboundTag warpOutboundEnabled + awgGlobalProfiles + awgOutbounds + awgInterfaceOutbounds proxyInboundsCfg proxyInboundsEnabled proxyInbounds diff --git a/modules/proxy-suite/options/types/amnezia-wg.nix b/modules/proxy-suite/options/types/amnezia-wg.nix index a1f4c5b..a5e5592 100644 --- a/modules/proxy-suite/options/types/amnezia-wg.nix +++ b/modules/proxy-suite/options/types/amnezia-wg.nix @@ -269,6 +269,26 @@ let default = false; description = "Whether to start this profile at boot. At most one profile may autostart."; }; + asOutbound = mkOption { + type = types.nullOr ( + types.enum [ + "singBox" + "interface" + ] + ); + default = null; + description = '' + Make the profile a proxy outbound tagged with its name instead of a global profile. It then + always runs, leaves the host's routes and resolver alone, and is not listed by + `proxy-ctl awg`. Requires proxy.enable. + - "singBox": a WireGuard endpoint in its own sing-box process, reached as a loopback SOCKS + hop. sing-box speaks plain WireGuard: AmneziaWG obfuscation is dropped with a warning. + - "interface": the AmneziaWG interface comes up without routes (Table = off), and the + outbound binds to it, so obfuscation works. With the sing-box backend its DNS goes + through the interface too (proxy.dns.remote); XRay resolves as usual. + Either way the tunnel itself reaches the peer over the uplink, past TUN and TProxy. + ''; + }; allowConfigHooks = mkOption { type = types.bool; default = false; diff --git a/modules/proxy-suite/options/warp.nix b/modules/proxy-suite/options/warp.nix index e827991..5b6f71c 100644 --- a/modules/proxy-suite/options/warp.nix +++ b/modules/proxy-suite/options/warp.nix @@ -12,7 +12,8 @@ in default = null; description = '' Runtime path to a WireGuard profile for WARP, as written by `wgcf register && wgcf generate`. - AmneziaWG lines (Jc, S1-S4, H1-H4, I1-I5, AWG 3 timing) are honoured by the AmneziaWG profile only. + AmneziaWG lines (Jc, S1-S4, H1-H4, I1-I5, AWG 3 timing) are honoured by the AmneziaWG profile + (asAmneziaWg, asOutbound = "interface") only. When null, proxy-suite-warp registers a device with wgcf (accepting Cloudflare's terms) into /var/lib/proxy-suite/warp, through the local proxy when proxy.enable is set, and @@ -35,13 +36,21 @@ in }; asOutbound = mkOption { - type = types.bool; - default = false; + type = types.nullOr ( + types.enum [ + "singBox" + "interface" + ] + ); + default = null; description = '' - Add WARP as an outbound tagged "warp": a SOCKS hop to proxy-suite-warp-tunnel, which - runs WARP as a sing-box WireGuard endpoint on 127.0.0.1:18538, as the proxy-suite-daemon user. - The tunnel starts again on a new source port when WARP does not answer within 15 seconds - of a start, or misses three probes later on, unless the uplink itself is down. + Add WARP as an outbound tagged "warp". + - "singBox": a SOCKS hop to proxy-suite-warp-tunnel, which runs WARP as a sing-box WireGuard + endpoint on 127.0.0.1:18538, as the proxy-suite-daemon user. The tunnel starts again on a + new source port when WARP does not answer within 15 seconds of a start, or misses three + probes later on, unless the uplink itself is down. + - "interface": an AmneziaWG profile named "warp" with asOutbound = "interface", which honours + the AmneziaWG lines of the profile. Requires amneziaWg.enable. ''; }; diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index c547300..b08a258 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -74,19 +74,22 @@ let "proxy-suite: sshProxy.asOutbound requires proxy.enable = true" ) (mkAssertion ( - !cfg.warp.enable || cfg.warp.asOutbound || cfg.warp.asAmneziaWg + !cfg.warp.enable || cfg.warp.asOutbound != null || cfg.warp.asAmneziaWg ) "proxy-suite: warp.enable = true needs warp.asOutbound or warp.asAmneziaWg") # One key, one session: the second peer on a WARP key takes the session over. - (mkAssertion (!(cfg.warp.enable && cfg.warp.asOutbound && cfg.warp.asAmneziaWg)) + (mkAssertion (!(cfg.warp.enable && cfg.warp.asOutbound != null && cfg.warp.asAmneziaWg)) "proxy-suite: warp.asOutbound and warp.asAmneziaWg share one WARP key and would knock each other off; enable one" ) # Daemon configs are readable by the service group; users must not share it. (mkAssertion (cfg.userControl.group != derived.constants.serviceUser) "proxy-suite: userControl.group must not be ${derived.constants.serviceUser}, the group that can read backend configs" ) - (requireEnabled derived.warpOutboundEnabled proxyEnabled + (requireEnabled (cfg.warp.enable && cfg.warp.asOutbound != null) proxyEnabled "proxy-suite: warp.asOutbound requires proxy.enable = true" ) + (requireEnabled ( + cfg.warp.enable && cfg.warp.asOutbound == "interface" + ) cfg.amneziaWg.enable ''proxy-suite: warp.asOutbound = "interface" requires amneziaWg.enable = true'') (requireEnabled ( cfg.warp.enable && cfg.warp.asAmneziaWg ) cfg.amneziaWg.enable "proxy-suite: warp.asAmneziaWg requires amneziaWg.enable = true") diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index e6d847f..95dd1a1 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -50,6 +50,7 @@ let sshProxyOutboundEnabled sshProxyUnitEnabled warpCfg + awgOutbounds proxyInboundsCfg proxyInboundsEnabled proxyInboundsNeedLocalProxy @@ -69,8 +70,11 @@ let headBin = "${pkgs.coreutils}/bin/head"; seqBin = "${pkgs.coreutils}/bin/seq"; findBin = "${pkgs.findutils}/bin/find"; + # `proxy-ctl awg` toggles global profiles; outbound ones always run and show up with the proxy. amneziaWgProfileNamesFile = pkgs.writeText "proxy-suite-core" ( - builtins.toJSON (builtins.attrNames cfg.amneziaWg.profiles) + builtins.toJSON ( + builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) + ) ); proxySuiteScriptsDir = builtins.path { @@ -96,6 +100,7 @@ let proxyCfg sshProxyCfg warpCfg + awgOutbounds xrayEnabled hybridEnabled pureXrayEnabled diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index e2ea69d..926dfe5 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -5,6 +5,7 @@ proxyCfg, sshProxyCfg, warpCfg, + awgOutbounds, constants, pureXrayEnabled, hybridEnabled, @@ -370,39 +371,72 @@ let _proxy_suite_record_tag_source ${sshProxyTag} ssh ''; - # WARP runs in proxy-suite-warp-tunnel, which restarts it when the handshake stops being - # answered. Every backend reaches it as a loopback SOCKS hop. - mkWarpOutboundBlock = - let - outbound = - if pureXrayEnabled then - { - protocol = "socks"; - tag = "warp"; - settings = { - address = "127.0.0.1"; - port = warpCfg.tunnelPort; - }; - } - else - { - type = "socks"; - tag = "warp"; - server = "127.0.0.1"; - server_port = warpCfg.tunnelPort; + # Outbounds whose JSON is known at build time: every backend takes it as is. + mkFixedOutboundBlock = comment: source: outbound: '' + # outbound: ${outbound.tag} (${comment}) + OB_JSON=${lib.escapeShellArg (builtins.toJSON outbound)} + ${ + if hybridEnabled then + ''_proxy_suite_add_sing_box_ob "$OB_JSON"'' + else + ''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")'' + } + _proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source} + ''; + + # WARP and "singBox" AmneziaWG profiles run in a tunnel unit, which restarts them when the + # handshake stops being answered. Every backend reaches it as a loopback SOCKS hop. + mkTunnelOutboundBlock = + unit: source: tag: port: + mkFixedOutboundBlock "SOCKS hop to ${unit}" source ( + if pureXrayEnabled then + { + protocol = "socks"; + inherit tag; + settings = { + address = "127.0.0.1"; + inherit port; }; - in - '' - # outbound: warp (SOCKS hop to proxy-suite-warp-tunnel) - OB_JSON=${lib.escapeShellArg (builtins.toJSON outbound)} - ${ - if hybridEnabled then - ''_proxy_suite_add_sing_box_ob "$OB_JSON"'' - else - ''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")'' - } - _proxy_suite_record_tag_source warp warp - ''; + } + else + { + type = "socks"; + inherit tag; + server = "127.0.0.1"; + server_port = port; + } + ); + + # An "interface" AmneziaWG profile: the outbound binds to the interface, which has no routes. + # sing-box resolves its destinations through it too; XRay resolves as usual. + mkInterfaceOutboundBlock = + routingMark: ob: + mkFixedOutboundBlock "bound to ${ob.interface}" "awg" ( + if pureXrayEnabled then + { + protocol = "freedom"; + inherit (ob) tag; + streamSettings.sockopt = { + inherit (ob) interface; + } + // lib.optionalAttrs (routingMark != null) { mark = routingMark; }; + } + else + { + type = "direct"; + inherit (ob) tag; + bind_interface = ob.interface; + domain_resolver = constants.awgDnsServerTag ob.tag; + } + // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; } + ); + + mkAwgOutboundBlock = + routingMark: ob: + if ob.kind == "interface" then + mkInterfaceOutboundBlock routingMark ob + else + mkTunnelOutboundBlock "proxy-suite-awg-${ob.name}" "awg" ob.tag ob.tunnelPort; mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock; @@ -464,7 +498,10 @@ let ) proxyCfg.subscriptions; sshProxyBlock = lib.optionalString sshProxyCfg.asOutbound (mkSshProxyOutboundBlock routingMark); - warpBlock = lib.optionalString (warpCfg.enable && warpCfg.asOutbound) mkWarpOutboundBlock; + warpBlock = lib.optionalString (warpCfg.enable && warpCfg.asOutbound == "singBox") ( + mkTunnelOutboundBlock "proxy-suite-warp-tunnel" "warp" "warp" warpCfg.tunnelPort + ); + awgBlocks = lib.concatMapStrings (mkAwgOutboundBlock routingMark) awgOutbounds; wrapperBlock = if pureXrayEnabled && selectionMode == "urltest" then @@ -534,6 +571,7 @@ let + runtimeOutboundsBlock + sshProxyBlock + warpBlock + + awgBlocks + requireOutboundsBlock + pinBlock + inventoryBlock diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 4e90c26..590ba91 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -6,6 +6,7 @@ proxyCfg, sshProxyCfg, warpCfg, + awgOutbounds, xrayEnabled, hybridEnabled, pureXrayEnabled, @@ -111,6 +112,7 @@ let proxyCfg sshProxyCfg warpCfg + awgOutbounds constants pureXrayEnabled hybridEnabled diff --git a/modules/proxy-suite/warp.nix b/modules/proxy-suite/warp.nix index 86ad16e..4f2decd 100644 --- a/modules/proxy-suite/warp.nix +++ b/modules/proxy-suite/warp.nix @@ -1,5 +1,5 @@ -# Cloudflare WARP: the tunnel behind the "warp" outbound, the AmneziaWG profile and, without a -# configFile, wgcf registration. +# Cloudflare WARP: the sing-box tunnel or AmneziaWG profile behind the "warp" outbound, the global +# AmneziaWG profile and, without a configFile, wgcf registration. { lib, pkgs, @@ -9,13 +9,9 @@ let w = derived.warpCfg; - inherit (derived.constants) serviceUser runAsServiceUser unprivilegedServiceConfig; + inherit (derived.constants) unprivilegedServiceConfig; listener = cfg.proxy.listener; auth = listener.auth; - scriptsDir = builtins.path { - name = "proxy-suite-scripts"; - path = ../../scripts; - }; host = if builtins.elem listener.address [ @@ -89,112 +85,30 @@ let } ''; - # sing-box's "local" server has no upstream on hosts behind systemd-resolved, so the tunnel - # resolves like the main config: the peer hostname and destinations go to proxy.dns.local. - dnsServer = { - tag = "local"; - type = cfg.proxy.dns.local.type; - server = cfg.proxy.dns.local.address; - server_port = cfg.proxy.dns.local.port; - }; - mark = cfg.proxy.tproxy.proxyMark; - probe = port: url: '' - ${pkgs.curl}/bin/curl -s --noproxy "" -x socks5h://127.0.0.1:${toString port} -m "$timeout" \ - -o /dev/null ${url}''; - - # Some lines drop a share of fresh WARP handshakes for good, and sing-box retries on the - # same source port forever. A new process binds a new port, so the watchdog exits when - # WARP stops answering and systemd starts the tunnel again. A healthy WARP handshake takes - # a fraction of a second, so a start gets 15 seconds; a running tunnel gets three misses. - # The "direct-in" listener reaches Cloudflare through the uplink with the backend's mark (not - # urlTest.url, which is picked to be blocked here): when that fails too, WARP could not work - # from a new port either. - watchdogScript = pkgs.writeShellScript "proxy-suite-warp" '' - set -uo pipefail - ${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json" & - singbox=$! - - healthy=0 - failures=0 - uplink_down=0 - since=0 - while sleep $(( healthy ? 10 : 2 )); do - kill -0 "$singbox" 2>/dev/null || { wait "$singbox"; exit 1; } - timeout=$(( healthy ? 10 : 4 )) - if ${probe w.tunnelPort "-f ${lib.escapeShellArg cfg.proxy.urlTest.url}"}; then - (( healthy )) || echo "proxy-suite: WARP is answering" >&2 - healthy=1 failures=0 uplink_down=0 - continue - fi - if ! ${probe w.directPort "https://1.1.1.1/cdn-cgi/trace"}; then - (( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging WARP" >&2 - uplink_down=1 failures=0 since=$SECONDS - continue - fi - uplink_down=0 - if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then - echo "proxy-suite: WARP is not answering; restarting the tunnel on a new source port" >&2 - kill "$singbox" - wait "$singbox" - exit 1 - fi - done - ''; - - tunnelScript = pkgs.writeShellScript "proxy-suite-warp" '' - set -euo pipefail - profile=${lib.escapeShellArg w.profilePath} - if [ ! -s "$profile" ]; then - echo "proxy-suite: waiting for the WARP profile at $profile" >&2 - until [ -s "$profile" ]; do sleep 5; done - fi - - # The profile is a secret, so it is converted here, as root, rather than baked into - # the store; sing-box itself runs as ${serviceUser}. - endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag warp --routing-mark ${toString mark} < "$profile") - (umask 027 && ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{ - log: {level: "warn"}, - dns: {servers: [${builtins.toJSON dnsServer}]}, - route: { - default_domain_resolver: "local", - rules: [{inbound: ["direct-in"], outbound: "direct"}], - final: "warp" - }, - inbounds: [ - {type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString w.tunnelPort}}, - {type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString w.directPort}} - ], - outbounds: [{type: "direct", tag: "direct", routing_mark: ${toString mark}}], - endpoints: [$ep] - }' > "$RUNTIME_DIRECTORY/config.json") - ${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/config.json" - - exec ${runAsServiceUser pkgs [ "net_admin" ]} ${watchdogScript} - ''; + inherit (import ./wg-tunnel.nix { inherit lib pkgs cfg derived; }) mkTunnel; in { - services.proxy-suite.amneziaWg.profiles = lib.mkIf w.asAmneziaWg { - warp.configFile = w.profilePath; + services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") { + warp = { + configFile = w.profilePath; + asOutbound = lib.mkIf (w.asOutbound == "interface") "interface"; + }; }; systemd.services = lib.mkMerge [ - (lib.mkIf w.asOutbound { - proxy-suite-warp-tunnel = { + (lib.mkIf (w.asOutbound == "singBox") { + proxy-suite-warp-tunnel = mkTunnel { description = "proxy-suite - Cloudflare WARP tunnel behind the warp outbound"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - wantedBy = [ "multi-user.target" ]; - # Probe-triggered restarts must not trip the start limit. - startLimitIntervalSec = 0; - serviceConfig = { - Type = "simple"; - ExecStart = tunnelScript; - Restart = "always"; - RestartSec = 2; - RuntimeDirectory = "proxy-suite-warp-tunnel"; - RuntimeDirectoryMode = "0750"; - UMask = "0077"; - }; + unit = "proxy-suite-warp-tunnel"; + tag = "warp"; + profile = '' + profile=${lib.escapeShellArg w.profilePath} + if [ ! -s "$profile" ]; then + echo "proxy-suite: waiting for the WARP profile at $profile" >&2 + until [ -s "$profile" ]; do sleep 5; done + fi + ''; + inherit (w) tunnelPort directPort; }; }) @@ -223,7 +137,7 @@ in }; # Only pulls registration in: a simple unit gives the profile no ordering guarantee. - proxy-suite-awg-warp = lib.mkIf w.asAmneziaWg { + proxy-suite-awg-warp = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") { wants = [ "proxy-suite-warp.service" ]; }; }) diff --git a/modules/proxy-suite/wg-tunnel.nix b/modules/proxy-suite/wg-tunnel.nix new file mode 100644 index 0000000..28ed4d3 --- /dev/null +++ b/modules/proxy-suite/wg-tunnel.nix @@ -0,0 +1,138 @@ +# A WireGuard profile as a sing-box endpoint in its own process, behind a loopback SOCKS +# listener the proxy outbound dials: the WARP tunnel and AmneziaWG profiles with +# asOutbound = "singBox". +{ + lib, + pkgs, + cfg, + derived, +}: + +let + inherit (derived.constants) serviceUser runAsServiceUser; + scriptsDir = builtins.path { + name = "proxy-suite-scripts"; + path = ../../scripts; + }; + + # sing-box's "local" server has no upstream on hosts behind systemd-resolved, so the tunnel + # resolves the peer hostname like the main config, with proxy.dns.local. Destinations are + # resolved through the tunnel itself, with proxy.dns.remote. + dnsServer = tag: upstream: { + inherit tag; + type = upstream.type; + server = upstream.address; + server_port = upstream.port; + }; + mark = cfg.proxy.tproxy.proxyMark; + probe = port: url: '' + ${pkgs.curl}/bin/curl -s --noproxy "" -x socks5h://127.0.0.1:${toString port} -m "$timeout" \ + -o /dev/null ${url}''; + + # Some lines drop a share of fresh handshakes for good, and sing-box retries on the same + # source port forever. A new process binds a new port, so the watchdog exits when the peer + # stops answering and systemd starts the tunnel again. A healthy handshake takes a fraction + # of a second, so a start gets 15 seconds; a running tunnel gets three misses. The + # "direct-in" listener reaches Cloudflare through the uplink with the backend's mark (not + # urlTest.url, which is picked to be blocked here): when that fails too, the tunnel could + # not work from a new port either. + mkWatchdog = + { + tag, + tunnelPort, + directPort, + }: + pkgs.writeShellScript "proxy-suite-wg-tunnel" '' + set -uo pipefail + ${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json" & + singbox=$! + + healthy=0 + failures=0 + uplink_down=0 + since=0 + while sleep $(( healthy ? 10 : 2 )); do + kill -0 "$singbox" 2>/dev/null || { wait "$singbox"; exit 1; } + timeout=$(( healthy ? 10 : 4 )) + if ${probe tunnelPort "-f ${lib.escapeShellArg cfg.proxy.urlTest.url}"}; then + (( healthy )) || echo "proxy-suite: ${tag} is answering" >&2 + healthy=1 failures=0 uplink_down=0 + continue + fi + if ! ${probe directPort "https://1.1.1.1/cdn-cgi/trace"}; then + (( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging ${tag}" >&2 + uplink_down=1 failures=0 since=$SECONDS + continue + fi + uplink_down=0 + if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then + echo "proxy-suite: ${tag} is not answering; restarting the tunnel on a new source port" >&2 + kill "$singbox" + wait "$singbox" + exit 1 + fi + done + ''; + + # `profile` is a shell snippet, run as root, that sets $profile to the WireGuard .conf. + mkTunnel = + { + description, + unit, + tag, + profile, + tunnelPort, + directPort, + }: + let + tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" '' + set -euo pipefail + ${profile} + + # The profile is a secret, so it is converted here, as root, rather than baked into + # the store; sing-box itself runs as ${serviceUser}. + endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag} --routing-mark ${toString mark} < "$profile") + (umask 027 && ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{ + log: {level: "warn"}, + dns: {servers: [ + ${builtins.toJSON (dnsServer "local" cfg.proxy.dns.local)}, + (${builtins.toJSON (dnsServer "remote" cfg.proxy.dns.remote)} + {detour: "${tag}", domain_resolver: "local"}) + ]}, + route: { + default_domain_resolver: "remote", + rules: [{inbound: ["direct-in"], outbound: "direct"}], + final: "${tag}" + }, + inbounds: [ + {type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString tunnelPort}}, + {type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString directPort}} + ], + outbounds: [{type: "direct", tag: "direct", routing_mark: ${toString mark}}], + endpoints: [$ep + {domain_resolver: "local"}] + }' > "$RUNTIME_DIRECTORY/config.json") + ${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/config.json" + + exec ${runAsServiceUser pkgs [ "net_admin" ]} ${mkWatchdog { inherit tag tunnelPort directPort; }} + ''; + in + { + inherit description; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + # Probe-triggered restarts must not trip the start limit. + startLimitIntervalSec = 0; + serviceConfig = { + Type = "simple"; + ExecStart = tunnelScript; + Restart = "always"; + RestartSec = 2; + RuntimeDirectory = unit; + RuntimeDirectoryMode = "0750"; + UMask = "0077"; + }; + }; +in +{ + inherit mkTunnel; +} diff --git a/modules/proxy-suite/zapret.nix b/modules/proxy-suite/zapret.nix index 0db4857..1ebbe64 100644 --- a/modules/proxy-suite/zapret.nix +++ b/modules/proxy-suite/zapret.nix @@ -14,8 +14,9 @@ let zapretCfg = cfg.zapret; perAppZapretCfg = cfg.perAppRouting.zapret; + # Global AmneziaWG profiles only: an outbound one leaves the host's routes alone. awgServiceNames = map (name: "proxy-suite-awg-${name}.service") ( - builtins.attrNames cfg.amneziaWg.profiles + builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) ); zapretPackages = import ./zapret/packages.nix { inherit diff --git a/modules/proxy-suite/zapret2.nix b/modules/proxy-suite/zapret2.nix index ba1b85d..83c15ca 100644 --- a/modules/proxy-suite/zapret2.nix +++ b/modules/proxy-suite/zapret2.nix @@ -17,8 +17,9 @@ let perAppZapretCfg = cfg.perAppRouting.zapret; cutoffCfg = zapretCfg.zapret2.cutoff; inherit (import ./derived.nix { inherit lib cfg; }) constants; + # Global AmneziaWG profiles only: an outbound one leaves the host's routes alone. awgServiceNames = map (name: "proxy-suite-awg-${name}.service") ( - builtins.attrNames cfg.amneziaWg.profiles + builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) ); runtime = import ./zapret2/runtime.nix { diff --git a/nix/checks/amnezia-wg-outbound.nix b/nix/checks/amnezia-wg-outbound.nix new file mode 100644 index 0000000..5bbc745 --- /dev/null +++ b/nix/checks/amnezia-wg-outbound.nix @@ -0,0 +1,216 @@ +{ + pkgs, + evalProxySuite, + mkBadProxySuiteFixture, + mkFailingAssertions, + mkProxyCtlDerived, + mkTProxyConfig, + dnsServerByTag, +}: + +let + generated = import ./read-generated.nix; + inherit (pkgs.lib) hasInfix; + + mkFixture = + backend: + evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + inherit backend; + tproxy.enable = true; + }; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles = { + de = { + asOutbound = "interface"; + configFile = "/run/secrets/de.conf"; + }; + plain = { + asOutbound = "singBox"; + configFile = "/run/secrets/plain.conf"; + }; + home.configFile = "/run/secrets/home.conf"; + }; + }; + }; + } + ]; + singBox = mkFixture "sing-box"; + xray = mkFixture "xray"; + hybrid = mkFixture "hybrid"; + services = singBox.config.systemd.services; + startOf = + fixture: + generated.readDerivation fixture.config.systemd.services.proxy-suite-socks.serviceConfig.ExecStart; + singBoxStart = startOf singBox; + + de = services.proxy-suite-awg-de; + dePrepare = generated.readDerivation (builtins.head de.serviceConfig.ExecStartPre); + deStart = generated.readDerivation de.serviceConfig.ExecStart; + plainTunnel = generated.readDerivation services.proxy-suite-awg-plain.serviceConfig.ExecStart; + dnsServer = dnsServerByTag (mkTProxyConfig singBox) "awg-dns-de"; + + warpInterface = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy.enable = true; + amneziaWg.enable = true; + warp = { + enable = true; + configFile = "/run/secrets/wgcf-profile.conf"; + asOutbound = "interface"; + }; + }; + } + ]; +in +{ + assertions = [ + # "interface": the backend binds to the device and resolves through it. + ( + assert hasInfix + ''"bind_interface":"awg-de","domain_resolver":"awg-dns-de","routing_mark":2,"tag":"de","type":"direct"'' + singBoxStart; + assert hasInfix "_proxy_suite_record_tag_source de awg" singBoxStart; + assert + dnsServer == { + tag = "awg-dns-de"; + type = "udp"; + server = "1.1.1.1"; + server_port = 53; + bind_interface = "awg-de"; + routing_mark = 2; + }; + assert hasInfix + ''"protocol":"freedom","streamSettings":{"sockopt":{"interface":"awg-de","mark":2}},"tag":"de"'' + (startOf xray); + assert + hasInfix "_proxy_suite_add_sing_box_ob" (startOf hybrid) + && hasInfix ''"bind_interface":"awg-de"'' (startOf hybrid); + true + ) + # "interface": no routes, no bypass rule, no conflicts, always running. + ( + assert hasInfix "--outbound-fwmark 2" dePrepare; + assert builtins.length de.serviceConfig.ExecStartPre == 1; + assert !(de.serviceConfig ? ExecStopPost); + assert (de.conflicts or [ ]) == [ ]; + assert builtins.elem "multi-user.target" de.wantedBy; + assert de.serviceConfig.Restart == "on-failure"; + assert hasInfix "ping -n -c 1 -I awg-de" deStart; + assert !(builtins.elem "proxy-suite-awg-de.service" services.proxy-suite-tproxy.conflicts); + assert builtins.elem "proxy-suite-awg-home.service" services.proxy-suite-tproxy.conflicts; + assert !(builtins.elem "proxy-suite-awg-de.service" services.proxy-suite-awg-home.conflicts); + assert hasInfix ''iifname "awg-de" accept'' + singBox.config.networking.firewall.extraReversePathFilterRules; + assert (mkProxyCtlDerived singBox).awgProfiles == [ "home" ]; + true + ) + # "singBox": a tunnel unit behind a loopback SOCKS hop, fed the prepared profile. + ( + assert hasInfix ''"server":"127.0.0.1","server_port":18542,"tag":"plain","type":"socks"'' + singBoxStart; + assert hasInfix "_proxy_suite_record_tag_source plain awg" singBoxStart; + assert hasInfix "--output \"$profile\"" plainTunnel && !(hasInfix "--outbound-fwmark" plainTunnel); + assert hasInfix "warp_outbound.py --tag plain --routing-mark 2" plainTunnel; + assert hasInfix "listen_port: 18542" plainTunnel; + assert hasInfix ''detour: "plain"'' plainTunnel; + assert !(services ? proxy-suite-awg-plain-watchdog); + true + ) + # warp.asOutbound = "interface" is the AmneziaWG profile, not the sing-box tunnel. + ( + assert warpInterface.config.services.proxy-suite.amneziaWg.profiles.warp.asOutbound == "interface"; + assert !(warpInterface.config.systemd.services ? proxy-suite-warp-tunnel); + assert hasInfix ''"bind_interface":"awg-warp"'' (startOf warpInterface); + true + ) + ] + ++ mkFailingAssertions mkBadProxySuiteFixture [ + # An outbound profile without a backend. + { + enable = true; + amneziaWg = { + enable = true; + profiles.de = { + asOutbound = "interface"; + configFile = "/run/de.conf"; + }; + }; + } + # An outbound profile always runs. + { + enable = true; + proxy.enable = true; + amneziaWg = { + enable = true; + profiles.de = { + asOutbound = "singBox"; + autostart = true; + configFile = "/run/de.conf"; + }; + }; + } + # Routes for an interface that must have none. + { + enable = true; + proxy.enable = true; + amneziaWg = { + enable = true; + profiles.de = { + asOutbound = "interface"; + settings = { + addresses = [ "10.0.0.2/32" ]; + privateKey = "private"; + table = "auto"; + peers = [ + { + publicKey = "public"; + allowedIPs = [ "0.0.0.0/0" ]; + } + ]; + }; + }; + }; + } + # warp.asOutbound = "interface" without AmneziaWG. + { + enable = true; + proxy.enable = true; + warp = { + enable = true; + configFile = "/run/wgcf.conf"; + asOutbound = "interface"; + }; + } + # A profile tag colliding with a declared outbound. + { + enable = true; + proxy = { + enable = true; + outbounds = [ + { + tag = "de"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + amneziaWg = { + enable = true; + profiles.de = { + asOutbound = "singBox"; + configFile = "/run/de.conf"; + }; + }; + } + ]; +} diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 5ed0c4e..a1898e4 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -168,6 +168,18 @@ let ; }; + amneziaWgOutboundChecks = import ./amnezia-wg-outbound.nix { + inherit + pkgs + evalProxySuite + mkBadProxySuiteFixture + mkFailingAssertions + mkProxyCtlDerived + mkTProxyConfig + dnsServerByTag + ; + }; + globalProxyModeChecks = import ./global-proxy-modes.nix { inherit pkgs @@ -253,6 +265,7 @@ let ++ xrayBackendChecks.assertions ++ outboundValidationChecks.assertions ++ amneziaWgChecks.assertions + ++ amneziaWgOutboundChecks.assertions ++ zapretChecks.assertions ++ zapret2Checks.assertions ++ globalProxyModeChecks.assertions diff --git a/nix/checks/warp.nix b/nix/checks/warp.nix index 90f89da..3a925b4 100644 --- a/nix/checks/warp.nix +++ b/nix/checks/warp.nix @@ -44,20 +44,20 @@ let singBoxHop = ''"server":"127.0.0.1","server_port":18538,"tag":"warp","type":"socks"''; xrayHop = ''"protocol":"socks","settings":{"address":"127.0.0.1","port":18538},"tag":"warp"''; - singBox = mkFixture "sing-box" { asOutbound = true; }; + singBox = mkFixture "sing-box" { asOutbound = "singBox"; }; singBoxStart = startOf singBox; singBoxTunnel = tunnelOf singBox; - xray = mkFixture "xray" { asOutbound = true; }; + xray = mkFixture "xray" { asOutbound = "singBox"; }; xrayStart = startOf xray; - hybrid = mkFixture "hybrid" { asOutbound = true; }; + hybrid = mkFixture "hybrid" { asOutbound = "singBox"; }; hybridStart = startOf hybrid; auto = mkFixture "sing-box" { - asOutbound = true; + asOutbound = "singBox"; configFile = null; }; autoTunnel = tunnelOf auto; generator = mkFixture "sing-box" { - asOutbound = true; + asOutbound = "singBox"; configFile = null; generatorUrl = "https://gen.example.com/api/warp?mode=awg2"; }; @@ -97,7 +97,7 @@ let warp = { enable = true; configFile = profile; - asOutbound = true; + asOutbound = "singBox"; }; } # asAmneziaWg without AmneziaWG. @@ -116,7 +116,7 @@ let warp = { enable = true; configFile = profile; - asOutbound = true; + asOutbound = "singBox"; asAmneziaWg = true; }; proxy.enable = true; @@ -127,7 +127,7 @@ let warp = { enable = true; configFile = profile; - asOutbound = true; + asOutbound = "singBox"; }; proxy = { enable = true; diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 387858e..e205caa 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -237,6 +237,17 @@ def _toggle(unit, name, verb="status", *_): usage(f"{name} [status|on|off]") +def _warp_unit(): + """The unit behind the warp outbound: its sing-box tunnel, or an outbound AmneziaWG profile. + + A global "warp" profile belongs to `awg on warp`, not here. + """ + awg = _awg_service("warp") + if "warp" not in _awg_profiles() and svc_exists(awg): + return awg + return "proxy-suite-warp-tunnel" + + def _emit(text, qr): """Prints text, or its QR code.""" if not qr: @@ -2533,7 +2544,7 @@ COMMANDS = { "zapret": cmd_zapret, "awg": cmd_awg, "ssh": lambda *args: _toggle("proxy-suite-ssh-proxy", "ssh", *args), - "warp": lambda *args: _toggle("proxy-suite-warp-tunnel", "warp", *args), + "warp": lambda *args: _toggle(_warp_unit(), "warp", *args), "tg": lambda *args: _toggle("proxy-suite-tg-ws-proxy", "tg", *args), "apps": cmd_apps, "inbounds": cmd_inbounds, diff --git a/scripts/amneziawg_config.py b/scripts/amneziawg_config.py index 8eda655..39725da 100644 --- a/scripts/amneziawg_config.py +++ b/scripts/amneziawg_config.py @@ -284,6 +284,29 @@ def _set_interface_value(config: str, key: str, value: str) -> str: return "\n".join(lines) + "\n" +def _remove_interface_key(config: str, key: str) -> str: + pattern = re.compile(rf"^\s*{re.escape(key)}\s*=", re.IGNORECASE) + lines: list[str] = [] + in_interface = False + for line in config.splitlines(): + stripped = line.strip() + if stripped.startswith("["): + in_interface = stripped.lower() == "[interface]" + if not (in_interface and pattern.match(line)): + lines.append(line) + return "\n".join(lines) + "\n" + + +def as_outbound(config: str, fwmark: int) -> str: + """Keep the host's routes and resolver: the proxy binds to the interface instead. + + The mark lets the tunnel's own packets past TUN and TProxy capture. + """ + config = _remove_interface_key(config, "DNS") + config = _set_interface_value(config, "Table", "off") + return _set_interface_value(config, "FwMark", str(fwmark)) + + def conf_sections(config: str) -> list[tuple[str, list[tuple[str, str]]]]: """Each [Section] of a WireGuard .conf, lowercased, with its key = value lines in order. @@ -607,6 +630,12 @@ def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--manifest") parser.add_argument("--output") + parser.add_argument( + "--outbound-fwmark", + type=int, + metavar="MARK", + help="render for an outbound-only interface: no routes or DNS, packets marked MARK", + ) parser.add_argument( "--inspect", metavar="CONFIG", @@ -625,7 +654,10 @@ def main() -> int: manifest = json.loads(_read_limited(args.manifest)) if not isinstance(manifest, dict): raise ConfigError("manifest must be a JSON object") - write_private(args.output, prepare(manifest)) + config = prepare(manifest) + if args.outbound_fwmark is not None: + config = as_outbound(config, args.outbound_fwmark) + write_private(args.output, config) except (ConfigError, KeyError, OSError, json.JSONDecodeError) as exc: parser.exit(1, f"amneziawg-config: {exc}\n") return 0 diff --git a/scripts/test-amneziawg-config.py b/scripts/test-amneziawg-config.py index 6cfca8f..b90566e 100644 --- a/scripts/test-amneziawg-config.py +++ b/scripts/test-amneziawg-config.py @@ -447,6 +447,17 @@ class AmneziaWgConfigTests(unittest.TestCase): "auto", ) + def test_outbound_render_keeps_host_routes_and_resolver(self): + config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1").replace( + "Address = 10.8.0.2/32", "Address = 10.8.0.2/32\nTable = 1234\ndns = 9.9.9.9" + ) + rendered = amneziawg_config.as_outbound(config, 2) + self.assertEqual(amneziawg_config.section_values(rendered, "interface", "dns"), []) + self.assertEqual(amneziawg_config.section_values(rendered, "interface", "table"), ["off"]) + self.assertEqual(amneziawg_config.section_values(rendered, "interface", "fwmark"), ["2"]) + # The peer is untouched. + self.assertIn("Endpoint = vpn.example.com:51820", rendered) + if __name__ == "__main__": unittest.main() diff --git a/scripts/test-warp-outbound.py b/scripts/test-warp-outbound.py index 1fc6e62..8023ddd 100644 --- a/scripts/test-warp-outbound.py +++ b/scripts/test-warp-outbound.py @@ -2,7 +2,7 @@ import unittest -from warp_outbound import ConfigError, build +from warp_outbound import ConfigError, build, obfuscation_keys WGCF = """[Interface] PrivateKey = priv= @@ -38,6 +38,12 @@ class WarpOutboundTest(unittest.TestCase): ob = build(WGCF.replace("[Peer]", "RekeyAfterTime = 100-120\n[Peer]\nPersistentKeepalive = 25-35"), "warp", None) self.assertEqual(ob["peers"][0]["persistent_keepalive_interval"], 25) + def test_obfuscation_keys(self): + self.assertEqual(obfuscation_keys(WGCF), []) + awg = WGCF.replace("[Peer]", "Jc = 4\nH1 = 1-2\n[Peer]") + self.assertEqual(obfuscation_keys(awg), ["h1", "jc"]) + self.assertNotIn("jc", build(awg, "warp", None)) + def test_rejects_missing_peer(self): with self.assertRaises(ConfigError): build(WGCF.split("[Peer]")[0], "warp", None) diff --git a/scripts/warp_outbound.py b/scripts/warp_outbound.py index f9bfc3e..8afe6ea 100644 --- a/scripts/warp_outbound.py +++ b/scripts/warp_outbound.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Turn a WireGuard .conf (e.g. wgcf-profile.conf) into a sing-box WireGuard endpoint for WARP.""" +"""Turn a WireGuard .conf (a wgcf profile, an AmneziaWG profile) into a sing-box WireGuard endpoint.""" from __future__ import annotations @@ -8,7 +8,7 @@ import json import sys from typing import Any -from amneziawg_config import ConfigError, conf_sections +from amneziawg_config import VPN_INTERFACE_FIELDS, ConfigError, conf_sections def parse_conf(text: str) -> tuple[dict[str, str], dict[str, str]]: @@ -62,16 +62,33 @@ def build(text: str, tag: str, routing_mark: int | None) -> dict[str, Any]: return endpoint +def obfuscation_keys(text: str) -> list[str]: + """AmneziaWG [Interface] keys sing-box has no use for; the endpoint goes without them.""" + return sorted( + {key for name, pairs in conf_sections(text) if name == "interface" for key, _ in pairs} + & VPN_INTERFACE_FIELDS.keys() + ) + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--tag", default="warp") parser.add_argument("--routing-mark", type=int) args = parser.parse_args() + text = sys.stdin.read() try: - print(json.dumps(build(sys.stdin.read(), args.tag, args.routing_mark))) + print(json.dumps(build(text, args.tag, args.routing_mark))) except ValueError as error: - print(f"proxy-suite: warp: {error}", file=sys.stderr) + print(f"proxy-suite: {args.tag}: {error}", file=sys.stderr) return 1 + dropped = obfuscation_keys(text) + if dropped: + names = ", ".join(VPN_INTERFACE_FIELDS[key] for key in dropped) + print( + f"proxy-suite: {args.tag}: warning: sing-box speaks plain WireGuard; dropping {names}." + " A server that expects them will not answer", + file=sys.stderr, + ) return 0