From d70bcb317fce5b6b2e800aaccb58b90b6e3d41ea Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Sat, 10 Oct 2026 16:19:54 +0500 Subject: [PATCH] feat: per-app keep-running --- docs/options/index.md | 3 + docs/options/perAppRouting.md | 44 ++++++ docs/usage/.snippets/per-app-4.nix | 18 +++ docs/usage/.snippets/per-app-5.nix | 22 +++ docs/usage/per-app.md | 58 ++++++++ modules/proxy-suite/amnezia-wg.nix | 12 +- modules/proxy-suite/derived.nix | 125 ++++++++++++++++++ .../proxy-suite/options/per-app-routing.nix | 17 +++ modules/proxy-suite/options/types.nix | 11 ++ modules/proxy-suite/service-assertions.nix | 22 ++- .../service/per-app-routing/via.nix | 13 +- modules/proxy-suite/service/units.nix | 75 ++++++++++- modules/proxy-suite/zapret/common.nix | 13 +- nix/checks/per-app-routing-tproxy.nix | 113 ++++++++++++++++ .../per-app-routing-validation-resources.nix | 46 +++++++ 15 files changed, 570 insertions(+), 22 deletions(-) create mode 100644 docs/usage/.snippets/per-app-4.nix create mode 100644 docs/usage/.snippets/per-app-5.nix diff --git a/docs/options/index.md b/docs/options/index.md index 46494a2..fa97437 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -130,6 +130,7 @@ services.proxy-suite = { tproxy = { enable = false; fwmark = 17; + keepRunning = false; localSubnets = [ "192.168.0.0/16" ]; @@ -140,6 +141,7 @@ services.proxy-suite = { enable = false; fwmark = 16; interface = "psperapptun0"; + keepRunning = false; localSubnets = [ "192.168.0.0/16" ]; @@ -155,6 +157,7 @@ services.proxy-suite = { zapret = { enable = false; filterMark = 268435456; + keepRunning = false; qnum = 201; }; }; diff --git a/docs/options/perAppRouting.md b/docs/options/perAppRouting.md index 298f349..2c46e86 100644 --- a/docs/options/perAppRouting.md +++ b/docs/options/perAppRouting.md @@ -11,6 +11,7 @@ Part of the [proxy-suite options reference](./index.md). - [createDefaultProfiles](#services-proxy-suite-perapprouting-createdefaultprofiles) - [profiles](#services-proxy-suite-perapprouting-profiles) - item + - [keepRunning](#services-proxy-suite-perapprouting-profiles-keeprunning) - [name](#services-proxy-suite-perapprouting-profiles-name) - [outbound](#services-proxy-suite-perapprouting-profiles-outbound) - [route](#services-proxy-suite-perapprouting-profiles-route) @@ -21,6 +22,7 @@ Part of the [proxy-suite options reference](./index.md). - tproxy - [enable](#services-proxy-suite-perapprouting-tproxy-enable) - [fwmark](#services-proxy-suite-perapprouting-tproxy-fwmark) + - [keepRunning](#services-proxy-suite-perapprouting-tproxy-keeprunning) - [localSubnets](#services-proxy-suite-perapprouting-tproxy-localsubnets) - [routeTable](#services-proxy-suite-perapprouting-tproxy-routetable) - tun @@ -28,6 +30,7 @@ Part of the [proxy-suite options reference](./index.md). - [address](#services-proxy-suite-perapprouting-tun-address) - [fwmark](#services-proxy-suite-perapprouting-tun-fwmark) - [interface](#services-proxy-suite-perapprouting-tun-interface) + - [keepRunning](#services-proxy-suite-perapprouting-tun-keeprunning) - [localSubnets](#services-proxy-suite-perapprouting-tun-localsubnets) - [mtu](#services-proxy-suite-perapprouting-tun-mtu) - [routeTable](#services-proxy-suite-perapprouting-tun-routetable) @@ -37,6 +40,7 @@ Part of the [proxy-suite options reference](./index.md). - zapret - [enable](#services-proxy-suite-perapprouting-zapret-enable) - [filterMark](#services-proxy-suite-perapprouting-zapret-filtermark) + - [keepRunning](#services-proxy-suite-perapprouting-zapret-keeprunning) - [qnum](#services-proxy-suite-perapprouting-zapret-qnum) @@ -65,6 +69,17 @@ Profiles for ` proxy-ctl apps run -- `\. **Default:** `[ ]`\ **Example:** `[ { name = "steam-browser"; route = "proxychains"; } ]` + +## services\.proxy-suite\.perAppRouting\.profiles\.\*\.keepRunning + +Keep what this profile runs through running from boot, rather than starting it with +the first app and stopping it after the last: its ` outbound ` (an AmneziaWG +interface or profile, or a pin slot, which then stays taken), or else its ` route `’s +backend, as ` perAppRouting..keepRunning ` does\. + +**Type:** boolean\ +**Default:** `false` + ## services\.proxy-suite\.perAppRouting\.profiles\.\*\.name @@ -136,6 +151,16 @@ Firewall mark for wrapped apps’ traffic\. **Type:** signed integer\ **Default:** `17` + +## services\.proxy-suite\.perAppRouting\.tproxy\.keepRunning + +Keep the per-app TProxy backend running from boot, rather than starting it with the first app +and stopping it after the last: apps start without waiting for it\. +Under a global TUN or TProxy it stays down, and comes back once that stops\. + +**Type:** boolean\ +**Default:** `false` + ## services\.proxy-suite\.perAppRouting\.tproxy\.localSubnets @@ -185,6 +210,15 @@ Interface name\. **Type:** network interface name\ **Default:** `"psperapptun0"` + +## services\.proxy-suite\.perAppRouting\.tun\.keepRunning + +Keep the per-app TUN backend running from boot, rather than starting it with the first app +and stopping it after the last: apps start without waiting for it\. + +**Type:** boolean\ +**Default:** `false` + ## services\.proxy-suite\.perAppRouting\.tun\.localSubnets @@ -247,6 +281,16 @@ Firewall mark bit for wrapped apps’ traffic\. **Type:** signed integer\ **Default:** `268435456` + +## services\.proxy-suite\.perAppRouting\.zapret\.keepRunning + +Keep the per-app zapret backend running from boot, rather than starting it with the first app +and stopping it after the last: apps start without waiting for it\. +Under a global TUN, TProxy or AmneziaWG profile it stays down, and comes back once that stops\. + +**Type:** boolean\ +**Default:** `false` + ## services\.proxy-suite\.perAppRouting\.zapret\.qnum diff --git a/docs/usage/.snippets/per-app-4.nix b/docs/usage/.snippets/per-app-4.nix new file mode 100644 index 0000000..02a2e4f --- /dev/null +++ b/docs/usage/.snippets/per-app-4.nix @@ -0,0 +1,18 @@ +{ config, lib, pkgs, ... }: +{ + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ]; + }; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + tun = { + enable = true; + keepRunning = true; + }; + }; +}; +} diff --git a/docs/usage/.snippets/per-app-5.nix b/docs/usage/.snippets/per-app-5.nix new file mode 100644 index 0000000..151ed08 --- /dev/null +++ b/docs/usage/.snippets/per-app-5.nix @@ -0,0 +1,22 @@ +{ config, lib, pkgs, ... }: +{ + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "nl"; urlFile = "/run/secrets/nl-url"; } ]; + }; + amneziaWg = { + enable = true; + profiles.home.configFile = "/run/secrets/home.conf"; + }; + perAppRouting = { + enable = true; + tun.enable = true; + profiles = [ + { name = "game"; route = "tun"; outbound = "nl"; keepRunning = true; } + { name = "home"; outbound = "awg:home"; keepRunning = true; } + ]; + }; +}; +} diff --git a/docs/usage/per-app.md b/docs/usage/per-app.md index ecb8933..250b14c 100644 --- a/docs/usage/per-app.md +++ b/docs/usage/per-app.md @@ -100,6 +100,64 @@ services.proxy-suite = { `proxy-ctl apps rm game`. In `proxy-tui` and the desktop app, the Apps tab adds and removes them, and runs a command via an outbound. +## Keep a route running + +`tun`, `tproxy` and `zapret` start their backend with the first app and stop it after the last, +so each first app waits for it to come up. `keepRunning` keeps one running from boot instead: + +```nix +services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ]; + }; + perAppRouting = { + enable = true; + createDefaultProfiles = true; + tun = { + enable = true; + keepRunning = true; + }; + }; +}; +``` + +The per-app TProxy and zapret step aside under a global TUN or TProxy (zapret under a global +AmneziaWG profile too), as below, and come back once it stops. + +A profile through one outbound can be kept running too, with its own `keepRunning`: + +```nix +services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "nl"; urlFile = "/run/secrets/nl-url"; } ]; + }; + amneziaWg = { + enable = true; + profiles.home.configFile = "/run/secrets/home.conf"; + }; + perAppRouting = { + enable = true; + tun.enable = true; + profiles = [ + { name = "game"; route = "tun"; outbound = "nl"; keepRunning = true; } + { name = "home"; outbound = "awg:home"; keepRunning = true; } + ]; + }; +}; +``` + +- An "interface" AmneziaWG outbound keeps its rules and DNS forwarder for apps up. +- A global AmneziaWG profile is kept up for apps alone (as `--via` brings it up), unless the + profile is up globally, which carries the apps already. +- Any other outbound keeps its pin slot: it counts against `perAppRouting.via.pinSlots` + for good, and with it the route's backend stays up. + +Only declared profiles: one `proxy-ctl apps add` adds still starts with its first app. + ## Good to know - `tun`, `tproxy` and `zapret` profiles start a system service, so they ask for an admin diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index 8f41a41..184944f 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -672,9 +672,15 @@ let ExecStart = withArg start; ExecStop = withArg stop; } - // lib.optionalAttrs (cfg.proxy.enable && !outbound) { - ExecStopPost = proxyBypassDown; - } + // ( + let + # Per-app zapret back once it is down, if kept running. + stopPost = + derived.constants.withPerAppStandby "${spec.unit}${lib.optionalString spec.template "*"}.service" + (if cfg.proxy.enable then proxyBypassDown else null); + in + lib.optionalAttrs (!outbound && stopPost != null) { ExecStopPost = stopPost; } + ) # The Endpoint lookup (ownLookups) gets past the kill switch by this group, so a # profile that dropped can come back while the kill switch holds. // lib.optionalAttrs (derived.killSwitchEnabled && !outbound) { diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index f165288..275d185 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -629,6 +629,109 @@ let # Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode. clashApiEnabled = singBoxEnabled; perAppZapretEnabled = perAppZapretCfg.enable; + # The global units each per-app backend steps aside for (constants.refuseUnderGlobal), as + # systemctl patterns: they stop it as they start, and the standby unit waits them out. + perAppGlobalModes = { + "proxy-suite-per-app-tun" = [ ]; + "proxy-suite-per-app-tproxy" = [ + "proxy-suite-tproxy.service" + "proxy-suite-tun.service" + ]; + "proxy-suite-per-app-zapret" = [ + "proxy-suite-tproxy.service" + "proxy-suite-tun.service" + ] + ++ map (name: "proxy-suite-awg-${name}.service") ( + builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) + ) + ++ lib.optional awgRuntimeGlobal "proxy-suite-awg@*.service"; + }; + # A tag as proxy-ctl names its via units: in hex, as Python's str.encode().hex(). + hexOf = + s: + lib.concatMapStrings ( + c: lib.fixedWidthString 2 "0" (lib.toLower (lib.toHexString (lib.strings.charToInt c))) + ) (lib.stringToCharacters s); + # What `proxy-ctl apps run` starts for a declared profile (_run_via, cmd_apps_run), null for + # nothing of its own (direct, proxychains): `units`, in order, without ".service"; `modes`, + # the global units they step aside for; `key`, the via instance, if any. + perAppProfileUnits = + profile: + let + target = perAppViaTarget profile.outbound; + hex = hexOf target.name; + viaProfile = + target.kind != "outbound" + && perAppViaProfiles + && (target.kind == "awg" || awgGlobalProfiles ? ${target.name}); + viaInterface = !viaProfile && builtins.any (ob: ob.tag == target.name) perAppViaInterfaceOutbounds; + backend = "proxy-suite-per-app-${profile.route}"; + in + if profile.outbound == null then + if perAppGlobalModes ? ${backend} then + { + key = null; + units = [ backend ]; + modes = perAppGlobalModes.${backend}; + } + else + null + else if viaProfile then + { + key = "app-${hex}"; + # The profile brought up for the apps alone, then the via unit on its slot. + units = [ + "proxy-suite-awg-app@${target.name}" + "proxy-suite-per-app-via@app-${hex}" + ]; + modes = [ + "proxy-suite-awg-${target.name}.service" + ] + ++ lib.optional awgRuntimeGlobal "proxy-suite-awg@${target.name}.service"; + } + else if viaInterface then + { + key = "awg-${hex}"; + units = [ "proxy-suite-per-app-via@awg-${hex}" ]; + modes = [ ]; + } + else + { + key = "${profile.route}-${hex}"; + units = [ "proxy-suite-per-app-via-${profile.route}@${hex}" ]; + modes = perAppGlobalModes."proxy-suite-per-app-tproxy"; + }; + # What is kept running between apps (perAppRouting..keepRunning and + # perAppRouting.profiles.*.keepRunning), as perAppProfileUnits gives it; the standby unit + # (service/units.nix) starts it. + perAppKeepRunning = lib.unique ( + lib.concatMap + ( + route: + lib.optional + ( + cfg.perAppRouting.${route}.enable + && cfg.perAppRouting.${route}.keepRunning + && (route == "zapret" || proxyEnabled) + ) + (perAppProfileUnits { + inherit route; + outbound = null; + }) + ) + [ + "tun" + "tproxy" + "zapret" + ] + ++ builtins.filter (entry: entry != null) ( + map perAppProfileUnits (builtins.filter (profile: profile.keepRunning) cfg.perAppRouting.profiles) + ) + ); + # The via instances kept: no last app's exit stops them, and no pin is taken back from them. + perAppKeptViaKeys = lib.filter (key: key != null) (map (entry: entry.key) perAppKeepRunning); + # The global modes whose stop brings something kept back (constants.withPerAppStandby). + perAppStandbyGlobalModes = lib.unique (lib.concatMap (entry: entry.modes) perAppKeepRunning); # The system-wide instance; per-app zapret runs its own. zapretGlobalEnabled = zapretCfg.enable && zapretCfg.global.enable; zapretCutoffEnabled = @@ -808,6 +911,23 @@ let ${cfg.host.systemctl}${managerFlag} stop -- "$unit" 2>/dev/null || true done ''} ${lib.concatStringsSep " " patterns}"; + # A global mode's ExecStopPost (null: none), and after it, if needed, what brings back + # the per-app backends kept running (perAppKeepRunning) that it stopped. `unit`: its + # perAppGlobalModes pattern; a template's, "@*.service", stands for its instances. + # --no-block: the standby unit waits for this stop (After=). + withPerAppStandby = + unit: stopPost: + if + builtins.any ( + mode: + mode == unit + || (lib.hasSuffix "@*.service" unit && lib.hasPrefix (lib.removeSuffix "*.service" unit) mode) + ) perAppStandbyGlobalModes + then + lib.optionals (stopPost != null) (lib.toList stopPost) + ++ [ "-+${cfg.host.systemctl}${managerFlag} start --no-block proxy-suite-per-app-standby.service" ] + else + stopPost; # The same for a unit that needs no root at all; "+" ExecStartPre/ExecStopPost # commands still run privileged. unprivilegedServiceConfig = @@ -1127,6 +1247,11 @@ in zapretEngine perAppZapretCfg perAppZapretEnabled + perAppProfileUnits + perAppKeepRunning + perAppKeptViaKeys + perAppGlobalModes + perAppStandbyGlobalModes zapretGlobalEnabled zapretCutoffEnabled zapretCutoffProxyFallback diff --git a/modules/proxy-suite/options/per-app-routing.nix b/modules/proxy-suite/options/per-app-routing.nix index 35d2c7f..06b4015 100644 --- a/modules/proxy-suite/options/per-app-routing.nix +++ b/modules/proxy-suite/options/per-app-routing.nix @@ -20,6 +20,20 @@ let "10.0.0.0/8" ]; }; + # `globalModes`: what it steps aside for (constants.refuseUnderGlobal), or null. + keepRunning = + what: globalModes: + mkOption { + type = types.bool; + default = false; + description = '' + Keep the ${what} backend running from boot, rather than starting it with the first app + and stopping it after the last: apps start without waiting for it. + '' + + lib.optionalString (globalModes != null) '' + Under a global ${globalModes} it stays down, and comes back once that stops. + ''; + }; in { options.services.proxy-suite.perAppRouting = { @@ -64,6 +78,7 @@ in tun = { enable = mkEnableOption "per-app TUN"; + keepRunning = keepRunning "per-app TUN" null; fwmark = int 16 "Firewall mark for wrapped apps' traffic."; routeTable = int 101 "Routing table for the per-app TUN."; localSubnets = localSubnets "Subnets that skip the proxy (DNS still goes through it)."; @@ -85,6 +100,7 @@ in tproxy = { enable = mkEnableOption "per-app TProxy"; + keepRunning = keepRunning "per-app TProxy" "TUN or TProxy"; fwmark = int 17 "Firewall mark for wrapped apps' traffic."; routeTable = int 102 "Routing table for the per-app TProxy."; localSubnets = localSubnets "Subnets that skip the proxy (DNS still goes through it)."; @@ -106,6 +122,7 @@ in zapret = { enable = mkEnableOption "per-app zapret, a separate zapret for wrapped apps only"; + keepRunning = keepRunning "per-app zapret" "TUN, TProxy or AmneziaWG profile"; filterMark = int 268435456 "Firewall mark bit for wrapped apps' traffic."; qnum = int 201 "NFQUEUE number. Must differ from the global zapret's."; }; diff --git a/modules/proxy-suite/options/types.nix b/modules/proxy-suite/options/types.nix index 20e5e05..2e46bcb 100644 --- a/modules/proxy-suite/options/types.nix +++ b/modules/proxy-suite/options/types.nix @@ -94,6 +94,17 @@ let ''; example = "de"; }; + + keepRunning = mkOption { + type = types.bool; + default = false; + description = '' + Keep what this profile runs through running from boot, rather than starting it with + the first app and stopping it after the last: its `outbound` (an AmneziaWG + interface or profile, or a pin slot, which then stays taken), or else its `route`'s + backend, as `perAppRouting..keepRunning` does. + ''; + }; }; }; in diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index f39a389..42c46fa 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -512,7 +512,27 @@ let "proxy-suite: perAppRouting profile '${profile.name}': '${profile.outbound}' is both a global AmneziaWG profile and an outbound; say \"awg:${target.name}\" or \"outbound:${target.name}\"" ) ] - ) perAppRoutingCfg.profiles; + ++ [ + (mkAssertion (!profile.keepRunning || derived.perAppProfileUnits profile != null) + "proxy-suite: perAppRouting profile '${profile.name}': keepRunning has nothing to keep for route \"${profile.route}\" with no outbound" + ) + ] + ) perAppRoutingCfg.profiles + # Kept pins never give their slot back: they have to leave none short. + ++ + map + ( + route: + let + kept = builtins.filter (lib.hasPrefix "${route}-") derived.perAppKeptViaKeys; + in + mkAssertion (builtins.length kept <= derived.perAppPinSlots) + "proxy-suite: perAppRouting profiles keep ${toString (builtins.length kept)} outbounds running through per-app ${route}, more than perAppRouting.via.pinSlots (${toString derived.perAppPinSlots})" + ) + [ + "tun" + "tproxy" + ]; localProxyAuthCfg = proxyCfg.listener.auth; localProxyAuthUsed = diff --git a/modules/proxy-suite/service/per-app-routing/via.nix b/modules/proxy-suite/service/per-app-routing/via.nix index 9ad097e..a8dcb00 100644 --- a/modules/proxy-suite/service/per-app-routing/via.nix +++ b/modules/proxy-suite/service/per-app-routing/via.nix @@ -73,6 +73,15 @@ let ipFamily = cidr: if lib.hasInfix ":" cidr then "ip6" else "ip"; + # Runs `action` for a via instance kept running (perAppKeptViaKeys), `key` as shell text. + keptCase = + key: action: + lib.optionalString (ctx.perAppKeptViaKeys != [ ]) '' + case ${key} in + ${lib.concatStringsSep " | " ctx.perAppKeptViaKeys}) ${action} ;; + esac + ''; + # $1, the instance, to $key, $tag and its outbound's $interface, $table and $mark. An # awg- instance is an "interface" outbound; app- a global profile, which # proxy-suite-awg-app@ has brought up on a slot of its own. @@ -379,7 +388,7 @@ let ${viaUserRule} "$1" ''; # ExecStopPost of a user's unit: with no other user's left, the via unit goes, and the - # global profile it ran through. perApp members may only start those (polkit.nix): + # global profile it ran through, unless kept running. perApp members may only start those (polkit.nix): # stopping one under another user's apps would send them out unmarked. viaRetire = pkgs.writeShellScript "proxy-suite-per-app" '' set -euo pipefail @@ -389,6 +398,7 @@ let | ${awk} '$3 == "restart" { found = 1 } END { exit !found }'; then exit 0 fi + ${keptCase "$key" "exit 0"} ${viaUsersLock} others=$(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \ "proxy-suite-per-app-via-user@*-$key.service" \ @@ -597,6 +607,7 @@ let [[ $other =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || continue (( $(${pkgs.coreutils}/bin/date +%s) - $(${pkgs.coreutils}/bin/stat -c %Y "$slot_file") >= 60 )) || continue other_hex=$(printf '%s' "$other" | ${pkgs.coreutils}/bin/od -An -tx1 | ${pkgs.coreutils}/bin/tr -d ' \n') + ${keptCase ''"${route}-$other_hex"'' "continue"} if [[ -z $(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \ "proxy-suite-per-app-via-user@*-${route}-$other_hex.service") ]]; then echo "proxy-suite: taking back ${route} pin slot $n from '$other': nothing runs through it" >&2 diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index c030166..3e054c4 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -76,9 +76,56 @@ let # Or any outbound, through a pin slot: either way, the apps' slices and their marking. perAppViaEnabled = perAppViaAwg || perAppRouting.pinUp != { }; # A per-app backend every user's apps share. perApp members may only start it (polkit.nix): - # it goes once the last user's marking unit that requires it stops, or the last pin of it. + # it goes once the last user's marking unit that requires it stops, or the last pin of it, + # unless it is kept running (perAppRouting..keepRunning; the standby unit below). perAppSharedBackend = - unit: restartOnSwitch (lib.recursiveUpdate unit { unitConfig.StopWhenUnneeded = true; }); + name: unit: + restartOnSwitch ( + lib.recursiveUpdate unit { + unitConfig.StopWhenUnneeded = + !builtins.elem [ name ] (map (entry: entry.units) ctx.perAppKeepRunning); + } + ); + # Starts what is kept running, but what a global mode carrying its traffic holds down + # (constants.refuseUnderGlobal): its stop runs this again (constants.withPerAppStandby). + # A global AmneziaWG profile's copy for apps goes up first, waited for: the via unit reads + # its slot as it starts, so it starts again if the copy was down. + perAppStandbyStart = + entry: + let + units = entry.units; + last = "${lib.last units}.service"; + first = "${builtins.head units}.service"; + in + lib.optionalString (entry.modes != [ ]) "under_global ${lib.escapeShellArgs entry.modes} || " + + ( + if builtins.length units == 1 then + "$systemctl start --no-block ${last}\n" + else + '' + if $systemctl is-active --quiet ${first}; then + $systemctl start --no-block ${last} + else + $systemctl start ${first} && $systemctl restart --no-block ${last} + fi + '' + ); + perAppStandbyScript = ctx.pkgs.writeShellScript "proxy-suite-per-app" '' + set -u + systemctl=${ctx.constants.systemctl} + # A global mode still stopping, maybe the one whose stop started this, is waited out. + under_global() { + for _ in $(${ctx.seqBin} 1 100); do + [[ -n $($systemctl list-units --plain --no-legend --state=deactivating "$@") ]] || break + ${ctx.sleepBin} 0.1 + done + [[ -n $($systemctl list-units --plain --no-legend --state=active,activating,reloading "$@") ]] + } + # The waits last: an AmneziaWG handshake. + ${lib.concatMapStrings perAppStandbyStart ( + builtins.sort (a: b: builtins.length a.units < builtins.length b.units) ctx.perAppKeepRunning + )} + ''; # A switch restarts it rather than stopping it across activation: a shorter gap, and a # restart keeps the per-app holds (user-rules.nix). [Service] is where the switch reads it. restartOnSwitch = unit: lib.recursiveUpdate unit { serviceConfig."X-StopIfChanged" = false; }; @@ -432,7 +479,7 @@ let execStart = tproxyUpScript; # Post: also after a start that failed partway, whose marking table would # otherwise outlive it and send marked traffic out past the kill switch. - execStopPost = tproxyDownScript; + execStopPost = ctx.constants.withPerAppStandby "${serviceNames.tproxy}.service" tproxyDownScript; }) ); } @@ -457,7 +504,7 @@ let ]; execStart = scripts.startTun; execStartPost = if pureXrayEnabled then xrayTunUpScript else null; - execStopPost = tunCleanupScript; + execStopPost = ctx.constants.withPerAppStandby "${serviceNames.tun}.service" tunCleanupScript; runtimeDirectory = serviceNames.tun; stateDirectory = "proxy-suite"; }) @@ -467,7 +514,7 @@ let enable = proxyEnabled && perAppRoutingTun.enable; name = serviceNames.perAppTun; value = reloadAfterFirewall perAppRouting.perAppTunReloadScript ( - perAppSharedBackend (mkRestartingService { + perAppSharedBackend serviceNames.perAppTun (mkRestartingService { description = "proxy-suite per-app-routing TUN backend"; after = [ "network-online.target" @@ -504,7 +551,7 @@ let enable = proxyEnabled && perAppRoutingTproxy.enable; name = serviceNames.perAppTproxy; value = reloadAfterFirewall perAppRouting.perAppTproxyReloadScript ( - perAppSharedBackend (mkOneshotService { + perAppSharedBackend serviceNames.perAppTproxy (mkOneshotService { description = "proxy-suite per-app-routing TProxy backend"; after = [ "network.target" @@ -559,7 +606,21 @@ let { enable = perAppZapretEnabled; name = serviceNames.perAppZapret; - value = perAppSharedBackend { }; + value = perAppSharedBackend serviceNames.perAppZapret { }; + } + { + enable = ctx.perAppKeepRunning != [ ]; + name = "proxy-suite-per-app-standby"; + value = mkOneshotService { + description = "Start the proxy-suite per-app backends kept running"; + # After the global modes: one starting at boot is up by then, and the stop of one that + # started this is over. A template's instances are waited out by the script. + after = builtins.filter (unit: !lib.hasInfix "*" unit) ctx.perAppStandbyGlobalModes; + wantedBy = [ "multi-user.target" ]; + execStart = perAppStandbyScript; + # Run again by each global mode's stop. + extraServiceConfig.RemainAfterExit = false; + }; } { enable = perAppZapretEnabled; diff --git a/modules/proxy-suite/zapret/common.nix b/modules/proxy-suite/zapret/common.nix index b3aa0b9..d6eba2b 100644 --- a/modules/proxy-suite/zapret/common.nix +++ b/modules/proxy-suite/zapret/common.nix @@ -57,16 +57,9 @@ in }; # The per-app instance's ExecStartPre: it has nothing to add under a global mode, which # it never displaces (constants.refuseUnderGlobal); those take it down as they start. - perAppRefuseUnderGlobal = derived.constants.refuseUnderGlobal pkgs ( - [ - "proxy-suite-tproxy.service" - "proxy-suite-tun.service" - ] - ++ map (name: "proxy-suite-awg-${name}.service") ( - builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) - ) - ++ lib.optional derived.awgRuntimeGlobal "proxy-suite-awg@*.service" - ); + perAppRefuseUnderGlobal = + derived.constants.refuseUnderGlobal pkgs + derived.perAppGlobalModes."proxy-suite-per-app-zapret"; perAppZapretMarkUpScript = pkgs.writeShellScript scriptName '' set -euo pipefail diff --git a/nix/checks/per-app-routing-tproxy.nix b/nix/checks/per-app-routing-tproxy.nix index 9df403d..df8bdb3 100644 --- a/nix/checks/per-app-routing-tproxy.nix +++ b/nix/checks/per-app-routing-tproxy.nix @@ -40,6 +40,65 @@ let inherit pkgs; cfg = perAppRoutingTproxyFixture.config.services.proxy-suite; }).perAppTproxyRulesFile; + + keepRunningFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy.tun.enable = true; + perAppRouting = { + enable = true; + tun = { + enable = true; + keepRunning = true; + }; + tproxy = { + enable = true; + keepRunning = true; + }; + }; + }; + } + ]; + keepRunningServices = keepRunningFixture.config.systemd.services; + keepRunningStandby = keepRunningServices.proxy-suite-per-app-standby; + keepRunningStandbyScript = generated.readDerivation keepRunningStandby.serviceConfig.ExecStart; + + # Profiles through an outbound, kept: a pin slot, and a global AmneziaWG profile's copy for apps. + keepViaFixture = evalProxySuite [ + baseModule + { + services.proxy-suite = { + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles.home.configFile = "/run/secrets/awg.conf"; + }; + perAppRouting = { + enable = true; + tun.enable = true; + profiles = [ + { + name = "game"; + route = "tun"; + outbound = "primary"; + keepRunning = true; + } + { + name = "home-app"; + outbound = "home"; + keepRunning = true; + } + ]; + }; + }; + } + ]; + keepViaServices = keepViaFixture.config.systemd.services; + keepViaStandbyScript = generated.readDerivation keepViaServices.proxy-suite-per-app-standby.serviceConfig.ExecStart; + keepViaPerApp = mkPerAppUserRules keepViaFixture; + keepViaRetireScript = generated.readDerivation keepViaPerApp.viaRetire; + keepViaPinUpScript = generated.readDerivation keepViaPerApp.pinUp.tun; in { assertions = [ @@ -68,6 +127,60 @@ in perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy-user@".requires == [ "proxy-suite-per-app-tproxy.service" ]; + # Started with the first app, so nothing to keep running. + assert !(perAppRoutingTproxyFixture.config.systemd.services ? proxy-suite-per-app-standby); + true + ) + + # -- perAppRouting: keepRunning keeps the backends up from boot, back after a global mode -- + ( + assert !keepRunningServices.proxy-suite-per-app-tun.unitConfig.StopWhenUnneeded; + assert !keepRunningServices.proxy-suite-per-app-tproxy.unitConfig.StopWhenUnneeded; + assert keepRunningStandby.wantedBy == [ "multi-user.target" ]; + assert !keepRunningStandby.serviceConfig.RemainAfterExit; + # Ordered after the global modes, so it sees one that starts at boot or is stopping. + assert builtins.elem "proxy-suite-tun.service" keepRunningStandby.after; + assert builtins.elem "proxy-suite-tproxy.service" keepRunningStandby.after; + # The per-app TUN runs under a global mode; the per-app TProxy steps aside for one. + assert pkgs.lib.hasInfix "\n$systemctl start --no-block proxy-suite-per-app-tun.service\n" + keepRunningStandbyScript; + assert pkgs.lib.hasInfix + "\nunder_global proxy-suite-tproxy.service proxy-suite-tun.service || $systemctl start --no-block proxy-suite-per-app-tproxy.service\n" + keepRunningStandbyScript; + # A global mode's stop brings it back, after its own cleanup. + assert builtins.length keepRunningServices.proxy-suite-tun.serviceConfig.ExecStopPost == 2; + assert pkgs.lib.hasSuffix "start --no-block proxy-suite-per-app-standby.service" ( + pkgs.lib.last keepRunningServices.proxy-suite-tun.serviceConfig.ExecStopPost + ); + true + ) + + # -- perAppRouting: a kept profile keeps its outbound's units, which nothing takes down -- + ( + let + inherit (pkgs.lib) hasInfix; + # "primary" and "home" in hex, as proxy-ctl names their units. + kept = "tun-7072696d617279 | app-686f6d65)"; + in + assert hasInfix + "under_global proxy-suite-tproxy.service proxy-suite-tun.service || $systemctl start --no-block proxy-suite-per-app-via-tun@7072696d617279.service" + keepViaStandbyScript; + # The copy for apps first; the via unit again if it was down, for its slot. + assert hasInfix + "under_global proxy-suite-awg-home.service proxy-suite-awg@home.service || if $systemctl is-active --quiet proxy-suite-awg-app@home.service; then" + keepViaStandbyScript; + assert hasInfix + "$systemctl start proxy-suite-awg-app@home.service && $systemctl restart --no-block proxy-suite-per-app-via@app-686f6d65.service" + keepViaStandbyScript; + # Not by the last app's exit, nor taken back by another pin. + assert hasInfix "${kept} exit 0 ;;" keepViaRetireScript; + assert hasInfix "${kept} continue ;;" keepViaPinUpScript; + # The global profile's stop brings its copy back. + assert pkgs.lib.hasSuffix "start --no-block proxy-suite-per-app-standby.service" ( + pkgs.lib.last keepViaServices.proxy-suite-awg-home.serviceConfig.ExecStopPost + ); + # The pin holds the backend up through Requires=. + assert keepViaServices.proxy-suite-per-app-tun.unitConfig.StopWhenUnneeded; true ) diff --git a/nix/checks/per-app-routing-validation-resources.nix b/nix/checks/per-app-routing-validation-resources.nix index 6ccf96e..1670525 100644 --- a/nix/checks/per-app-routing-validation-resources.nix +++ b/nix/checks/per-app-routing-validation-resources.nix @@ -4,6 +4,52 @@ { assertions = [ + # A pin kept running holds its slot for good. + (rejects "keep 2 outbounds running through per-app tun, more than perAppRouting.via.pinSlots (1)" [ + { + services.proxy-suite = { + proxy.outbounds = [ + { + tag = "second"; + url = "http://proxy2.example.com:8080"; + } + ]; + perAppRouting = { + enable = true; + tun.enable = true; + via.pinSlots = 1; + profiles = [ + { + name = "a"; + route = "tun"; + outbound = "primary"; + keepRunning = true; + } + { + name = "b"; + route = "tun"; + outbound = "second"; + keepRunning = true; + } + ]; + }; + }; + } + ]) + (rejects "keepRunning has nothing to keep for route \"proxychains\"" [ + { + services.proxy-suite.perAppRouting = { + enable = true; + proxychains.enable = true; + profiles = [ + { + name = "curl"; + keepRunning = true; + } + ]; + }; + } + ]) (rejects "perAppRouting.tun.fwmark must differ from proxy.tproxy.proxyMark" [ { services.proxy-suite = {