From 65082aad88cd527f0fc77521b74433561da5c53f Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Sun, 4 Oct 2026 15:39:56 +0500 Subject: [PATCH] feat: per-app awg and custom via --- README.md | 4 + docs/options/amneziaWg.md | 11 + docs/options/index.md | 7 + docs/options/perAppRouting.md | 39 ++ docs/usage/.snippets/amneziawg-3.nix | 13 +- docs/usage/.snippets/amneziawg-4.nix | 11 + docs/usage/.snippets/per-app-3.nix | 15 + docs/usage/amneziawg.md | 53 +- docs/usage/per-app.md | 42 +- modules/proxy-suite/amnezia-wg.nix | 285 ++++++++-- .../proxy-suite/config-templates/sing-box.nix | 83 ++- modules/proxy-suite/derived.nix | 124 ++++- modules/proxy-suite/nftables.nix | 191 ++++--- modules/proxy-suite/options/amnezia-wg.nix | 13 + .../proxy-suite/options/per-app-routing.nix | 14 + modules/proxy-suite/options/types.nix | 14 + modules/proxy-suite/service-assertions.nix | 48 +- modules/proxy-suite/service/control.nix | 17 + modules/proxy-suite/service/default.nix | 18 + .../proxy-suite/service/per-app-routing.nix | 1 + .../service/per-app-routing/profiles.nix | 17 +- .../service/per-app-routing/user-rules.nix | 13 +- .../service/per-app-routing/via.nix | 514 ++++++++++++++++++ .../service/polkit-rules.template.js | 4 +- modules/proxy-suite/service/polkit.nix | 3 + .../backend-filter-sing-box.template.jq | 15 +- .../script-blocks/backend-jq-filter.nix | 17 + .../service/script-blocks/outbounds.nix | 43 +- modules/proxy-suite/service/scripts.nix | 10 + modules/proxy-suite/service/units.nix | 80 +++ modules/proxy-suite/zapret/common.nix | 7 + .../proxy-suite/zapret/package-builder.nix | 17 +- nix/checks/amnezia-wg-outbound.nix | 10 +- nix/checks/amnezia-wg.nix | 20 +- nix/checks/module-suite.nix | 5 + nix/checks/per-app-routing-awg.nix | 285 ++++++++++ nix/checks/user-control.nix | 5 +- pkgs/proxy-ctl/proxy_ctl.py | 381 +++++++++++-- pkgs/proxy-ctl/proxy_model.py | 31 +- pkgs/proxy-ctl/test_proxy_ctl.py | 182 ++++++- scripts/amneziawg_config.py | 20 + scripts/per_app_dns.py | 160 ++++++ scripts/test-amneziawg-config.py | 29 + 43 files changed, 2674 insertions(+), 197 deletions(-) create mode 100644 docs/usage/.snippets/amneziawg-4.nix create mode 100644 docs/usage/.snippets/per-app-3.nix create mode 100644 modules/proxy-suite/service/per-app-routing/via.nix create mode 100644 nix/checks/per-app-routing-awg.nix create mode 100644 scripts/per_app_dns.py diff --git a/README.md b/README.md index 2593b3f..b21cd9c 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,10 @@ Changes and secrets need root or the userControl group. apps [list] per-app routing profiles apps run -- [args] run a command through a profile + apps run --via -- run a command through one outbound + (--route tun|tproxy picks the method) + apps add [--route r] [--via o] add a profile without a rebuild + apps rm remove one added that way inbounds [list] server inbounds inbounds link [user] [--onion|--variant=] [--qr|--json] diff --git a/docs/options/amneziaWg.md b/docs/options/amneziaWg.md index 35fc2ce..69860f4 100644 --- a/docs/options/amneziaWg.md +++ b/docs/options/amneziaWg.md @@ -69,6 +69,7 @@ Part of the [proxy-suite options reference](./index.md). - runtime - [enable](#services-proxy-suite-amneziawg-runtime-enable) - [interfaceName](#services-proxy-suite-amneziawg-runtime-interfacename) + - [outboundKind](#services-proxy-suite-amneziawg-runtime-outboundkind) - [serverUdpPorts](#services-proxy-suite-amneziawg-serverudpports) - [toolsPackage](#services-proxy-suite-amneziawg-toolspackage) - [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage) @@ -570,6 +571,16 @@ Interface of the global profiles added at runtime\. Only one of them runs at a t **Type:** string matching the pattern ^\[A-Za-z0-9_\.-]{1,15}$\ **Default:** `"awg-rt"` + +## services\.proxy-suite\.amneziaWg\.runtime\.outboundKind + +How an outbound added with ` proxy-ctl proxy outbounds add ` runs, unless it says +(` --interface `, ` --userspace `): in wireproxy, or as an AmneziaWG interface of its own +(root hosts only), which apps can also be run through with ` proxy-ctl apps run --via `\. + +**Type:** one of “userspace”, “interface”\ +**Default:** `"userspace"` + ## services\.proxy-suite\.amneziaWg\.serverUdpPorts diff --git a/docs/options/index.md b/docs/options/index.md index 8ea2ec0..5b997c7 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -46,6 +46,7 @@ services.proxy-suite = { runtime = { enable = true; interfaceName = "awg-rt"; + outboundKind = "userspace"; }; serverUdpPorts = [ ]; toolsPackage = ‹proxy-suite's patched amneziawg-tools (pkgs/amneziawg.nix)›; @@ -138,6 +139,12 @@ services.proxy-suite = { mtu = 1400; routeTable = 101; }; + via = { + localSubnets = [ + "192.168.0.0/16" + ]; + pinSlots = 8; + }; zapret = { enable = false; filterMark = 268435456; diff --git a/docs/options/perAppRouting.md b/docs/options/perAppRouting.md index 9e81729..e47d713 100644 --- a/docs/options/perAppRouting.md +++ b/docs/options/perAppRouting.md @@ -12,6 +12,7 @@ Part of the [proxy-suite options reference](./index.md). - [profiles](#services-proxy-suite-perapprouting-profiles) - item - [name](#services-proxy-suite-perapprouting-profiles-name) + - [outbound](#services-proxy-suite-perapprouting-profiles-outbound) - [route](#services-proxy-suite-perapprouting-profiles-route) - proxychains - [enable](#services-proxy-suite-perapprouting-proxychains-enable) @@ -30,6 +31,9 @@ Part of the [proxy-suite options reference](./index.md). - [localSubnets](#services-proxy-suite-perapprouting-tun-localsubnets) - [mtu](#services-proxy-suite-perapprouting-tun-mtu) - [routeTable](#services-proxy-suite-perapprouting-tun-routetable) + - via + - [localSubnets](#services-proxy-suite-perapprouting-via-localsubnets) + - [pinSlots](#services-proxy-suite-perapprouting-via-pinslots) - zapret - [enable](#services-proxy-suite-perapprouting-zapret-enable) - [filterMark](#services-proxy-suite-perapprouting-zapret-filtermark) @@ -69,6 +73,20 @@ Unique profile name\. **Type:** string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$\ **Example:** `"steam-browser"` + +## services\.proxy-suite\.perAppRouting\.profiles\.\*\.outbound + +Send all of the app’s traffic through this outbound, past the routing rules\. An +“interface” AmneziaWG outbound (` amneziaWg.profiles..asOutbound `), or a +global AmneziaWG profile, takes the app’s packets into its interface directly, +whatever ` route ` is; any other outbound needs ` route ` “tun” or “tproxy”\. For a name +that is both a global profile and an outbound, say which: “awg:\” or +“outbound:\”\. + +**Type:** null or string\ +**Default:** `null`\ +**Example:** `"de"` + ## services\.proxy-suite\.perAppRouting\.profiles\.\*\.route @@ -192,6 +210,27 @@ Routing table for the per-app TUN\. **Type:** signed integer\ **Default:** `101` + +## services\.proxy-suite\.perAppRouting\.via\.localSubnets + +Subnets an app run ` --via ` an AmneziaWG interface (an “interface” outbound or a global +profile) still reaches directly; DNS still goes through the tunnel\. Every other +address goes through it, private ones included, as the server may serve them\. + +**Type:** list of string\ +**Default:** `[ "192.168.0.0/16" ]`\ +**Example:** `[ "192.168.0.0/16" "10.0.0.0/8" ]` + + +## services\.proxy-suite\.perAppRouting\.via\.pinSlots + +How many outbounds ` apps run --via ` can send apps through at once, for per-app TProxy +and again for per-app TUN; at most 16\. Apps via the same outbound share one\. An +“interface” AmneziaWG outbound takes none: apps enter it directly\. + +**Type:** signed integer\ +**Default:** `8` + ## services\.proxy-suite\.perAppRouting\.zapret\.enable diff --git a/docs/usage/.snippets/amneziawg-3.nix b/docs/usage/.snippets/amneziawg-3.nix index a518e25..0b9d057 100644 --- a/docs/usage/.snippets/amneziawg-3.nix +++ b/docs/usage/.snippets/amneziawg-3.nix @@ -2,10 +2,17 @@ { services.proxy-suite = { enable = true; - amneziaWg.enable = true; # no profiles needed - userControl = { + proxy.enable = true; + amneziaWg = { enable = true; - scopes = [ "services" "amneziaWg" "outbounds" ]; # optional: no sudo for these + profiles.de = { + configFile = "/run/secrets/de-awg.conf"; + asOutbound = "interface"; + }; + }; + perAppRouting = { + enable = true; + profiles = [ { name = "games"; outbound = "de"; } ]; }; }; } diff --git a/docs/usage/.snippets/amneziawg-4.nix b/docs/usage/.snippets/amneziawg-4.nix new file mode 100644 index 0000000..a518e25 --- /dev/null +++ b/docs/usage/.snippets/amneziawg-4.nix @@ -0,0 +1,11 @@ +{ config, lib, pkgs, ... }: +{ + services.proxy-suite = { + enable = true; + amneziaWg.enable = true; # no profiles needed + userControl = { + enable = true; + scopes = [ "services" "amneziaWg" "outbounds" ]; # optional: no sudo for these + }; +}; +} diff --git a/docs/usage/.snippets/per-app-3.nix b/docs/usage/.snippets/per-app-3.nix new file mode 100644 index 0000000..19dce6a --- /dev/null +++ b/docs/usage/.snippets/per-app-3.nix @@ -0,0 +1,15 @@ +{ config, lib, pkgs, ... }: +{ + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "nl"; urlFile = "/run/secrets/nl-url"; } ]; + }; + perAppRouting = { + enable = true; + tun.enable = true; + profiles = [ { name = "game"; route = "tun"; outbound = "nl"; } ]; + }; +}; +} diff --git a/docs/usage/amneziawg.md b/docs/usage/amneziawg.md index b3e4bed..e3ac975 100644 --- a/docs/usage/amneziawg.md +++ b/docs/usage/amneziawg.md @@ -64,6 +64,46 @@ host's routes and DNS alone. Use it like any other outbound: for selection, in | `"userspace"` | yes | no | Runs in wireproxy. The only mode on home-manager and Nix-on-Droid. | | `"singBox"` | no | no | Plain WireGuard inside sing-box. For servers without obfuscation, such as WARP. | +## Run single apps through it + +With [per-app routing](./per-app.md) on, `--via` sends one app through an outbound: + +```sh +proxy-ctl apps run --via de -- steam +``` + +An `"interface"` outbound takes the app's packets into its interface directly: no proxy in +between, and UDP as it is. The app's DNS goes to the profile's `DNS` servers (or to +`proxy.dns.remote` when it names none), through the tunnel, even when `/etc/resolv.conf` +points at a local resolver. While the interface is down, the app's connections fail instead of +leaving another way. A `"userspace"` or `"singBox"` outbound works like any other outbound +here: through per-app TUN or TProxy. + +A global profile works too, declared or added with `awg add`: `--via home` brings up a copy +of it for the apps alone, the same way, and takes it down after the last one exits. The +rest of the system is untouched. A profile cannot be up globally and for apps at once: while +`awg on home` holds it, `--via home` runs the app as it is, and `awg on home` stops the copy. +When a name is both a global profile and an outbound, say which: `--via awg:home` or +`--via outbound:home`. + +```nix +services.proxy-suite = { + enable = true; + proxy.enable = true; + amneziaWg = { + enable = true; + profiles.de = { + configFile = "/run/secrets/de-awg.conf"; + asOutbound = "interface"; + }; + }; + perAppRouting = { + enable = true; + profiles = [ { name = "games"; outbound = "de"; } ]; + }; +}; +``` + ## Add one without rebuilding `amneziaWg.enable` alone is enough: profiles and outbounds can come from `proxy-ctl` instead @@ -86,15 +126,21 @@ proxy-ctl awg add home ~/home.conf # a name first; a link, a file, or - proxy-ctl awg on home proxy-ctl awg rm home proxy-ctl proxy outbounds add de ~/de.conf # an outbound instead (needs proxy.enable) +proxy-ctl proxy outbounds add nl ~/nl.conf --interface # on an interface of its own ``` - A global profile works like a declared one: `awg on`, the tray menu, the kill switch. The ones added this way share one interface, `amneziaWg.runtime.interfaceName`. - An outbound runs in wireproxy (like `asOutbound = "userspace"`), so the obfuscation stays. - It cannot chain through another outbound. + With `--interface` it gets an AmneziaWG interface of its own instead (like + `asOutbound = "interface"`; root hosts only), which apps can run through directly (see + above). + `amneziaWg.runtime.outboundKind` sets which one an outbound gets when the command does not + say. Either way, it cannot chain through another outbound. - In `proxy-tui` and the desktop app, paste a `vpn://` link or a whole `.conf` onto a tab: on - the Outbounds tab it becomes an outbound, anywhere else a global profile. The AmneziaWG tab - also adds one from a prompt, and removes what was added. + the Outbounds tab it becomes an outbound, anywhere else a global profile. The Outbounds tab + also adds one on an interface of its own, and the AmneziaWG tab adds a global profile from a + prompt and removes what was added. - Hooks (`PostUp` and the like) are always refused, whoever adds the config. `--container ` picks one from a `vpn://` export that holds several. - Adding and removing takes root, or a `userControl` scope: `amneziaWg` for global profiles, @@ -116,4 +162,5 @@ proxy-ctl proxy outbounds add de ~/de.conf # an outbound instead (needs proxy.e - [`amneziaWg.profiles`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles) - [`amneziaWg.runtime`](../options/amneziaWg.md#services-proxy-suite-amneziawg-runtime-enable) - [`asOutbound`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles-name-asoutbound) +- [Route a single app](./per-app.md) - [`settings`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles-name-settings) diff --git a/docs/usage/per-app.md b/docs/usage/per-app.md index cbe0e93..6f8022a 100644 --- a/docs/usage/per-app.md +++ b/docs/usage/per-app.md @@ -63,13 +63,52 @@ services.proxy-suite = { Then run `proxy-ctl apps run browser -- chromium`. +## Through one outbound + +Send an app through one outbound you pick, past the [routing rules](./routing.md): + +```sh +proxy-ctl apps run --via nl -- firefox +proxy-ctl apps run --via nl --route tproxy -- curl https://example.com +``` + +Or name it in a profile: + +```nix +services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ { tag = "nl"; urlFile = "/run/secrets/nl-url"; } ]; + }; + perAppRouting = { + enable = true; + tun.enable = true; + profiles = [ { name = "game"; route = "tun"; outbound = "nl"; } ]; + }; +}; +``` + +- An "interface" AmneziaWG outbound, or a global AmneziaWG profile (`--via home`), takes the + app straight into its interface, with no proxy in between, and sends the app's DNS to the + profile's DNS server. See [Use an AmneziaWG config](./amneziawg.md). +- Any other outbound goes through per-app TUN or TProxy (`--route`; TUN when both are + enabled) and needs the sing-box or hybrid backend. Each outbound in use takes one of + `perAppRouting.via.pinSlots`. +- When the outbound is down, the app's connections fail; they never leave another way. +- Add profiles without a rebuild: `proxy-ctl apps add game --via nl`, then + `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. + ## Good to know - `tun`, `tproxy` and `zapret` profiles start a system service, so they ask for an admin password unless `userControl` grants the `perApp` scope (see [Control it day to day](./control.md)). - While a global TUN or TProxy is running, these three run the app without their route: - the global mode already carries its traffic. `proxy-ctl` prints a note when it does. + the global mode already carries its traffic. `proxy-ctl` prints a note when it does. So + does `--via`, except that an "interface" AmneziaWG outbound still takes the app under a + global TProxy or AmneziaWG profile. - If `/etc/resolv.conf` points only at a local resolver (such as systemd-resolved on 127.0.0.53), the app's DNS queries skip its route. `proxy-ctl` warns about this. - The app follows your [routing rules](./routing.md) like any other proxied traffic. @@ -79,3 +118,4 @@ Then run `proxy-ctl apps run browser -- chromium`. - [Wrap programs with the proxy](./wrap-apps.md): a package that always starts through a profile - [`perAppRouting.profiles`](../options/perAppRouting.md#services-proxy-suite-perapprouting-profiles) - [`perAppRouting.createDefaultProfiles`](../options/perAppRouting.md#services-proxy-suite-perapprouting-createdefaultprofiles) +- [`perAppRouting.via`](../options/perAppRouting.md#services-proxy-suite-perapprouting-via-pinslots) diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index b66b709..153d1c3 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -18,6 +18,9 @@ let awgServerUdpRulePriority runtimeAwgDir runtimeOutboundsDir + awgRuntimeIfacePrefix + awgRuntimeIfaceSlots + awgRuntimeIfaceTableBase awgRuntimeTunnelBasePort awgRuntimeTunnelSlots systemctl @@ -101,8 +104,12 @@ let # What a unit's scripts know of the profile they run. `init` is their first line and sets # $profile_name; `runDir` is the runtime directory, as shell text; `source` the arguments # amneziawg_config.py reads the profile with; `outbound` whether it is an "interface" one. + # `iface` is its interface and `table` an outbound's route table, as text for inside double + # quotes: a name the type allows only safe characters in, or a variable `init` sets. staticSpec = name: profile: { inherit name profile; + iface = profile.interfaceName; + table = if profile.asOutbound == "interface" then toString (outboundRouteTable name) else ""; template = false; unit = serviceName name; init = "profile_name=${lib.escapeShellArg name}"; @@ -124,6 +131,8 @@ let runtimeSpec = { name = "$profile_name"; profile = runtimeProfile; + iface = runtimeProfile.interfaceName; + table = ""; template = true; unit = "proxy-suite-awg@"; init = '' @@ -138,7 +147,135 @@ let source = ''--config "${runtimeAwgDir}/$profile_name.conf"''; outbound = false; }; - specConfig = spec: "${spec.runDir}/${spec.profile.interfaceName}.conf"; + # Outbounds added with `proxy outbounds add --interface`: .awg in the runtime outbound + # spool, and in .iface the slot proxy-ctl gave it, which names its interface and table. + # Instances of one template, as the global ones; hooks refused (--config), the spool being + # group-writable. + runtimeIfaceSpec = { + name = "$profile_name"; + profile = { + asOutbound = "interface"; + autostart = false; + settings = null; + }; + iface = "$interface"; + table = "$table"; + template = true; + unit = "proxy-suite-awg-if@"; + init = '' + profile_name=''${1:-} + if [[ ! $profile_name =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then + echo "proxy-suite: '$profile_name' is not an outbound tag" >&2 + exit 1 + fi + # The slot the unit started with: by its stop, the spool's entry may be gone. + slot_file="/run/proxy-suite-awg-if-$profile_name/slot" + if [[ -s $slot_file ]]; then + slot=$(${pkgs.coreutils}/bin/head -n 1 "$slot_file") + else + # O_NOFOLLOW: the spool is group-writable. + slot=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$profile_name.iface" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true) + fi + if [[ ! $slot =~ ^[0-9]+$ ]] || (( slot >= ${toString awgRuntimeIfaceSlots} )); then + echo "proxy-suite: AmneziaWG outbound '$profile_name' needs a slot in 0-${ + toString (awgRuntimeIfaceSlots - 1) + } in $profile_name.iface" >&2 + exit 1 + fi + interface="${awgRuntimeIfacePrefix}$slot" + table=$(( ${toString awgRuntimeIfaceTableBase} + slot )) + if [[ -d /run/proxy-suite-awg-if-$profile_name && ! -s $slot_file ]]; then + echo "$slot" > "$slot_file" + fi + ''; + runDir = "/run/proxy-suite-awg-if-$profile_name"; + runtimeDirectory = "proxy-suite-awg-if-%i"; + source = ''--config "${runtimeOutboundsDir}/$profile_name.awg"''; + outbound = true; + }; + # A global profile, declared or added with `awg add`, for `apps run --via `: a copy + # brought up as an outbound interface has it (no routes, no DNS), on an interface and table + # of a free slot, while apps run through it. One unit with the profile up globally: each + # stops the other (Conflicts=), since both would hold the same key with the same peer. + appManifests = pkgs.writeText "proxy-suite-awg" ( + builtins.toJSON ( + lib.mapAttrs (_: profile: toString (manifestFor profile)) derived.awgGlobalProfiles + ) + ); + appSlotDir = "${derived.constants.runtimeDir}/proxy-suite-awg-app"; + appSlotFile = ''"${appSlotDir}/slot-$slot"''; + appSpec = { + name = "$profile_name"; + profile = { + asOutbound = "interface"; + autostart = false; + settings = null; + }; + iface = "$interface"; + table = "$table"; + template = true; + unit = "proxy-suite-awg-app@"; + description = "proxy-suite AmneziaWG profile %i for the apps run through it"; + init = '' + profile_name=''${1:-} + if [[ ! $profile_name =~ ^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$ ]]; then + echo "proxy-suite: '$profile_name' is not an AmneziaWG profile name" >&2 + exit 1 + fi + manifest=$(${pkgs.jq}/bin/jq -r --arg n "$profile_name" '.[$n] // empty' ${appManifests}) + if [[ -n $manifest ]]; then + source_args=(--manifest "$manifest") + ${lib.optionalString derived.awgRuntimeGlobal '' + # Added with `awg add`: hooks refused (--config), the directory being group-writable. + elif [[ -f ${runtimeAwgDir}/$profile_name.conf ]]; then + source_args=(--config "${runtimeAwgDir}/$profile_name.conf") + ''} + else + echo "proxy-suite: no global AmneziaWG profile '$profile_name'" >&2 + exit 1 + fi + # The slot the unit holds, else a free one: the file slot- naming the profile. + slot_file="/run/proxy-suite-awg-app-$profile_name/slot" + slot="" + if [[ -s $slot_file ]]; then + slot=$(${pkgs.coreutils}/bin/head -n 1 "$slot_file") + elif [[ -d /run/proxy-suite-awg-app-$profile_name ]]; then + ${pkgs.coreutils}/bin/mkdir -p ${appSlotDir} + exec 9>>"${appSlotDir}/lock" + ${pkgs.util-linux}/bin/flock 9 + for (( n = 0; n < ${toString derived.constants.awgAppSlots}; n++ )); do + if [[ ! -e ${appSlotDir}/slot-$n || $(< ${appSlotDir}/slot-$n) == "$profile_name" ]]; then + printf '%s\n' "$profile_name" > ${appSlotDir}/slot-$n + slot=$n + break + fi + done + ${pkgs.util-linux}/bin/flock -u 9 + exec 9>&- + if [[ -z $slot ]]; then + echo "proxy-suite: all ${toString derived.constants.awgAppSlots} slots for AmneziaWG profiles apps run through are taken" >&2 + exit 1 + fi + echo "$slot" > "$slot_file" + fi + if [[ ! $slot =~ ^[0-9]+$ ]]; then + echo "proxy-suite: AmneziaWG profile '$profile_name' is not up for apps" >&2 + exit 1 + fi + interface="${derived.constants.awgAppIfacePrefix}$slot" + table=$(( ${toString derived.constants.awgAppTableBase} + slot )) + ''; + runDir = "/run/proxy-suite-awg-app-$profile_name"; + runtimeDirectory = "proxy-suite-awg-app-%i"; + source = ''"''${source_args[@]}"''; + outbound = true; + release = '' + if [[ -f ${appSlotFile} && $(< ${appSlotFile}) == "$profile_name" ]]; then + ${pkgs.coreutils}/bin/rm -f ${appSlotFile} + fi + ''; + }; + specConfig = spec: "${spec.runDir}/${spec.iface}.conf"; # Runtime profiles cannot be named in Conflicts= at build time, and share one interface: # starting any global profile stops the runtime ones still up. $1: its own instance, if one. @@ -172,9 +309,9 @@ let # Some lines drop a share of fresh flows for good, handshakes included. A new source port # is a new flow, and moving the interface to one keeps its routes, so traffic never leaks # past the tunnel while it tries again. A pinned ListenPort is left alone. - mkHandshakeHelpers = profile: '' + mkHandshakeHelpers = spec: '' awg=${awgCfg.toolsPackage}/bin/awg - interface=${lib.escapeShellArg profile.interfaceName} + interface="${spec.iface}" # Seconds since the newest handshake of any peer; a large number before the first. handshake_age() { @@ -186,7 +323,7 @@ let new_source_port() { ${ - if profile.settings != null && profile.settings.listenPort != null then + if spec.profile.settings != null && spec.profile.settings.listenPort != null then ":" else ''"$awg" set "$interface" listen-port 0 || true'' @@ -197,18 +334,18 @@ 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: '' + outboundRuleCleanup = spec: '' 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 + while ${pkgs.iproute2}/bin/ip "$family" rule del pref ${toString awgOutboundRulePriority} oif "${spec.iface}" 2>/dev/null; do :; done + ${pkgs.iproute2}/bin/ip "$family" route flush table "${spec.table}" 2>/dev/null || true done ''; - outboundRoutesUp = name: profile: '' - ${outboundRuleCleanup name profile} + outboundRoutesUp = spec: '' + ${outboundRuleCleanup spec} 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)} + if [[ -n $(${pkgs.iproute2}/bin/ip "$family" -o addr show dev "${spec.iface}" scope global) ]]; then + ${pkgs.iproute2}/bin/ip "$family" route replace default dev "${spec.iface}" table "${spec.table}" + ${pkgs.iproute2}/bin/ip "$family" rule add pref ${toString awgOutboundRulePriority} oif "${spec.iface}" table "${spec.table}" fi done ''; @@ -289,20 +426,20 @@ 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: + spec: "${pkgs.iputils}/bin/ping -n -c 1" - + lib.optionalString ( - profile.asOutbound == "interface" - ) " -I ${lib.escapeShellArg profile.interfaceName}"; + + lib.optionalString (spec.profile.asOutbound == "interface") " -I \"${spec.iface}\""; # An outbound interface keeps the host's routes and resolver, and marks its packets so TUN and - # TProxy let them past. A global one under the kill switch marks them with a mark it knows. + # TProxy let them past; its DNS servers go to runDir/dns. A global one under the kill switch + # marks them with a mark it knows. prepareCommand = spec: output: '' ${pkgs.python3}/bin/python3 ${configTool} \ ${spec.source} \ --output ${output}${ if spec.profile.asOutbound == "interface" then - " --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}" + # The DNS line goes, but per-app routing sends a wrapped app's lookups to it. + " --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark} --dns-out \"${spec.runDir}/dns\"" else lib.optionalString ( derived.killSwitchEnabled && spec.profile.asOutbound == null @@ -370,7 +507,7 @@ let for family in -4 -6; do had_table=0 for table in $(${pkgs.iproute2}/bin/ip "$family" route show table all 2>/dev/null \ - | ${pkgs.gawk}/bin/awk '$1 == "default" && $2 == "dev" && $3 == "${profile.interfaceName}" { for (i = 1; i <= NF; i++) if ($i == "table") print $(i + 1) }'); do + | ${pkgs.gawk}/bin/awk -v iface="${spec.iface}" '$1 == "default" && $2 == "dev" && $3 == iface { for (i = 1; i <= NF; i++) if ($i == "table") print $(i + 1) }'); do had_table=1 while ${pkgs.iproute2}/bin/ip "$family" rule delete table "$table" 2>/dev/null; do :; done ${pkgs.iproute2}/bin/ip "$family" route flush table "$table" 2>/dev/null || true @@ -381,17 +518,13 @@ let done if command -v nft >/dev/null; then nft list tables 2>/dev/null \ - | ${pkgs.gnugrep}/bin/grep -F " wg-quick-${profile.interfaceName}" \ + | ${pkgs.gnugrep}/bin/grep -F " wg-quick-${spec.iface}" \ | while read -r _ family table; do nft delete table "$family" "$table" 2>/dev/null || true; done 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 spec - } + ${cfg.host.resolvconfPackage}/bin/resolvconf -d "${spec.iface}" -f 2>/dev/null || true + ${pkgs.iproute2}/bin/ip link delete dev "${spec.iface}" 2>/dev/null || true + ${if outbound then outboundRuleCleanup spec else repliesDown profile + restoreSrcValidMark spec} + ${spec.release or ""} } trap cleanup ERR @@ -401,12 +534,12 @@ let --inspect "${configPath}") ${lib.optionalString (!outbound) (saveSrcValidMark spec)} ${awgCommon.awgQuickUp "$implementation" ''"${configPath}"''} - ${if outbound then outboundRoutesUp name profile else repliesUp profile} + ${if outbound then outboundRoutesUp spec else repliesUp profile} - ${mkHandshakeHelpers profile} + ${mkHandshakeHelpers spec} # 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 - ${pingVia profile} -W 1 "$probe" >/dev/null 2>&1 || true + ${pingVia spec} -W 1 "$probe" >/dev/null 2>&1 || true if (( $(handshake_age) < 1000000 )); then trap - ERR exit 0 @@ -423,12 +556,8 @@ let set -uo pipefail status=0 ${awgCfg.toolsPackage}/bin/awg-quick down "${configPath}" || status=$? - ${ - if outbound then - outboundRuleCleanup name profile - else - repliesDown profile + restoreSrcValidMark spec - } + ${if outbound then outboundRuleCleanup spec else repliesDown profile + restoreSrcValidMark spec} + ${spec.release or ""} exit "$status" ''); # A template's scripts get the instance name. @@ -437,11 +566,18 @@ let ( if outbound then { - description = "proxy-suite AmneziaWG interface behind the ${name} outbound"; + description = + spec.description or ( + if spec.template then + "proxy-suite AmneziaWG interface behind the %i outbound (added at runtime)" + else + "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" ]; + # The sync unit starts a template's instances. + wantedBy = lib.optionals (!spec.template) [ "multi-user.target" ]; startLimitIntervalSec = 0; } else @@ -602,20 +738,23 @@ let Type = "oneshot"; ExecStart = pkgs.writeShellScript "proxy-suite-awg" '' set -uo pipefail + # Each entry's unit: a wireproxy tunnel, or with .iface an interface of its own. declare -A keep=() for entry in "${runtimeOutboundsDir}"/*.awg; do [[ -e $entry ]] || continue tag=''${entry##*/} tag=''${tag%.awg} - keep[$tag]=1 - ${systemctl} start --no-block "proxy-suite-awg-tunnel@$tag.service" || true + kind=tunnel + ${lib.optionalString derived.awgRuntimeIfaceOutbounds "[[ -e ${runtimeOutboundsDir}/$tag.iface ]] && kind=if"} + keep[$kind@$tag]=1 + ${systemctl} start --no-block "proxy-suite-awg-$kind@$tag.service" || true done - ${systemctl} list-units --all --plain --no-legend 'proxy-suite-awg-tunnel@*.service' \ - | ${pkgs.gnugrep}/bin/grep -o 'proxy-suite-awg-tunnel@[^ ]*\.service' \ + ${systemctl} list-units --all --plain --no-legend 'proxy-suite-awg-tunnel@*.service' 'proxy-suite-awg-if@*.service' \ + | ${pkgs.gnugrep}/bin/grep -o 'proxy-suite-awg-\(tunnel\|if\)@[^ ]*\.service' \ | while read -r unit; do - tag=''${unit#proxy-suite-awg-tunnel@} - tag=''${tag%.service} - [[ -n ''${keep[$tag]:-} ]] || ${systemctl} stop --no-block "$unit" || true + instance=''${unit#proxy-suite-awg-} + instance=''${instance%.service} + [[ -n ''${keep[$instance]:-} ]] || ${systemctl} stop --no-block "$unit" || true done # grep finds nothing when no tunnel is loaded, which pipefail would make a failure. exit 0 @@ -636,7 +775,7 @@ let let inherit (spec) profile; egressProbe = profile.asOutbound == "interface"; - unit = if spec.template then "proxy-suite-awg@%i.service" else "${spec.unit}.service"; + unit = if spec.template then "${spec.unit}%i.service" else "${spec.unit}.service"; watchdog = pkgs.writeShellScript "proxy-suite-awg" '' ${spec.init} set -uo pipefail @@ -646,7 +785,7 @@ let echo "proxy-suite: AmneziaWG profile '$profile_name' never rekeys; nothing to watch" >&2 exec ${pkgs.coreutils}/bin/sleep infinity fi - ${mkHandshakeHelpers profile} + ${mkHandshakeHelpers spec} # Tells proxy-suite-outbound-groups at once, so a failover group this outbound is in # moves off it now rather than at its next test. hint() { @@ -672,7 +811,7 @@ let ''} stale=0 while sleep 15; do - ${pingVia profile} -W 2 "$probe" >/dev/null 2>&1 || true + ${pingVia spec} -W 2 "$probe" >/dev/null 2>&1 || true if (( $(handshake_age) <= rekey + 10 )); then stale=0 elif (( ++stale >= 2 )); then @@ -817,9 +956,16 @@ in ]; # Replies to the proxy's sockets come in on an interface the host has no route through. - services.proxy-suite.internal.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: '' - iifname "${ob.interface}" accept - '') derived.awgInterfaceOutbounds; + services.proxy-suite.internal.firewall.extraReversePathFilterRules = + lib.concatMapStrings (ob: '' + iifname "${ob.interface}" accept + '') derived.awgInterfaceOutbounds + + lib.optionalString derived.awgRuntimeIfaceOutbounds '' + iifname "${awgRuntimeIfacePrefix}*" accept + '' + + lib.optionalString derived.perAppViaProfiles '' + iifname "${derived.constants.awgAppIfacePrefix}*" accept + ''; services.proxy-suite.internal.services = lib.mkMerge [ (lib.mapAttrs' ( @@ -847,6 +993,29 @@ in "proxy-suite-awg-tunnel@" = runtimeTunnelService; proxy-suite-awg-runtime-sync = runtimeSyncService; }) + (lib.mkIf derived.perAppViaProfiles { + "proxy-suite-awg-app@" = lib.mkMerge [ + (mkService appSpec [ ]) + { + wants = [ "proxy-suite-awg-app-watchdog@%i.service" ]; + # The profile up globally, declared or added with `awg add`. + conflicts = [ + "proxy-suite-awg-%i.service" + "proxy-suite-awg@%i.service" + ]; + # Up only while proxy-ctl runs apps through it, which starts it again. + serviceConfig.Restart = lib.mkForce "no"; + } + ]; + "proxy-suite-awg-app-watchdog@" = mkWatchdog appSpec; + }) + (lib.mkIf derived.awgRuntimeIfaceOutbounds { + "proxy-suite-awg-if@" = lib.mkMerge [ + (mkService runtimeIfaceSpec [ ]) + { wants = [ "proxy-suite-awg-if-watchdog@%i.service" ]; } + ]; + "proxy-suite-awg-if-watchdog@" = mkWatchdog runtimeIfaceSpec; + }) (lib.listToAttrs ( map (ob: lib.nameValuePair (serviceName ob.name) (mkTunnelService ob)) tunnelOutbounds )) @@ -867,6 +1036,18 @@ in assertion = builtins.length interfaceNames == builtins.length (lib.unique interfaceNames); message = "proxy-suite: AmneziaWG profile interface names must be unique"; } + { + assertion = builtins.all ( + name: + !lib.hasPrefix awgRuntimeIfacePrefix name && !lib.hasPrefix derived.constants.awgAppIfacePrefix name + ) (map (name: profiles.${name}.interfaceName) profileNames); + message = "proxy-suite: AmneziaWG interface names starting with ${awgRuntimeIfacePrefix} or ${derived.constants.awgAppIfacePrefix} are for the interfaces proxy-suite brings up at runtime"; + } + { + # Their tables, per-app marks and DNS ports stay below the runtime ones'. + assertion = builtins.length derived.awgOutbounds <= 40; + message = "proxy-suite: at most 40 AmneziaWG outbound profiles"; + } { assertion = builtins.length autostartProfiles <= 1; message = "proxy-suite: at most one AmneziaWG profile may autostart"; diff --git a/modules/proxy-suite/config-templates/sing-box.nix b/modules/proxy-suite/config-templates/sing-box.nix index 839abd0..0d04706 100644 --- a/modules/proxy-suite/config-templates/sing-box.nix +++ b/modules/proxy-suite/config-templates/sing-box.nix @@ -16,6 +16,9 @@ let globalTproxy clashApiEnabled perAppRoutingTun + perAppPinSlots + perAppPinTproxy + perAppPinTun ; inherit (constants) xrayDnsBridgePorts @@ -113,10 +116,46 @@ let action = "hijack-dns"; }; - clashApiBlock = lib.optionalAttrs clashApiEnabled { - experimental.clash_api.external_controller = "127.0.0.1:${toString singBoxCfg.clashApiPort}"; + clashApiBlock = port: { + experimental.clash_api.external_controller = "127.0.0.1:${toString port}"; }; + # perAppRouting.via's pin slots (constants.perAppPinRulePriority): a selector each, which the + # backend filter fills with every outbound, block first and by default, and the Clash API + # switches to the outbound an app runs through. `match` is what of an app's connection + # tells its slot apart. + mkPins = + route: count: match: + let + slots = lib.genList (slot: slot) count; + tag = slot: "proxy-suite-pin-${route}-${toString slot}"; + in + { + inherit route; + rules = map (slot: match slot // { outbound = tag slot; }) slots; + selectors = map (slot: { + type = "selector"; + tag = tag slot; + outbounds = [ "block" ]; + default = "block"; + }) slots; + }; + pinTproxyInbound = slot: "per-app-pin-tproxy-${toString slot}"; + tproxyPins = mkPins "tproxy" perAppPinSlots (slot: { + inbound = [ (pinTproxyInbound slot) ] ++ lib.optional proxyCfg.ipv6 "${pinTproxyInbound slot}-6"; + }); + # The slot's source, which its packets are SNATed to as they enter the TUN. + tunPins = mkPins "tun" perAppPinSlots ( + slot: + let + source = constants.perAppPinTunSource slot; + in + { + inbound = [ "tun-in" ]; + source_ip_cidr = [ "${source.ipv4}/32" ] ++ lib.optional proxyCfg.ipv6 "${source.ipv6}/128"; + } + ); + mkConfig = { enableMixed ? false, @@ -135,6 +174,9 @@ let forceLocalDnsViaProxy ? false, useOutboundRoutingMark ? false, enableClashApi ? clashApiEnabled, + clashApiPort ? singBoxCfg.clashApiPort, + # perAppRouting.via's pin slots, of mkPins. + pins ? null, enableXrayDnsBridge ? hybridEnabled, xrayDnsBridgePort ? xrayDnsBridgePorts.socks, # Names the fake IP cache: TUN configs only. @@ -185,6 +227,25 @@ let listen_port = globalTproxy.port; } ) + ++ lib.optionals (enableTProxy && pins != null && pins.route == "tproxy") ( + lib.concatMap ( + slot: + [ + { + type = "tproxy"; + tag = pinTproxyInbound slot; + listen = "127.0.0.1"; + listen_port = constants.perAppPinTproxyPortBase + slot; + } + ] + ++ lib.optional proxyCfg.ipv6 { + type = "tproxy"; + tag = "${pinTproxyInbound slot}-6"; + listen = "::1"; + listen_port = constants.perAppPinTproxyPortBase + slot; + } + ) (lib.genList (slot: slot) perAppPinSlots) + ) ++ lib.optional enableTun ( { type = "tun"; @@ -215,19 +276,25 @@ let type = "block"; tag = "block"; } - ]; + ] + ++ lib.optionals (pins != null) pins.selectors; route = { default_domain_resolver = "local"; rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets ++ rules.remoteRuleSets; - rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules; + # The pins go after the common hijack-dns and sniff rules, wherever the backend + # filter finds those. + rules = + lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] + ++ rules.singBoxRoutingRules + ++ lib.optionals (pins != null) pins.rules; final = if (proxyCfg.routing.default == "proxy") then "proxy" else "direct"; } // lib.optionalAttrs (enableTun && tunAutoRoute) { auto_detect_interface = true; }; } - // lib.optionalAttrs enableClashApi clashApiBlock + // lib.optionalAttrs enableClashApi (clashApiBlock clashApiPort) ) # Fake addresses handed out survive a restart, so apps still holding one keep working. The # start script creates the directory; nothing else is stored, since TUN configs have no @@ -248,6 +315,7 @@ in tproxy = mkConfig { enableMixed = true; enableTProxy = constants.privileged; + pins = if perAppPinTproxy then tproxyPins else null; useOutboundRoutingMark = constants.privileged; xrayDnsBridgePort = xrayDnsBridgePorts.socks; }; @@ -272,13 +340,16 @@ in tunInterface = perAppRoutingTun.interface; tunAddress = perAppRoutingTun.address; tunIPv6Address = constants.perAppTunIPv6Address; + pins = if perAppPinTun then tunPins else null; + # The pins' selectors are switched through it. + enableClashApi = perAppPinTun; + clashApiPort = constants.perAppTunClashApiPort; tunMtu = perAppRoutingTun.mtu; tunAutoRoute = false; tunAutoRedirect = false; tunStrictRoute = false; forceLocalDnsViaProxy = false; useOutboundRoutingMark = globalTproxy.enable; - enableClashApi = false; xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; fakeIpCache = "per-app-tun"; }; diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 21b8191..2719310 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -200,8 +200,10 @@ let # (only sing-box listens on directPort). tunnelPort = awgTunnelBasePort + 2 * index; directPort = awgTunnelBasePort + 1 + 2 * index; - # Only an "interface" one routes by it. + # Only an "interface" one routes by it, and by this mark the apps sent into it. routeTable = constants.awgOutboundRouteTableBase + index; + perAppFwmark = constants.awgPerAppFwmarkBase + index; + perAppDnsPort = constants.awgPerAppDnsBasePort + index; } ) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles)); awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds; @@ -211,10 +213,75 @@ let awgRuntimeEnabled = cfg.amneziaWg.enable && cfg.amneziaWg.runtime.enable; awgRuntimeGlobal = awgRuntimeEnabled && cfg.host.privileged; awgRuntimeOutbounds = awgRuntimeEnabled && proxyEnabled && cfg.host.serviceManager != "supervisor"; + # Of those, ones on an AmneziaWG interface of their own (`outbounds add --interface`): root only. + awgRuntimeIfaceOutbounds = awgRuntimeOutbounds && cfg.host.privileged; # Some global profile may run: declared, or added at runtime. awgGlobalAvailable = awgGlobalProfiles != { } || awgRuntimeGlobal; # Profiles run behind a loopback SOCKS hop rather than an interface. awgTunnelOutbounds = builtins.filter (ob: ob.kind != "interface") awgOutbounds; + # `proxy-ctl apps run --via ` straight into an "interface" outbound: the marks it gives + # the apps, which the other per-app and global chains let past. + perAppViaInterfaceOutbounds = lib.optionals ( + cfg.perAppRouting.enable && cfg.host.privileged + ) awgInterfaceOutbounds; + perAppViaRuntime = cfg.perAppRouting.enable && awgRuntimeIfaceOutbounds; + # Or a global profile (declared, or added with `awg add`), brought up for the apps alone. + perAppViaProfiles = + cfg.perAppRouting.enable && cfg.host.privileged && (awgGlobalProfiles != { } || awgRuntimeGlobal); + # A per-app profile's `outbound`: "awg:" a global profile, "outbound:" an + # outbound, a bare name whichever it is. { kind; name; } with kind "awg", "outbound" or "". + perAppViaTarget = + outbound: + let + parts = builtins.match "(awg|outbound):(.*)" outbound; + in + if parts == null then + { + kind = ""; + name = outbound; + } + else + { + kind = builtins.head parts; + name = builtins.elemAt parts 1; + }; + # Whether it takes the app into an AmneziaWG interface directly ("interface" outbound, or a + # global profile, perhaps one `awg add` adds), with no per-app method; and whether a bare + # name is both a global profile and a declared outbound. + perAppViaDirect = + outbound: + let + target = perAppViaTarget outbound; + in + (target.kind != "awg" && builtins.any (ob: ob.tag == target.name) perAppViaInterfaceOutbounds) + || ( + target.kind != "outbound" + && perAppViaProfiles + && (builtins.hasAttr target.name awgGlobalProfiles || target.kind == "awg") + ); + perAppViaAmbiguous = + outbound: + let + target = perAppViaTarget outbound; + in + target.kind == "" + && builtins.hasAttr target.name awgGlobalProfiles + && builtins.elem target.name (map (ob: ob.tag) proxyCfg.outbounds); + # `apps run --via` any other outbound: a pin slot of per-app TProxy or TUN, which the + # backend sends to that outbound through a selector (sing-box only, for its Clash API). + perAppPinSlots = cfg.perAppRouting.via.pinSlots; + perAppPinEnabled = + cfg.perAppRouting.enable && singBoxEnabled && cfg.host.privileged && perAppPinSlots > 0; + perAppPinTproxy = perAppPinEnabled && cfg.perAppRouting.tproxy.enable; + perAppPinTun = perAppPinEnabled && cfg.perAppRouting.tun.enable; + perAppViaMarks = + map (ob: ob.perAppFwmark) perAppViaInterfaceOutbounds + ++ lib.optionals perAppViaRuntime ( + lib.genList (slot: constants.awgRuntimeIfacePerAppFwmarkBase + slot) constants.awgRuntimeIfaceSlots + ) + ++ lib.optionals perAppViaProfiles ( + lib.genList (slot: constants.awgAppPerAppFwmarkBase + slot) constants.awgAppSlots + ); proxyInboundsCfg = cfg.inbounds; proxyInboundsEnabled = proxyInboundsCfg.enable; @@ -632,6 +699,8 @@ let runtimeSubscriptionsDir = "${stateDir}/subscriptions.d"; # inbounds.runtime: users/.json and listeners/.json (scripts/inbound_runtime.py). runtimeInboundsDir = "${stateDir}/inbounds.d"; + # Per-app profiles added with `proxy-ctl apps add`: .json, next to the declared ones. + runtimeAppsDir = "${stateDir}/apps.d"; # Shell function for the scripts that read those spools as root. $1 a file: in a spool, # a regular file only, and never through a symlink, which would hand over any file root # can read (a share link or an error message then shows it), nor a FIFO, which would @@ -673,12 +742,53 @@ let awgOutboundRulePriority = 8991; # A global AmneziaWG profile's rules keeping the host's UDP services on the main table. awgServerUdpRulePriority = 8989; + # Apps run `--via` an "interface" AmneziaWG outbound: their mark (the base plus its + # index) sends them to its table, ahead of every other rule here (the XRay TUN's from + # 8992, sing-box's at tunAutoRouteRulePriority) and awg-quick's; the next rule turns + # them away while that table has no route. + awgPerAppFwmarkBase = 23040; + awgPerAppRulePriority = 8986; + awgPerAppUnreachablePriority = 8987; + # Their lookups go to a forwarder on loopback (scripts/per_app_dns.py), one port each, + # above the WARP devices' tunnels (18900 up, two each). + awgPerAppDnsBasePort = 19100; # Global profiles and outbounds added with proxy-ctl: .conf here, and # .awg with .port in runtimeOutboundsDir. runtimeAwgDir = "${stateDir}/amneziawg.d"; # Loopback SOCKS listeners of the runtime AmneziaWG outbounds, one per slot. awgRuntimeTunnelBasePort = 18800; awgRuntimeTunnelSlots = 32; + # Runtime "interface" outbounds: slot n in .iface is interface psawgr, with the + # table, per-app mark and per-app DNS port at these bases plus n, clear of the declared + # outbounds' (asserted). + awgRuntimeIfacePrefix = "psawgr"; + awgRuntimeIfaceSlots = 16; + awgRuntimeIfaceTableBase = 150; + awgRuntimeIfacePerAppFwmarkBase = 23040 + 64; + awgRuntimeIfaceDnsBasePort = 19100 + 40; + # Global profiles apps run through (proxy-suite-awg-app@): slot n is interface psawga, + # with the table, per-app mark and DNS port at these bases plus n. + awgAppIfacePrefix = "psawga"; + awgAppSlots = 8; + awgAppTableBase = 210; + awgAppPerAppFwmarkBase = 23232; + awgAppDnsBasePort = 19190; + # Pin slots: slot n of per-app TProxy is the backend's listener at the port base plus n, + # its mark and table at those bases plus n; one of per-app TUN is the source its packets + # are SNATed to as they enter the TUN, by its own mark and table. Each is a selector + # proxy-suite-pin--, switched through the Clash API (the per-app TUN backend's + # own). + perAppPinRulePriority = 8988; + perAppPinTproxyFwmarkBase = 23168; + perAppPinTunFwmarkBase = 23200; + perAppPinTproxyTableBase = 170; + perAppPinTunTableBase = 190; + perAppPinTproxyPortBase = 19160; + perAppPinTunSource = slot: { + ipv4 = "172.20.1.${toString (slot + 2)}"; + ipv6 = "fd66:21::${lib.toLower (lib.toHexString (slot + 2))}"; + }; + perAppTunClashApiPort = 19180; # 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. @@ -795,9 +905,21 @@ in awgGlobalAvailable awgRuntimeGlobal awgRuntimeOutbounds + awgRuntimeIfaceOutbounds awgOutbounds awgInterfaceOutbounds awgTunnelOutbounds + perAppViaInterfaceOutbounds + perAppViaRuntime + perAppViaProfiles + perAppViaTarget + perAppViaDirect + perAppViaAmbiguous + perAppViaMarks + perAppPinSlots + perAppPinEnabled + perAppPinTproxy + perAppPinTun proxyInboundsCfg proxyInboundsEnabled proxyInbounds diff --git a/modules/proxy-suite/nftables.nix b/modules/proxy-suite/nftables.nix index 9e71379..07f1c0e 100644 --- a/modules/proxy-suite/nftables.nix +++ b/modules/proxy-suite/nftables.nix @@ -11,6 +11,10 @@ let awgGlobalProfiles awgGlobalAvailable awgRuntimeGlobal + perAppViaMarks + perAppPinTproxy + perAppPinTun + perAppPinSlots ; inherit (constants) serviceUser; proxyCfg = cfg.proxy; @@ -23,6 +27,10 @@ let tgWsProxyBypassMarkLine = lib.optionalString tgWsProxyBypassEnabled '' meta mark ${toString tgWsProxyCfg.fwmark} return ''; + # Apps run `--via` an AmneziaWG interface are routed into it, not into the proxy. + perAppViaMarkLine = lib.optionalString (perAppViaMarks != [ ]) '' + meta mark { ${lib.concatMapStringsSep ", " toString perAppViaMarks} } return + ''; # Shared across all three nftables rule files that do IP routing. reservedIpBlock = '' @@ -86,10 +94,11 @@ let lib.optionalString (!proxyCfg.ipv6) "meta nfproto ipv4 " }meta l4proto { tcp, udp }"; # Both listeners share the port; `tproxy ip`/`tproxy ip6` only match their own family. - mkTproxyLines = prefix: suffix: '' - ${prefix}meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:${toString globalTproxy.port}${suffix} - ${lib.optionalString proxyCfg.ipv6 "${prefix}meta l4proto { tcp, udp } tproxy ip6 to [::1]:${toString globalTproxy.port}${suffix}"} + mkTproxyLinesTo = port: prefix: suffix: '' + ${prefix}meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:${toString port}${suffix} + ${lib.optionalString proxyCfg.ipv6 "${prefix}meta l4proto { tcp, udp } tproxy ip6 to [::1]:${toString port}${suffix}"} ''; + mkTproxyLines = mkTproxyLinesTo globalTproxy.port; nftablesRulesFile = pkgs.writeText "proxy-suite-routing" '' ${reservedIpBlock} @@ -118,40 +127,62 @@ let # inbound XRay dials unmarked, lacking CAP_NET_ADMIN), leave as they are. ct direction reply return meta skuid "${serviceUser}" return - ${tgWsProxyBypassMarkLine}${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ${tproxyProtocols} meta mark set ${toString globalTproxy.fwmark} + ${tgWsProxyBypassMarkLine}${perAppViaMarkLine}${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ${tproxyProtocols} meta mark set ${toString globalTproxy.fwmark} } } ''; - perAppTproxyRulesFile = pkgs.writeText "proxy-suite-routing" '' - ${reservedIpBlock} - table inet proxy_suite_per_app_tproxy { - chain prerouting { - type filter hook prerouting priority mangle; policy accept; - ${reservedLines} - iifname != "lo" ip saddr $RESERVED_IP return - iifname != "lo" ip6 saddr $RESERVED_IP6 return - # This host's own addresses are served here, not detoured through the proxy. - fib daddr type local return - ${perAppTproxyLocalSubnetLines} - # The backend's forged UDP replies belong to the app's flow too; an unconnected - # app socket is no match for the tproxy lookup, so the listener would take them. - ct direction reply return - ct mark ${toString perAppTproxy.fwmark} meta mark set ${toString perAppTproxy.fwmark} - ${mkTproxyLines "meta mark ${toString perAppTproxy.fwmark} " ""} - } + # Per-app TProxy, and a pin slot of it (perAppRouting.via): `mark` on the app's packets, which + # the backend takes on `port`. + mkPerAppTproxyRules = + { + table, + mark, + port, + }: + '' + ${reservedIpBlock} + table inet ${table} { + chain prerouting { + type filter hook prerouting priority mangle; policy accept; + ${reservedLines} + iifname != "lo" ip saddr $RESERVED_IP return + iifname != "lo" ip6 saddr $RESERVED_IP6 return + # This host's own addresses are served here, not detoured through the proxy. + fib daddr type local return + ${perAppTproxyLocalSubnetLines} + # The backend's forged UDP replies belong to the app's flow too; an unconnected + # app socket is no match for the tproxy lookup, so the listener would take them. + ct direction reply return + ct mark ${toString mark} meta mark set ${toString mark} + ${mkTproxyLinesTo port "meta mark ${toString mark} " ""} + } - chain output { - type route hook output priority mangle; policy accept; - ${reservedLines} - ${perAppTproxyLocalSubnetLines} - meta mark ${toString globalTproxy.proxyMark} return - ct direction reply return - ${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"} ct mark ${toString perAppTproxy.fwmark} meta mark set ${toString perAppTproxy.fwmark} - meta mark ${toString perAppTproxy.fwmark} return - } - } - ''; + chain output { + type route hook output priority mangle; policy accept; + ${reservedLines} + ${perAppTproxyLocalSubnetLines} + meta mark ${toString globalTproxy.proxyMark} return + ct direction reply return + ${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"} ct mark ${toString mark} meta mark set ${toString mark} + meta mark ${toString mark} return + } + } + ''; + + perAppTproxyRulesFile = pkgs.writeText "proxy-suite-routing" (mkPerAppTproxyRules { + table = "proxy_suite_per_app_tproxy"; + mark = perAppTproxy.fwmark; + inherit (globalTproxy) port; + }); + perAppPinTproxyRulesFiles = lib.genList ( + slot: + pkgs.writeText "proxy-suite-routing" (mkPerAppTproxyRules { + table = "proxy_suite_per_app_via_tproxy_${toString slot}"; + mark = constants.perAppPinTproxyFwmarkBase + slot; + port = constants.perAppPinTproxyPortBase + slot; + }) + ) (if perAppPinTproxy then perAppPinSlots else 0); # Everything proxy-suite sends itself, or has already taken into the proxy, gets past; the # rest is what TUN, TProxy or a global AmneziaWG profile would have taken, had it been up. @@ -163,7 +194,14 @@ let ++ lib.optional perAppTun.enable perAppTun.fwmark ++ lib.optional perAppTproxy.enable perAppTproxy.fwmark ++ lib.optional tgWsProxyBypassEnabled tgWsProxyCfg.fwmark - ++ lib.optional awgGlobalAvailable constants.awgGlobalFwmark; + ++ lib.optional awgGlobalAvailable constants.awgGlobalFwmark + ++ perAppViaMarks + ++ lib.optionals perAppPinTproxy ( + lib.genList (slot: constants.perAppPinTproxyFwmarkBase + slot) perAppPinSlots + ) + ++ lib.optionals perAppPinTun ( + lib.genList (slot: constants.perAppPinTunFwmarkBase + slot) perAppPinSlots + ); awgGlobalInterfaces = lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles ++ lib.optional awgRuntimeGlobal cfg.amneziaWg.runtime.interfaceName; @@ -231,34 +269,63 @@ let } ''; - perAppTunChainFile = pkgs.writeText "proxy-suite-routing" '' - ${reservedIpBlock} - table inet proxy_suite_per_app_tun { - # The per-user cgroup mark rules are added here at runtime; `output` reaches it - # by two paths, so they are written once. Defined first: a jump only resolves - # to a chain nft has already read. - chain app_mark { - } - chain output { - type route hook output priority mangle; policy accept; - # Replies to connections from outside leave the way they came, not through the TUN. - ct direction reply return - ct mark ${toString perAppTun.fwmark} meta mark set ${toString perAppTun.fwmark} - meta mark ${toString perAppTun.fwmark} return - # A wrapped app's DNS goes through the TUN even when its resolver sits on a - # local or reserved address, as the global TUN's dport 53 ip rules do: - # otherwise names resolve outside the proxy, fake DNS never sees them, and - # domain rules match nothing. - meta l4proto { tcp, udp } th dport 53 goto app_mark - ip daddr $RESERVED_IP return - ip6 daddr $RESERVED_IP6 return - ${lib.concatMapStrings (cidr: '' - ${ipFamily cidr} daddr ${cidr} return - '') perAppTun.localSubnets} - goto app_mark - } - } - ''; + # Per-app TUN, and a pin slot of it: `mark` on the app's packets routes them into the TUN. + # `snat`: the addresses a pin slot's packets enter the TUN from, which the backend tells the + # slot by. The app picked its source on the host's route, before the mark moved it here. + mkPerAppTunChain = + { + table, + mark, + snat ? null, + }: + '' + ${reservedIpBlock} + table inet ${table} { + # The per-user cgroup mark rules are added here at runtime; `output` reaches it + # by two paths, so they are written once. Defined first: a jump only resolves + # to a chain nft has already read. + chain app_mark { + } + chain output { + type route hook output priority mangle; policy accept; + # Replies to connections from outside leave the way they came, not through the TUN. + ct direction reply return + ct mark ${toString mark} meta mark set ${toString mark} + meta mark ${toString mark} return + # A wrapped app's DNS goes through the TUN even when its resolver sits on a + # local or reserved address, as the global TUN's dport 53 ip rules do: + # otherwise names resolve outside the proxy, fake DNS never sees them, and + # domain rules match nothing. + meta l4proto { tcp, udp } th dport 53 goto app_mark + ip daddr $RESERVED_IP return + ip6 daddr $RESERVED_IP6 return + ${lib.concatMapStrings (cidr: '' + ${ipFamily cidr} daddr ${cidr} return + '') perAppTun.localSubnets} + goto app_mark + } + ${lib.optionalString (snat != null) '' + chain postrouting { + type nat hook postrouting priority srcnat; policy accept; + oifname "${perAppTun.interface}" meta mark ${toString mark} meta nfproto ipv4 snat ip to ${snat.ipv4} + ${lib.optionalString proxyCfg.ipv6 ''oifname "${perAppTun.interface}" meta mark ${toString mark} meta nfproto ipv6 snat ip6 to ${snat.ipv6}''} + } + ''} + } + ''; + + perAppTunChainFile = pkgs.writeText "proxy-suite-routing" (mkPerAppTunChain { + table = "proxy_suite_per_app_tun"; + mark = perAppTun.fwmark; + }); + perAppPinTunChainFiles = lib.genList ( + slot: + pkgs.writeText "proxy-suite-routing" (mkPerAppTunChain { + table = "proxy_suite_per_app_via_tun_${toString slot}"; + mark = constants.perAppPinTunFwmarkBase + slot; + snat = constants.perAppPinTunSource slot; + }) + ) (if perAppPinTun then perAppPinSlots else 0); ip = "${pkgs.iproute2}/bin/ip"; nft = "${pkgs.nftables}/bin/nft"; @@ -270,8 +337,10 @@ in nftablesRulesFile killSwitchRulesFile perAppTproxyRulesFile + perAppPinTproxyRulesFiles perAppZapretRulesFile perAppTunChainFile + perAppPinTunChainFiles ip nft ; diff --git a/modules/proxy-suite/options/amnezia-wg.nix b/modules/proxy-suite/options/amnezia-wg.nix index b037c4b..b36b817 100644 --- a/modules/proxy-suite/options/amnezia-wg.nix +++ b/modules/proxy-suite/options/amnezia-wg.nix @@ -83,6 +83,19 @@ in default = "awg-rt"; description = "Interface of the global profiles added at runtime. Only one of them runs at a time, so they share it."; }; + + outboundKind = mkOption { + type = types.enum [ + "userspace" + "interface" + ]; + default = "userspace"; + description = '' + How an outbound added with `proxy-ctl proxy outbounds add` runs, unless it says + (`--interface`, `--userspace`): in wireproxy, or as an AmneziaWG interface of its own + (root hosts only), which apps can also be run through with `proxy-ctl apps run --via`. + ''; + }; }; profiles = mkOption { diff --git a/modules/proxy-suite/options/per-app-routing.nix b/modules/proxy-suite/options/per-app-routing.nix index 6752255..b8c71b6 100644 --- a/modules/proxy-suite/options/per-app-routing.nix +++ b/modules/proxy-suite/options/per-app-routing.nix @@ -85,6 +85,20 @@ in localSubnets = localSubnets "Subnets that skip the proxy (DNS still goes through it)."; }; + via = { + pinSlots = int 8 '' + How many outbounds `apps run --via` can send apps through at once, for per-app TProxy + and again for per-app TUN; at most 16. Apps via the same outbound share one. An + "interface" AmneziaWG outbound takes none: apps enter it directly. + ''; + + localSubnets = localSubnets '' + Subnets an app run `--via` an AmneziaWG interface (an "interface" outbound or a global + profile) still reaches directly; DNS still goes through the tunnel. Every other + address goes through it, private ones included, as the server may serve them. + ''; + }; + zapret = { enable = mkEnableOption "per-app zapret, a separate zapret for wrapped apps only"; filterMark = int 268435456 "Firewall mark bit for wrapped apps' traffic."; diff --git a/modules/proxy-suite/options/types.nix b/modules/proxy-suite/options/types.nix index fa08915..20e5e05 100644 --- a/modules/proxy-suite/options/types.nix +++ b/modules/proxy-suite/options/types.nix @@ -80,6 +80,20 @@ let "tproxy" or "zapret". ''; }; + + outbound = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Send all of the app's traffic through this outbound, past the routing rules. An + "interface" AmneziaWG outbound (`amneziaWg.profiles..asOutbound`), or a + global AmneziaWG profile, takes the app's packets into its interface directly, + whatever `route` is; any other outbound needs `route` "tun" or "tproxy". For a name + that is both a global profile and an outbound, say which: "awg:" or + "outbound:". + ''; + example = "de"; + }; }; }; in diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 3ade5d1..01da92a 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -455,7 +455,53 @@ let (requires hasZapretProfiles perAppZapretCfg.enable "route=zapret in perAppRouting.profiles" "perAppRouting.zapret.enable" ) - ]; + (mkAssertion + ( + !lib.any ( + mark: + builtins.elem mark ( + [ + globalTproxy.fwmark + globalTproxy.proxyMark + perAppRoutingTun.fwmark + perAppRoutingTproxy.fwmark + constants.awgGlobalFwmark + constants.awgInboundFwmark + ] + ++ lib.optional tgWsProxyCfg.enable tgWsProxyCfg.fwmark + ) + ) derived.perAppViaMarks + ) + "proxy-suite: apps run --via an AmneziaWG interface are marked from ${toString constants.awgPerAppFwmarkBase} up, which a proxy.tproxy, perAppRouting or tgWsProxy fwmark also uses" + ) + (mkAssertion ( + perAppRoutingCfg.via.pinSlots <= 16 + ) "proxy-suite: perAppRouting.via.pinSlots is at most 16") + ] + # An "interface" AmneziaWG outbound or a global profile takes the app directly; any other + # outbound, a pin slot of the profile's route. A name declared nowhere may be one added at + # runtime; one that is both a global profile and an outbound has to say which. + ++ lib.concatMap ( + profile: + let + target = derived.perAppViaTarget profile.outbound; + direct = derived.perAppViaDirect profile.outbound; + pinned = + target.kind != "awg" + && ( + (profile.route == "tproxy" && derived.perAppPinTproxy) + || (profile.route == "tun" && derived.perAppPinTun) + ); + in + lib.optionals (profile.outbound != null) [ + (mkAssertion (direct || pinned) + "proxy-suite: perAppRouting profile '${profile.name}': outbound '${profile.outbound}' needs route \"tproxy\" or \"tun\" with that method enabled, on a privileged host with the sing-box or hybrid backend; or an \"interface\" AmneziaWG outbound (amneziaWg.profiles..asOutbound), or a global AmneziaWG profile on a privileged host" + ) + (mkAssertion (!derived.perAppViaAmbiguous profile.outbound) + "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; localProxyAuthCfg = proxyCfg.listener.auth; localProxyAuthUsed = diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 1dc25da..29d1265 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -26,6 +26,8 @@ let amneziaWgProfileNamesFile awgRuntimeGlobal awgRuntimeOutbounds + awgRuntimeIfaceOutbounds + perAppViaRuntime proxySuiteScriptsDir ruleSets pkgs @@ -38,6 +40,7 @@ let proxyInboundsSubscriptionsFile ; inherit (ctx.perAppRouting) + perAppViaFile perAppRoutingProfilesFile proxychainsConfigFile proxychainsQuietArg @@ -73,6 +76,17 @@ in PER_APP_ROUTING_TPROXY_ENABLED = flag perAppRoutingTproxy.enable; PER_APP_ROUTING_ZAPRET_ENABLED = flag perAppZapretCfg.enable; PER_APP_ROUTING_PROFILES_FILE = toString perAppRoutingProfilesFile; + # And the ones `apps add` adds. + RUNTIME_APPS_DIR = constants.runtimeAppsDir; + # The outbounds `apps run --via` takes, tag -> its interface and mark. + PER_APP_VIA_FILE = toString perAppViaFile; + # And the runtime ones, on their own interfaces (.iface in the outbound spool). + PER_APP_VIA_RUNTIME = flag perAppViaRuntime; + # And global AmneziaWG profiles, each brought up apart for the apps. + PER_APP_VIA_PROFILES = flag ctx.perAppViaProfiles; + # Any other outbound, through a pin slot of these routes. + PER_APP_PIN_TPROXY = flag ctx.perAppPinTproxy; + PER_APP_PIN_TUN = flag ctx.perAppPinTun; PROXYCHAINS_CONFIG = toString proxychainsConfigFile; PROXYCHAINS_QUIET_ARG = lib.removeSuffix " " proxychainsQuietArg; ROUTE_MODE_STATE_FILE = routeModeStateFile; @@ -94,6 +108,9 @@ in AWG_CONFIG_TOOL = "${proxySuiteScriptsDir}/amneziawg_config.py"; AWG_TUNNEL_BASE_PORT = toString constants.awgRuntimeTunnelBasePort; AWG_TUNNEL_SLOTS = toString constants.awgRuntimeTunnelSlots; + AWG_RUNTIME_IFACE_OUTBOUNDS = flag awgRuntimeIfaceOutbounds; + AWG_RUNTIME_OUTBOUND_KIND = cfg.amneziaWg.runtime.outboundKind; + AWG_IFACE_SLOTS = toString constants.awgRuntimeIfaceSlots; WL_FILE = toString ( pkgs.writeText "proxy-suite-control" ( builtins.toJSON ( diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index b5e484d..b37cb6b 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -91,6 +91,10 @@ let path = constants.runtimeAwgDir; scope = "amneziaWg"; } + ++ lib.optional cfg.perAppRouting.enable { + path = constants.runtimeAppsDir; + scope = "perApp"; + } ++ lib.optional derived.zapretCutoffEnabled { path = "${constants.zapret2CutoffDir}/requests"; scope = "zapret"; @@ -352,6 +356,20 @@ lib.mkMerge [ "${constants.runtimeInboundsDir}/listeners" ] )) + # Per-app profiles added at runtime: read by everyone who runs apps, written with the + # perApp scope. + (lib.mkIf (cfg.enable && cfg.perAppRouting.enable) [ + "d ${constants.runtimeAppsDir} ${ + if !constants.privileged then + "0700 - -" + else if userControlAllows "perApp" then + "2775 root ${userControlCfg.group}" + else if derived.userControlAnyAllows "perApp" then + "2775 root root" + else + "0755 root root" + } -" + ]) # Global AmneziaWG profiles added at runtime. Listable, so the tray and TUI show # their names to everyone; each file is 0600 (amneziawg_config.py writes it so). (lib.mkIf (cfg.enable && derived.awgRuntimeGlobal) [ diff --git a/modules/proxy-suite/service/per-app-routing.nix b/modules/proxy-suite/service/per-app-routing.nix index 9efba4f..7e72f13 100644 --- a/modules/proxy-suite/service/per-app-routing.nix +++ b/modules/proxy-suite/service/per-app-routing.nix @@ -42,6 +42,7 @@ slices // import ./per-app-routing/profiles.nix { inherit ctx; } // import ./per-app-routing/backend-scripts.nix { inherit ctx; } // userRules +// import ./per-app-routing/via.nix { inherit ctx userRules; } // { inherit (builders) mkAnchorService; } diff --git a/modules/proxy-suite/service/per-app-routing/profiles.nix b/modules/proxy-suite/service/per-app-routing/profiles.nix index dc6c7aa..3b75df1 100644 --- a/modules/proxy-suite/service/per-app-routing/profiles.nix +++ b/modules/proxy-suite/service/per-app-routing/profiles.nix @@ -70,16 +70,15 @@ let ''; proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q "; - hasProxychainsProfiles = builtins.any ( - profile: profile.route == "proxychains" - ) effectivePerAppRoutingProfiles; - hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles; - hasTproxyProfiles = builtins.any ( - profile: profile.route == "tproxy" - ) effectivePerAppRoutingProfiles; - hasZapretProfiles = builtins.any ( - profile: profile.route == "zapret" + # A profile run straight into an AmneziaWG interface uses no method, whatever its route. + methodProfiles = builtins.filter ( + profile: (profile.outbound or null) == null || !ctx.perAppViaDirect profile.outbound ) effectivePerAppRoutingProfiles; + hasRoute = route: builtins.any (profile: profile.route == route) methodProfiles; + hasProxychainsProfiles = hasRoute "proxychains"; + hasTunProfiles = hasRoute "tun"; + hasTproxyProfiles = hasRoute "tproxy"; + hasZapretProfiles = hasRoute "zapret"; in { inherit diff --git a/modules/proxy-suite/service/per-app-routing/user-rules.nix b/modules/proxy-suite/service/per-app-routing/user-rules.nix index 656f363..92fa62c 100644 --- a/modules/proxy-suite/service/per-app-routing/user-rules.nix +++ b/modules/proxy-suite/service/per-app-routing/user-rules.nix @@ -16,18 +16,24 @@ }: let + # `prelude` runs first and may set what the rest reads: a template whose instance carries + # more than the uid turns its $1 into the uid and sets the shell variables that `nftTable`, + # `markRule` and `sliceNameArg` (the slice's name, as shell text) then name. mkUserRuleStart = { name, nftFamily, nftTable, nftChain, - sliceName, + sliceName ? null, + sliceNameArg ? lib.escapeShellArg sliceName, sliceLabel, markRule, + prelude ? "", }: pkgs.writeShellScript "proxy-suite-per-app" '' set -euo pipefail + ${prelude} uid="$1" if ! [[ $uid =~ ^[0-9]+$ ]]; then echo "proxy-suite: '$uid' is not a uid" >&2 @@ -44,7 +50,7 @@ let # The user owns this subtree and names its directories, quotes and semicolons included: # only a path nft reads as the one quoted string below, never one that closes the quote # and runs nft commands of its own as root. systemd's names never need more. - cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} \ + cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${sliceNameArg} \ | ${grepBin} -E '^[A-Za-z0-9@._:+,=\\/-]+$' | ${headBin} -n1 || true) if [ -z "$cgroup_dir" ]; then echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2 @@ -74,9 +80,11 @@ let nftFamily, nftTable, nftChain, + prelude ? "", }: pkgs.writeShellScript "proxy-suite-per-app" '' set -euo pipefail + ${prelude} uid="$1" rule_comment_prefix="proxy-suite-${name}-user-$uid" handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \ @@ -140,6 +148,7 @@ let }; in { + inherit mkUserRuleStart mkUserRuleStop; inherit perAppTunUserRuleStart perAppTunUserRuleStop diff --git a/modules/proxy-suite/service/per-app-routing/via.nix b/modules/proxy-suite/service/per-app-routing/via.nix new file mode 100644 index 0000000..3cfe0fa --- /dev/null +++ b/modules/proxy-suite/service/per-app-routing/via.nix @@ -0,0 +1,514 @@ +# `proxy-ctl apps run --via `: an app's traffic straight into an "interface" AmneziaWG +# outbound, past the proxy (proxy-suite-per-app-via@awg-); or, for any other outbound, +# into a pin slot of per-app TProxy or TUN, whose selector in the backend sends it there +# (proxy-suite-per-app-via-@). The tag goes in hex: that keeps it out of +# systemd's slice hierarchy, where "de" would be the parent of "de-2", and nft's cgroup match +# would take both. +{ ctx, userRules }: + +let + inherit (ctx) + lib + pkgs + cfg + constants + perAppRoutingCfg + perAppViaInterfaceOutbounds + perAppViaRuntime + perAppViaProfiles + perAppPinSlots + perAppPinTproxy + perAppPinTun + perAppRoutingTun + singBoxCfg + builders + proxySuiteScriptsDir + python3 + ip + nft + jq + ; + inherit (constants) + awgPerAppRulePriority + awgPerAppUnreachablePriority + runtimeOutboundsDir + awgRuntimeIfacePrefix + awgRuntimeIfaceSlots + awgRuntimeIfaceTableBase + awgRuntimeIfacePerAppFwmarkBase + awgRuntimeIfaceDnsBasePort + ; + inherit (import ../../nftables.nix { inherit lib pkgs cfg; }) + perAppPinTproxyRulesFiles + perAppPinTunChainFiles + ; + + remoteDns = cfg.proxy.dns.remote.address; + # proxy.dns.remote, for a profile with no DNS line of its own, if it is an address. + fallbackDns = lib.optional ( + builtins.match "[0-9.]+|[0-9A-Fa-f:]*:[0-9A-Fa-f:.]*" remoteDns != null + ) remoteDns; + + # tag -> what an instance needs of its outbound. proxy-ctl reads it too, to tell which tags + # take this path. + perAppViaFile = pkgs.writeText "proxy-suite-per-app" ( + builtins.toJSON ( + lib.listToAttrs ( + map ( + ob: + lib.nameValuePair ob.tag { + inherit (ob) interface; + table = ob.routeTable; + mark = ob.perAppFwmark; + dnsPort = ob.perAppDnsPort; + unit = "proxy-suite-awg-${ob.name}.service"; + dnsFile = "/run/proxy-suite-awg-${ob.name}/dns"; + inherit fallbackDns; + } + ) perAppViaInterfaceOutbounds + ) + ) + ); + + ipFamily = cidr: if lib.hasInfix ":" cidr then "ip6" else "ip"; + + # $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. + resolveInstance = '' + key=''${1:-} + if [[ ! $key =~ ^(awg|app)-([0-9a-f][0-9a-f]){1,64}$ ]]; then + echo "proxy-suite: '$key' is not a per-app via instance" >&2 + exit 1 + fi + tag=$(printf '%b' "$(printf '%s' "''${key#*-}" | ${pkgs.gnused}/bin/sed 's/../\\x&/g')") + if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then + echo "proxy-suite: '$tag' is not an outbound tag" >&2 + exit 1 + fi + if [[ $key == app-* ]]; then + ${ + if perAppViaProfiles then + '' + slot=$(${pkgs.coreutils}/bin/head -n 1 "/run/proxy-suite-awg-app-$tag/slot" 2>/dev/null || true) + if [[ ! $slot =~ ^[0-9]+$ ]] || (( slot >= ${toString constants.awgAppSlots} )); then + echo "proxy-suite: AmneziaWG profile '$tag' is not up for apps (proxy-suite-awg-app@$tag)" >&2 + exit 1 + fi + entry=$(${jq} -nc --arg t "$tag" --argjson s "$slot" --argjson fallback ${lib.escapeShellArg (builtins.toJSON fallbackDns)} '{ + interface: ("${constants.awgAppIfacePrefix}" + ($s | tostring)), + table: (${toString constants.awgAppTableBase} + $s), + mark: (${toString constants.awgAppPerAppFwmarkBase} + $s), + dnsPort: (${toString constants.awgAppDnsBasePort} + $s), + dnsFile: ("/run/proxy-suite-awg-app-" + $t + "/dns"), + fallbackDns: $fallback + }') + '' + else + '' + echo "proxy-suite: apps cannot run through global AmneziaWG profiles here" >&2 + exit 1 + '' + } + elif ! entry=$(${jq} -ce --arg t "$tag" '.[$t] // empty' ${perAppViaFile}); then + ${lib.optionalString perAppViaRuntime '' + # One added at runtime: its slot in the spool, which is group-writable (O_NOFOLLOW). + slot=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$tag.iface" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true) + if [[ $slot =~ ^[0-9]+$ ]] && (( slot < ${toString awgRuntimeIfaceSlots} )); then + entry=$(${jq} -nc --arg t "$tag" --argjson s "$slot" --argjson fallback ${lib.escapeShellArg (builtins.toJSON fallbackDns)} '{ + interface: ("${awgRuntimeIfacePrefix}" + ($s | tostring)), + table: (${toString awgRuntimeIfaceTableBase} + $s), + mark: (${toString awgRuntimeIfacePerAppFwmarkBase} + $s), + dnsPort: (${toString awgRuntimeIfaceDnsBasePort} + $s), + dnsFile: ("/run/proxy-suite-awg-if-" + $t + "/dns"), + fallbackDns: $fallback + }') + fi + ''} + if [[ -z ''${entry:-} ]]; then + echo "proxy-suite: '$tag' is not an \"interface\" AmneziaWG outbound" >&2 + exit 1 + fi + fi + interface=$(${jq} -r .interface <<< "$entry") + table=$(${jq} -r .table <<< "$entry") + mark=$(${jq} -r .mark <<< "$entry") + nft_table="proxy_suite_per_app_via_$mark" + dns_port=$(${jq} -r .dnsPort <<< "$entry") + ''; + + # $servers: the profile's own DNS servers, else proxy.dns.remote. + dnsServers = '' + dns_file=$(${jq} -r .dnsFile <<< "$entry") + servers=() + add_servers() { + local server + while read -r server; do + if [[ $server =~ ^[0-9A-Fa-f:.]+$ ]]; then servers+=("$server"); fi + done + } + if [[ -s $dns_file ]]; then add_servers < "$dns_file"; fi + if (( ! ''${#servers[@]} )); then add_servers < <(${jq} -r '.fallbackDns[]' <<< "$entry"); fi + ''; + + rulesDown = '' + for family in -4 -6; do + while ${ip} "$family" rule del pref ${toString awgPerAppRulePriority} fwmark "$mark" 2>/dev/null; do :; done + while ${ip} "$family" rule del pref ${toString awgPerAppUnreachablePriority} fwmark "$mark" 2>/dev/null; do :; done + done + ''; + + viaUp = pkgs.writeShellScript "proxy-suite-per-app" '' + set -euo pipefail + ${resolveInstance} + ${dnsServers} + dns="" + if (( ''${#servers[@]} )); then + # By the conntrack mark, which only the app's own connections carry: the forwarder's + # queries have the packet mark alone. + dns="ct mark $mark meta l4proto { tcp, udp } th dport 53 redirect to :$dns_port" + else + echo "proxy-suite: AmneziaWG outbound '$tag' names no DNS server: apps run via it look names up outside the tunnel" >&2 + fi + + ${nft} delete table inet "$nft_table" 2>/dev/null || true + ${rulesDown} + + ${nft} -f - </dev/null || true + ${rulesDown} + ''; + + # Instance -, the key awg- or -: the user's apps in the slice + # of what they run via. + userPrelude = '' + instance=''${1:-} + if [[ ! $instance =~ ^([0-9]+)-((awg|app|tproxy|tun)-[0-9a-f]+)$ ]]; then + echo "proxy-suite: '$instance' is not -" >&2 + exit 1 + fi + key=''${BASH_REMATCH[2]} + case "$key" in + awg-* | app-*) + set -- "$key" + ${resolveInstance} + nft_chain=app_mark + ;; + ${lib.concatMapStrings (route: '' + ${route}-*) + set -- "''${key#${route}-}" + ${decodeTag} + ${pinSlot route false} + if [[ -z $slot ]]; then + echo "proxy-suite: no ${route} pin slot holds '$tag'" >&2 + exit 1 + fi + nft_chain=${pinRoutes.${route}.nftChain} + ;; + '') pinRouteNames} + *) + echo "proxy-suite: '$key' is not run via here" >&2 + exit 1 + ;; + esac + slice_name="proxy-suite-per-app-via-$key.slice" + set -- "''${instance%%-*}" + ''; + viaUserStart = userRules.mkUserRuleStart { + name = "per-app-via-$key"; + nftFamily = "inet"; + nftTable = "$nft_table"; + nftChain = "$nft_chain"; + sliceNameArg = ''"$slice_name"''; + sliceLabel = "app via"; + markRule = "meta mark set $mark ct mark set $mark"; + prelude = userPrelude; + }; + viaUserStop = userRules.mkUserRuleStop { + name = "per-app-via-$key"; + nftFamily = "inet"; + nftTable = "$nft_table"; + nftChain = "$nft_chain"; + prelude = userPrelude; + }; + # The pin slots, of per-app TProxy and of per-app TUN. + pinRouteNames = lib.optional perAppPinTproxy "tproxy" ++ lib.optional perAppPinTun "tun"; + pinDir = "${constants.runtimeDir}/proxy-suite-per-app-via"; + curl = "${pkgs.curl}/bin/curl"; + flock = "${pkgs.util-linux}/bin/flock"; + pinTun = lib.escapeShellArg perAppRoutingTun.interface; + pinRoutes = { + tproxy = { + fwmarkBase = constants.perAppPinTproxyFwmarkBase; + tableBase = constants.perAppPinTproxyTableBase; + nftFiles = perAppPinTproxyRulesFiles; + # Where the user rule units add their cgroup rules, as for the per-app TProxy's own. + nftChain = "output"; + clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}"; + secretFile = "${constants.runtimeDir}/proxy-suite-socks/clash-secret"; + backend = "proxy-suite-socks.service"; + routingDown = builders.mkTproxyRoutingDown { + inherit ip; + fwmark = "$mark"; + table = "$table"; + }; + routingUp = '' + ${pinRoutes.tproxy.routingDown} + ${builders.mkTproxyRoutingUp { + inherit ip; + inherit (cfg.proxy) ipv6; + fwmark = "$mark"; + table = "$table"; + }} + ''; + }; + tun = { + fwmarkBase = constants.perAppPinTunFwmarkBase; + tableBase = constants.perAppPinTunTableBase; + nftFiles = perAppPinTunChainFiles; + nftChain = "app_mark"; + clashApi = "http://127.0.0.1:${toString constants.perAppTunClashApiPort}"; + secretFile = "${constants.runtimeDir}/proxy-suite-per-app-tun/clash-secret"; + backend = "proxy-suite-per-app-tun.service"; + # Into the TUN; the slot's nft table SNATs the packets to the source the backend tells + # the slot by. + routingUp = '' + ${ip} -4 route replace default dev ${pinTun} table "$table" + ${ + if cfg.proxy.ipv6 then + '' + ${ip} -6 route replace default dev ${pinTun} table "$table" + '' + else + '' + # No IPv6 in the TUN: unreachable, so the app falls back to IPv4. + ${ip} -6 route replace unreachable default table "$table" + '' + } + for family in -4 -6; do + while ${ip} "$family" rule del pref ${toString constants.perAppPinRulePriority} fwmark "$mark" 2>/dev/null; do :; done + ${ip} "$family" rule add pref ${toString constants.perAppPinRulePriority} fwmark "$mark" table "$table" + done + ''; + routingDown = '' + for family in -4 -6; do + while ${ip} "$family" rule del pref ${toString constants.perAppPinRulePriority} fwmark "$mark" 2>/dev/null; do :; done + ${ip} "$family" route flush table "$table" 2>/dev/null || true + done + ''; + }; + }; + + # $1, a tag in hex, to $hex and $tag. + decodeTag = '' + hex=''${1:-} + if [[ ! $hex =~ ^([0-9a-f][0-9a-f]){1,64}$ ]]; then + echo "proxy-suite: '$hex' is not an outbound tag in hex" >&2 + exit 1 + fi + tag=$(printf '%b' "$(printf '%s' "$hex" | ${pkgs.gnused}/bin/sed 's/../\\x&/g')") + if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then + echo "proxy-suite: '$tag' is not an outbound tag" >&2 + exit 1 + fi + ''; + + # $slot: the one of the route's slots that $tag holds; with `claim`, a free one when none + # does. Then its $mark, $table and $nft_table. A slot is the file - in pinDir, + # holding the tag. + pinSlot = + route: claim: + let + r = pinRoutes.${route}; + file = ''"${pinDir}/${route}-$n"''; + in + '' + ${pkgs.coreutils}/bin/mkdir -p ${pinDir} + exec 9>>"${pinDir}/lock" + ${flock} 9 + slot="" + for (( n = 0; n < ${toString perAppPinSlots}; n++ )); do + if [[ -f ${file} && $(< ${file}) == "$tag" ]]; then + slot=$n + break + fi + done + ${lib.optionalString claim '' + for (( n = 0; n < ${toString perAppPinSlots}; n++ )); do + [[ -z $slot ]] || break + if [[ ! -e ${file} ]]; then + printf '%s\n' "$tag" > ${file} + slot=$n + fi + done + ''} + ${flock} -u 9 + if [[ -n $slot ]]; then + mark=$(( ${toString r.fwmarkBase} + slot )) + table=$(( ${toString r.tableBase} + slot )) + nft_table="proxy_suite_per_app_via_${route}_$slot" + fi + ''; + + # select_pin : switches the slot's selector, while the backend comes up. + mkSelect = + route: + let + r = pinRoutes.${route}; + in + '' + select_pin() { + local code attempt secret + for attempt in $(${pkgs.coreutils}/bin/seq 1 "$2"); do + secret=$(${pkgs.coreutils}/bin/tr -d '\r\n' 2>/dev/null < ${r.secretFile} || true) + code=$(${curl} -s -o /dev/null -w '%{http_code}' --noproxy '*' -m 3 \ + -X PUT "${r.clashApi}/proxies/proxy-suite-pin-${route}-$slot" \ + -H "Content-Type: application/json" \ + -H @<(printf 'Authorization: Bearer %s\n' "$secret") \ + -d "$(${jq} -cn --arg n "$1" '{name: $n}')" || true) + case "$code" in + 2??) return 0 ;; + 400) + echo "proxy-suite: the backend has no outbound '$1' to run apps through" >&2 + return 2 + ;; + 404) + echo "proxy-suite: the backend has no ${route} pin slot $slot; restart ${r.backend}" >&2 + return 2 + ;; + esac + ${pkgs.coreutils}/bin/sleep 0.5 + done + echo "proxy-suite: the backend's Clash API at ${r.clashApi} did not answer" >&2 + return 1 + } + ''; + + mkPinUp = + route: + let + r = pinRoutes.${route}; + in + pkgs.writeShellScript "proxy-suite-per-app" '' + set -euo pipefail + ${decodeTag} + ${pinSlot route true} + if [[ -z $slot ]]; then + echo "proxy-suite: all ${toString perAppPinSlots} ${route} pin slots are taken (perAppRouting.via.pinSlots)" >&2 + exit 1 + fi + ${mkSelect route} + release() { + set +e + ${nft} delete table inet "$nft_table" 2>/dev/null + ${r.routingDown} + ${pkgs.coreutils}/bin/rm -f "${pinDir}/${route}-$slot" + } + trap release ERR + files=(${lib.concatMapStringsSep " " toString r.nftFiles}) + ${nft} delete table inet "$nft_table" 2>/dev/null || true + ${nft} -f "''${files[$slot]}" + ${r.routingUp} + # A backend that restarts restarts this too (PartOf), which switches it again. + select_pin "$tag" 60 + ''; + + mkPinDown = + route: + let + r = pinRoutes.${route}; + in + pkgs.writeShellScript "proxy-suite-per-app" '' + set -uo pipefail + ${decodeTag} + ${pinSlot route false} + [[ -n $slot ]] || exit 0 + ${mkSelect route} + # Blocked until another outbound claims the slot; a backend that is down blocks anyway. + select_pin block 1 2>/dev/null + ${nft} delete table inet "$nft_table" 2>/dev/null || true + ${r.routingDown} + ${pkgs.coreutils}/bin/rm -f "${pinDir}/${route}-$slot" + ''; + + pinUp = lib.genAttrs pinRouteNames mkPinUp; + pinDown = lib.genAttrs pinRouteNames mkPinDown; +in +{ + inherit + perAppViaFile + viaUp + viaDns + viaDown + viaUserStart + viaUserStop + pinRoutes + pinUp + pinDown + ; +} diff --git a/modules/proxy-suite/service/polkit-rules.template.js b/modules/proxy-suite/service/polkit-rules.template.js index 86def4e..1b80efb 100644 --- a/modules/proxy-suite/service/polkit-rules.template.js +++ b/modules/proxy-suite/service/polkit-rules.template.js @@ -20,7 +20,9 @@ for (var i = 0; !known && i < templates.length; i++) { } catch (error) { return null; } - if (instance !== uid) { + // A via instance is -. + var owner = template === "proxy-suite-per-app-via-user@" ? instance.split("-")[0] : instance; + if (owner !== uid) { return null; } } diff --git a/modules/proxy-suite/service/polkit.nix b/modules/proxy-suite/service/polkit.nix index 1791451..9e6e1c4 100644 --- a/modules/proxy-suite/service/polkit.nix +++ b/modules/proxy-suite/service/polkit.nix @@ -27,6 +27,9 @@ let # Tunnels of the AmneziaWG outbounds added at runtime; a global profile's own unit # (proxy-suite-awg@) is "services", like the declared ones. "proxy-suite-awg-tunnel@" = "outbounds"; + # A global profile brought up for `apps run --via`, by proxy-ctl as the app starts. + "proxy-suite-awg-app@" = "perApp"; + "proxy-suite-awg-if@" = "outbounds"; "proxy-suite-awg-runtime-sync." = "outbounds"; "proxy-suite-autoproxy-learn." = "autoProxy"; "proxy-suite-zapret2-cutoff." = "zapret"; diff --git a/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq b/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq index 9a9b61a..195fa41 100644 --- a/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq +++ b/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq @@ -2,7 +2,10 @@ def sing_box_preserved_rules: [.route.rules[] | select(((.action? // "") == "hijack-dns") and (((.inbound? // []) | index("xray-dns-in")) != null))]; -.outbounds = ($obs[0] + .outbounds) +# perAppRouting.via's pin rules, which no route mode replaces. +def is_pin: ((.outbound? // "") | type) == "string" and ((.outbound? // "") | startswith("proxy-suite-pin-")); +([.route.rules[]? | select(is_pin)]) as $pin_rules +| .outbounds = ($obs[0] + .outbounds) | if $auth_enabled then (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] else . end @@ -27,3 +30,13 @@ def sing_box_preserved_rules: else . end | .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets) | .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules) + # Pins after the common hijack-dns and sniff rules, so a pinned app's lookups are answered + # as any other's, and before every rule that picks an outbound. + | .route.rules |= [.[] | select(is_pin | not)] + | (.route.rules | map((.action? // "") == "sniff") | index(true)) as $sniff + | .route.rules = (if $sniff == null then $pin_rules + .route.rules + else .route.rules[:$sniff + 1] + $pin_rules + .route.rules[$sniff + 1:] end) + # Each pin's selector takes any outbound, block first: a slot nobody switched blocks. + | ([.outbounds[].tag | select(startswith("proxy-suite-pin-") | not)]) as $tags + | .outbounds |= map(if .type == "selector" and (.tag | startswith("proxy-suite-pin-")) + then .outbounds = (["block"] + ($tags - ["block"])) | .default = "block" else . end) diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix index ddc5137..62b519a 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -5,6 +5,9 @@ proxyInboundsGuardPrivate, proxyInboundsGuardStrategy ? null, userDnsRules ? [ ], + # proxy.dns.remote as a sing-box server, for the AmneziaWG interfaces added at runtime; null + # when there are none. + awgRuntimeDnsServer ? null, }: let @@ -16,6 +19,20 @@ else (fillTemplate ./backend-filter-sing-box.template.jq { userDnsRuleCount = toString (builtins.length userDnsRules); }) + # An outbound on such an interface resolves through it (awg-dns-), as a declared one + # does; only its server cannot be in the build-time config. + + lib.optionalString (awgRuntimeDnsServer != null) '' + | ([.dns.servers[]?.tag]) as $have + | .dns.servers += [ + .outbounds[] + | select(.type == "direct" and (.bind_interface | type) == "string" + and ((.domain_resolver? // "") | type) == "string" + and ((.domain_resolver? // "") | startswith("awg-dns-"))) + | select(.domain_resolver as $t | $have | index($t) | not) + | {tag: .domain_resolver, bind_interface} + ${builtins.toJSON awgRuntimeDnsServer} + + (if .routing_mark then {routing_mark} else {} end) + ] + '' + lib.optionalString proxyInboundsGuardPrivate ( fillTemplate ./backend-filter-private-guard.template.jq { resolveStrategy = lib.optionalString ( diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index ac9b8f4..e97d0d2 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -9,6 +9,7 @@ whitelistBypassJoiners, awgOutbounds, awgRuntimeOutbounds ? false, + awgRuntimeIfaceOutbounds ? false, constants, pureXrayEnabled, hybridEnabled, @@ -182,6 +183,38 @@ let _proxy_suite_record_tag_source "$1" "$3" } + ${lib.optionalString awgRuntimeIfaceOutbounds '' + # $1 tag, $2 its slot: an AmneziaWG outbound added at runtime on an interface of its + # own, as mkInterfaceOutboundBlock has it. sing-box resolves through the interface + # with a server the backend filter adds for awg-dns-; XRay resolves as usual. + _proxy_suite_add_awg_interface() { + local ob + case "$2" in + "" | *[!0-9]*) return 1 ;; + esac + [ "$2" -lt ${toString constants.awgRuntimeIfaceSlots} ] || return 1 + ob=$(${jq} -nc --arg t "$1" --arg i "${constants.awgRuntimeIfacePrefix}$2" ${ + lib.escapeShellArg ( + if pureXrayEnabled then + ''{protocol: "freedom", tag: $t, streamSettings: {sockopt: ({interface: $i}${ + lib.optionalString (routingMark != null) " + {mark: ${toString routingMark}}" + })}}'' + else + ''{type: "direct", tag: $t, bind_interface: $i, domain_resolver: ("${constants.awgDnsServerTag ""}" + $t)}${ + lib.optionalString (routingMark != null) " + {routing_mark: ${toString routingMark}}" + }'' + ) + }) || return 1 + ${ + if hybridEnabled then + ''_proxy_suite_add_sing_box_ob "$ob"'' + else + ''OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")'' + } + _proxy_suite_record_tag_source "$1" awg + } + ''} + # $1 sub tag, $2 file holding its URL, $3 its links file (absent for a cache # written before links existed: those entries share as JSON until the next update). _proxy_suite_record_subscription_share() { @@ -507,7 +540,15 @@ let case "$RUNTIME_OB_SRC" in *.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;; # Its tunnel (proxy-suite-awg-tunnel@) checks the port again before listening. - *.awg) _proxy_suite_add_socks_hop "$RUNTIME_OB_TAG" "$(_proxy_suite_read_source "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.port" 2>/dev/null | head -n 1)" runtime ;; + *.awg) + ${lib.optionalString awgRuntimeIfaceOutbounds '' + if [ -e "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.iface" ]; then + _proxy_suite_add_awg_interface "$RUNTIME_OB_TAG" "$(_proxy_suite_read_source "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.iface" 2>/dev/null | head -n 1)" + else + ''} + _proxy_suite_add_socks_hop "$RUNTIME_OB_TAG" "$(_proxy_suite_read_source "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.port" 2>/dev/null | head -n 1)" runtime + ${lib.optionalString awgRuntimeIfaceOutbounds "fi"} + ;; *) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(_proxy_suite_read_source "$RUNTIME_OB_SRC")" runtime ;; esac || { echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2; continue; } if [ -s "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" ]; then diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 89db03f..4d01259 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -129,6 +129,7 @@ let whitelistBypassJoiners awgOutbounds awgRuntimeOutbounds + awgRuntimeIfaceOutbounds constants pureXrayEnabled hybridEnabled @@ -161,6 +162,15 @@ let proxyInboundsGuardStrategy ; userDnsRules = proxyCfg.dns.singBox.rules; + awgRuntimeDnsServer = + if ctx.awgRuntimeIfaceOutbounds then + { + inherit (proxyCfg.dns.remote) type; + server = proxyCfg.dns.remote.address; + server_port = proxyCfg.dns.remote.port; + } + else + null; }; backendJqFilterFile = pkgs.writeText "proxy-suite-core" backendJqFilter; diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index 194078c..0503942 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -16,6 +16,8 @@ let perAppRoutingTun perAppRoutingTproxy perAppZapretEnabled + perAppViaInterfaceOutbounds + perAppViaRuntime sshProxyOutboundEnabled sshProxyUnitEnabled torOutboundEnabled @@ -68,6 +70,10 @@ let "sing-box"; localProxyAuthEnabled = ctx.localProxy.authEnabled; + # `apps run --via`: an "interface" AmneziaWG outbound to run through, declared or to come. + perAppViaAwg = perAppViaInterfaceOutbounds != [ ] || perAppViaRuntime || ctx.perAppViaProfiles; + # Or any outbound, through a pin slot: either way, the apps' slices and their marking. + perAppViaEnabled = perAppViaAwg || perAppRouting.pinUp != { }; # For the root units reading what userControl's group writes (outbounds.d, # subscriptions.d): the file system read-only but for their own directories, so no @@ -294,6 +300,75 @@ let execStop = "${perAppRouting.perAppZapretUserRuleStop} %i"; }; } + # `apps run --via `: an instance per outbound, up while anyone runs through it: its + # rules, and the forwarder its apps' lookups go to. Each user's apps in its slice are + # marked by the next unit (-). + { + enable = perAppViaAwg; + name = "proxy-suite-per-app-via@"; + value = mkRestartingService { + description = "proxy-suite per-app routing via %i"; + execStartPre = "${perAppRouting.viaUp} %i"; + execStart = "${perAppRouting.viaDns} %i"; + execStopPost = "${perAppRouting.viaDown} %i"; + runtimeDirectory = "proxy-suite-per-app-via-%i"; + extraServiceConfig = { + # Ready once the forwarder listens, so the app's first lookup finds it. + Type = "notify"; + NotifyAccess = "main"; + RestartSec = 2; + NoNewPrivileges = true; + ProtectSystem = "strict"; + ProtectHome = true; + PrivateTmp = true; + ProtectClock = true; + ProtectHostname = true; + ProtectKernelLogs = true; + RestrictRealtime = true; + RestrictSUIDSGID = true; + LockPersonality = true; + # nft and ip rules, and SO_MARK on the forwarder's sockets. + CapabilityBoundingSet = [ "CAP_NET_ADMIN" ]; + }; + }; + } + ] + # `apps run --via ` for any other outbound: a pin slot of per-app TProxy or TUN for + # each outbound apps run through. Part of the backend whose selector it switches: a + # restart of that switches it again. + ++ map (route: { + enable = true; + name = "proxy-suite-per-app-via-${route}@"; + value = + let + backend = perAppRouting.pinRoutes.${route}.backend; + in + mkOneshotService { + description = "proxy-suite per-app ${route} pin for the outbound %i (in hex)"; + execStart = "${perAppRouting.pinUp.${route}} %i"; + execStop = "${perAppRouting.pinDown.${route}} %i"; + after = [ backend ]; + requires = [ backend ]; + # As per-app TProxy: under a global mode, proxy-ctl runs the app without its route. + conflicts = [ + "${serviceNames.tproxy}.service" + "${serviceNames.tun}.service" + ]; + } + // { + partOf = [ backend ]; + }; + }) (builtins.attrNames perAppRouting.pinUp) + ++ [ + { + enable = perAppViaEnabled; + name = "proxy-suite-per-app-via-user@"; + value = mkOneshotService { + description = "Enable proxy-suite per-app via marking for %i"; + execStart = "${perAppRouting.viaUserStart} %i"; + execStop = "${perAppRouting.viaUserStop} %i"; + }; + } { # Not gated on hasSubscriptions: runtime subscriptions need refreshing too. enable = proxyEnabled; @@ -379,6 +454,11 @@ let name = "${serviceNames.perAppZapret}-anchor"; value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice"; } + { + enable = perAppViaEnabled; + name = "proxy-suite-per-app-via-anchor@"; + value = mkAnchorService "proxy-suite-per-app-via-%i.slice" "Anchor service for the proxy-suite per-app via %i slice"; + } ]; timerEntries = [ diff --git a/modules/proxy-suite/zapret/common.nix b/modules/proxy-suite/zapret/common.nix index d8b5045..32a8cc3 100644 --- a/modules/proxy-suite/zapret/common.nix +++ b/modules/proxy-suite/zapret/common.nix @@ -10,6 +10,7 @@ scriptName ? "proxy-suite-zapret", }: let + derived = import ../derived.nix { inherit lib cfg; }; dropMarkTable = "${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true"; in { @@ -21,6 +22,12 @@ in tunInterfaces = lib.unique ( lib.optional (cfg.proxy.enable && cfg.proxy.tun.enable) cfg.proxy.tun.interface ++ lib.optional (cfg.proxy.enable && cfg.perAppRouting.tun.enable) cfg.perAppRouting.tun.interface + # AmneziaWG outbound interfaces, and those apps run through: what enters them is a + # tunnel's inside. Desync there would send its fakes out the uplink, past the tunnel. + # (A trailing * is nft's wildcard; the iptables rules make it +.) + ++ map (ob: ob.interface) derived.awgInterfaceOutbounds + ++ lib.optional derived.awgRuntimeIfaceOutbounds "${derived.constants.awgRuntimeIfacePrefix}*" + ++ lib.optional derived.perAppViaProfiles "${derived.constants.awgAppIfacePrefix}*" # TProxy reroutes local apps' packets out lo to the backend's listener; desync there # corrupts the handshake the backend reads, like on a TUN. ++ lib.optional ( diff --git a/modules/proxy-suite/zapret/package-builder.nix b/modules/proxy-suite/zapret/package-builder.nix index e663a3e..c4d407a 100644 --- a/modules/proxy-suite/zapret/package-builder.nix +++ b/modules/proxy-suite/zapret/package-builder.nix @@ -39,11 +39,18 @@ let "$rule_helper" "$1" "$chain" -t mangle -m mark ! --mark 0/${filterMark} -m comment --comment "proxy-suite ${scope} per-app-zapret bypass" -j RETURN done ''} - ${lib.concatMapStrings (interface: '' - "$rule_helper" "$1" POSTROUTING -t mangle -o ${lib.escapeShellArg interface} -m comment --comment "proxy-suite ${scope} TUN bypass" -j RETURN - "$rule_helper" "$1" INPUT -t mangle -i ${lib.escapeShellArg interface} -m comment --comment "proxy-suite ${scope} TUN bypass" -j RETURN - "$rule_helper" "$1" FORWARD -t mangle -i ${lib.escapeShellArg interface} -m comment --comment "proxy-suite ${scope} TUN bypass" -j RETURN - '') tunInterfaces} + ${lib.concatMapStrings ( + interface: + let + # iptables' wildcard. + name = lib.escapeShellArg (lib.replaceStrings [ "*" ] [ "+" ] interface); + in + '' + "$rule_helper" "$1" POSTROUTING -t mangle -o ${name} -m comment --comment "proxy-suite ${scope} TUN bypass" -j RETURN + "$rule_helper" "$1" INPUT -t mangle -i ${name} -m comment --comment "proxy-suite ${scope} TUN bypass" -j RETURN + "$rule_helper" "$1" FORWARD -t mangle -i ${name} -m comment --comment "proxy-suite ${scope} TUN bypass" -j RETURN + '' + ) tunInterfaces} done return 0 } diff --git a/nix/checks/amnezia-wg-outbound.nix b/nix/checks/amnezia-wg-outbound.nix index a29f9ea..398b418 100644 --- a/nix/checks/amnezia-wg-outbound.nix +++ b/nix/checks/amnezia-wg-outbound.nix @@ -111,7 +111,7 @@ in 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 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); @@ -123,9 +123,9 @@ in # 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 ''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 ) @@ -136,7 +136,7 @@ in 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); + assert !(hasInfix "oif" 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; diff --git a/nix/checks/amnezia-wg.nix b/nix/checks/amnezia-wg.nix index f21c0a4..d6b5cb4 100644 --- a/nix/checks/amnezia-wg.nix +++ b/nix/checks/amnezia-wg.nix @@ -247,10 +247,12 @@ in grep -qx 'stop proxy-suite-awg@gone.service' log ! grep -q 'stop proxy-suite-awg@self.service' log - printf '%s\n' '● proxy-suite-awg-tunnel@old.service loaded failed failed x' > units + printf '%s\n' '● proxy-suite-awg-tunnel@old.service loaded failed failed x' \ + ' proxy-suite-awg-if@gone.service loaded active exited x' > units : > log $sync grep -qx 'stop --no-block proxy-suite-awg-tunnel@old.service' log + grep -qx 'stop --no-block proxy-suite-awg-if@gone.service' log touch "$out" ''; @@ -399,7 +401,21 @@ in assert runtimeTunnel.serviceConfig.RuntimeDirectory == "proxy-suite-awg-tunnel-%i"; assert builtins.elem "proxy-suite-outbound-reload.service" runtimeUnits.proxy-suite-awg-runtime-sync.wantedBy; - assert pkgs.lib.hasInfix "proxy-suite-awg-tunnel@$tag.service" runtimeSync; + assert pkgs.lib.hasInfix "proxy-suite-awg-$kind@$tag.service" runtimeSync; + assert pkgs.lib.hasInfix "[[ -e /var/lib/proxy-suite/outbounds.d/$tag.iface ]] && kind=if" + runtimeSync; + # Or, with .iface, an interface of its own: a template like the global one's, + # behind a direct outbound bound to it. + assert runtimeUnits."proxy-suite-awg-if@".wantedBy == [ ]; + assert runtimeUnits."proxy-suite-awg-if@".serviceConfig.RuntimeDirectory == "proxy-suite-awg-if-%i"; + assert builtins.elem "proxy-suite-awg-if-watchdog@%i.service" + runtimeUnits."proxy-suite-awg-if@".wants; + assert runtimeUnits."proxy-suite-awg-if-watchdog@".bindsTo == [ "proxy-suite-awg-if@%i.service" ]; + assert pkgs.lib.hasInfix "_proxy_suite_add_awg_interface" runtimeOutboundScript; + assert pkgs.lib.hasInfix ''bind_interface: $i, domain_resolver: ("awg-dns-" + $t)'' + runtimeOutboundScript; + assert runtimeCtl.wrapperEnv.AWG_RUNTIME_IFACE_OUTBOUNDS == "1"; + assert runtimeCtl.wrapperEnv.AWG_RUNTIME_OUTBOUND_KIND == "userspace"; # The backend dials each one's tunnel on the port in .port. assert pkgs.lib.hasInfix ''"/var/lib/proxy-suite/outbounds.d"/*.awg'' runtimeOutboundScript; assert pkgs.lib.hasInfix "_proxy_suite_add_socks_hop" runtimeOutboundScript; diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 39f7f7b..2dc837a 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -181,6 +181,10 @@ let ; }; + perAppRoutingAwgChecks = import ./per-app-routing-awg.nix { + inherit checkLib pkgs mkPerAppUserRules; + }; + outboundValidationChecks = import ./outbound-validation.nix { inherit mkBadProxySuiteFixture mkFailingAssertions; }; @@ -337,6 +341,7 @@ let ++ subscriptionChecks.assertions ++ routeModeChecks.assertions ++ perAppRoutingChecks.assertions + ++ perAppRoutingAwgChecks.assertions ++ serverModuleChecks.assertions ); in diff --git a/nix/checks/per-app-routing-awg.nix b/nix/checks/per-app-routing-awg.nix new file mode 100644 index 0000000..42ca5c2 --- /dev/null +++ b/nix/checks/per-app-routing-awg.nix @@ -0,0 +1,285 @@ +{ + checkLib, + pkgs, + mkPerAppUserRules, +}: + +let + inherit (checkLib) mkProxySuite rejectsProxySuite; + generated = import ./read-generated.nix; + inherit (pkgs.lib) hasInfix; + + config = { + enable = true; + proxy = { + enable = true; + tproxy.enable = true; + }; + killSwitch.enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles = { + de = { + asOutbound = "interface"; + configFile = "/run/secrets/de.conf"; + }; + plain = { + asOutbound = "singBox"; + configFile = "/run/secrets/plain.conf"; + }; + # Global: apps run through a copy of it, brought up apart. + home.configFile = "/run/secrets/home.conf"; + }; + }; + perAppRouting = { + enable = true; + profiles = [ + { + name = "game"; + route = "tun"; + outbound = "de"; + } + ]; + }; + }; + fixture = mkProxySuite config; + services = fixture.config.systemd.services; + via = services."proxy-suite-per-app-via@"; + perAppRouting = mkPerAppUserRules fixture; + viaUp = generated.readDerivation perAppRouting.viaUp; + viaDns = generated.readDerivation perAppRouting.viaDns; + appCopy = services."proxy-suite-awg-app@"; + viaFile = builtins.fromJSON (generated.readDerivation perAppRouting.perAppViaFile); + viaUserStart = generated.readDerivation perAppRouting.viaUserStart; + anchor = fixture.config.systemd.user.services."proxy-suite-per-app-via-anchor@"; + dePrepare = generated.readDerivation ( + builtins.head services.proxy-suite-awg-de.serviceConfig.ExecStartPre + ); + nftr = import ../../modules/proxy-suite/nftables.nix { + inherit (pkgs) lib; + inherit pkgs; + cfg = fixture.config.services.proxy-suite; + }; + globalTproxyRules = generated.readDerivation nftr.nftablesRulesFile; + killSwitchRules = generated.readDerivation nftr.killSwitchRulesFile; + + withoutPerApp = mkProxySuite (config // { perAppRouting.enable = false; }); + + # Pins: any outbound, through per-app TProxy or TUN. + pinConfig = { + enable = true; + proxy = { + enable = true; + ipv6 = false; + tproxy.enable = true; + outbounds = [ + { + tag = "nl"; + url = "socks5://127.0.0.1:1080"; + } + ]; + }; + killSwitch.enable = true; + perAppRouting = { + enable = true; + tproxy.enable = true; + tun.enable = true; + profiles = [ + { + name = "game"; + route = "tproxy"; + outbound = "nl"; + } + ]; + }; + }; + pinFixture = mkProxySuite pinConfig; + pinServices = pinFixture.config.systemd.services; + pinPerApp = mkPerAppUserRules pinFixture; + pinTproxyUp = generated.readDerivation pinPerApp.pinUp.tproxy; + pinTproxyDown = generated.readDerivation pinPerApp.pinDown.tproxy; + pinTunUp = generated.readDerivation pinPerApp.pinUp.tun; + pinUserStart = generated.readDerivation pinPerApp.viaUserStart; + pinTproxyConfig = checkLib.mkTProxyConfig pinFixture; + pinTunConfig = checkLib.mkPerAppTunConfig pinFixture; + pinNft = import ../../modules/proxy-suite/nftables.nix { + inherit (pkgs) lib; + inherit pkgs; + cfg = pinFixture.config.services.proxy-suite; + }; +in +{ + assertions = [ + # Only the "interface" outbound takes apps directly, by its table and a mark of its own. + ( + assert + viaFile == { + de = { + interface = "awg-de"; + table = 110; + mark = 23040; + dnsPort = 19100; + unit = "proxy-suite-awg-de.service"; + dnsFile = "/run/proxy-suite-awg-de/dns"; + fallbackDns = [ "1.1.1.1" ]; + }; + }; + assert hasInfix "--dns-out \"/run/proxy-suite-awg-de/dns\"" dePrepare; + true + ) + # The instance: the app's packets marked into the table, masqueraded, DNS rewritten to the + # profile's resolver, and turned away while the table has no route. + ( + assert hasInfix "%i" via.serviceConfig.ExecStart; + assert via.serviceConfig.Type == "notify"; + assert hasInfix "per_app_dns.py --port \"$dns_port\" --mark \"$mark\"" viaDns; + assert hasInfix ''nft_table="proxy_suite_per_app_via_$mark"'' viaUp; + assert hasInfix ''oifname "$interface" meta mark $mark masquerade'' viaUp; + assert hasInfix "ct mark $mark meta l4proto { tcp, udp } th dport 53 redirect to :$dns_port" viaUp; + assert hasInfix "th dport 53 goto app_mark" viaUp; + assert hasInfix "ip daddr 192.168.0.0/16 return" viaUp; + assert hasInfix ''rule add pref 8986 fwmark "$mark" lookup "$table"'' viaUp; + assert hasInfix ''rule add pref 8987 fwmark "$mark" unreachable'' viaUp; + assert hasInfix "priority mangle - 10" viaUp; + # The tunnel's own packets carry its FwMark and still look like the app's: never taken, + # nor marked on the way in, or they loop back into the tunnel. + assert hasInfix "meta mark != 0 return" viaUp; + assert hasInfix ''iifname "$interface" ct mark $mark meta mark set $mark'' viaUp; + # Private ranges go through the tunnel, the server's own address among them. + assert !(hasInfix "RESERVED_IP" viaUp); + true + ) + # Each user's apps, in the outbound's slice; the slice from a user unit. + ( + assert hasInfix "^([0-9]+)-((awg|app|tproxy|tun)-[0-9a-f]+)$" viaUserStart; + assert hasInfix "nft_chain=app_mark" viaUserStart; + assert hasInfix ''-name "$slice_name"'' viaUserStart; + assert hasInfix "meta mark set $mark ct mark set $mark" viaUserStart; + assert anchor.serviceConfig.Slice == "proxy-suite-per-app-via-%i.slice"; + assert services ? "proxy-suite-per-app-via-user@"; + true + ) + # Global TProxy and the kill switch let the apps' mark past. + ( + # And the slots of the outbounds added at runtime, on interfaces of their own. + assert hasInfix "meta mark { 23040, 23104, 23105," globalTproxyRules; + # And the slots of the global profiles apps run through. + assert hasInfix "23119, 23232," globalTproxyRules; + assert hasInfix "23239 } return" globalTproxyRules; + assert hasInfix "23040" killSwitchRules; + true + ) + # A global profile: a copy rendered as an "interface" outbound has it, on a slot's + # interface, never up with the profile itself. + ( + assert appCopy.wantedBy == [ ]; + assert appCopy.serviceConfig.Restart == "no"; + assert + builtins.elem "proxy-suite-awg-%i.service" appCopy.conflicts + && builtins.elem "proxy-suite-awg@%i.service" appCopy.conflicts; + assert builtins.elem "proxy-suite-awg-app-watchdog@%i.service" appCopy.wants; + assert services."proxy-suite-awg-app-watchdog@".bindsTo == [ "proxy-suite-awg-app@%i.service" ]; + assert appCopy.serviceConfig.RuntimeDirectory == "proxy-suite-awg-app-%i"; + assert hasInfix ''"/run/proxy-suite-awg-app-$tag/slot"'' viaUp; + assert hasInfix "^(awg|app)-([0-9a-f][0-9a-f]){1,64}$" viaUp; + assert hasInfix ''iifname "psawga*" accept'' + fixture.config.networking.firewall.extraReversePathFilterRules; + true + ) + # Without per-app routing there is nothing to run via. + ( + assert !(withoutPerApp.config.systemd.services ? "proxy-suite-per-app-via@"); + true + ) + # Pin slots: a listener, a rule and a selector each in the backend, which the filter fills; + # a unit per route, part of the backend whose selector it switches. + ( + assert pinServices ? "proxy-suite-per-app-via-tproxy@"; + assert pinServices."proxy-suite-per-app-via-tproxy@".partOf == [ "proxy-suite-socks.service" ]; + assert pinServices."proxy-suite-per-app-via-tun@".partOf == [ "proxy-suite-per-app-tun.service" ]; + assert builtins.elem "proxy-suite-tproxy.service" + pinServices."proxy-suite-per-app-via-tun@".conflicts; + assert pinServices ? "proxy-suite-per-app-via-user@"; + # The kernel path's unit only with an "interface" AmneziaWG outbound to take. + assert !(pinServices ? "proxy-suite-per-app-via@"); + assert builtins.elem { + type = "tproxy"; + tag = "per-app-pin-tproxy-0"; + listen = "127.0.0.1"; + listen_port = 19160; + } pinTproxyConfig.inbounds; + assert builtins.elem { + inbound = [ "per-app-pin-tproxy-7" ]; + outbound = "proxy-suite-pin-tproxy-7"; + } pinTproxyConfig.route.rules; + assert builtins.elem { + type = "selector"; + tag = "proxy-suite-pin-tproxy-0"; + outbounds = [ "block" ]; + default = "block"; + } pinTproxyConfig.outbounds; + assert builtins.elem { + inbound = [ "tun-in" ]; + source_ip_cidr = [ "172.20.1.2/32" ]; + outbound = "proxy-suite-pin-tun-0"; + } pinTunConfig.route.rules; + assert pinTunConfig.experimental.clash_api.external_controller == "127.0.0.1:19180"; + assert hasInfix ''select_pin "$tag" 60'' pinTproxyUp; + assert hasInfix "/proxies/proxy-suite-pin-tproxy-$slot" pinTproxyUp; + assert hasInfix "/run/proxy-suite-socks/clash-secret" pinTproxyUp; + assert hasInfix "127.0.0.1:19180" pinTunUp; + assert hasInfix ''route replace default dev psperapptun0 table "$table"'' pinTunUp; + # The backend tells a TUN slot by the source its packets are SNATed to. + assert hasInfix ''oifname "psperapptun0" meta mark 23200 meta nfproto ipv4 snat ip to 172.20.1.2'' ( + generated.readDerivation (builtins.head pinNft.perAppPinTunChainFiles) + ); + assert hasInfix ''rule add pref 8988 fwmark "$mark" table "$table"'' pinTunUp; + assert hasInfix "select_pin block 1" pinTproxyDown; + assert builtins.length pinNft.perAppPinTproxyRulesFiles == 8; + assert hasInfix "tproxy ip to 127.0.0.1:19167" ( + generated.readDerivation (pkgs.lib.last pinNft.perAppPinTproxyRulesFiles) + ); + assert hasInfix "table inet proxy_suite_per_app_via_tun_0" ( + generated.readDerivation (builtins.head pinNft.perAppPinTunChainFiles) + ); + assert hasInfix "ct mark 23200 meta mark set 23200" ( + generated.readDerivation (builtins.head pinNft.perAppPinTunChainFiles) + ); + # The user rule units find the slot a pin holds. + assert hasInfix "^([0-9]+)-((awg|app|tproxy|tun)-[0-9a-f]+)$" pinUserStart; + assert hasInfix "nft_chain=output" pinUserStart; + assert hasInfix "23168" (checkLib.mkNftRules pinFixture "killSwitchRulesFile"); + true + ) + # Any outbound for a tproxy or tun profile; only an "interface" one for the rest. + (rejectsProxySuite "outbound 'nl' needs route \"tproxy\" or \"tun\"" ( + pinConfig + // { + perAppRouting = pinConfig.perAppRouting // { + profiles = [ + { + name = "game"; + route = "proxychains"; + outbound = "nl"; + } + ]; + }; + } + )) + (rejectsProxySuite "outbound 'plain' needs route \"tproxy\" or \"tun\"" ( + config + // { + perAppRouting = config.perAppRouting // { + profiles = [ + { + name = "game"; + route = "tun"; + outbound = "plain"; + } + ]; + }; + } + )) + ]; +} diff --git a/nix/checks/user-control.nix b/nix/checks/user-control.nix index dd80041..5173f3b 100644 --- a/nix/checks/user-control.nix +++ b/nix/checks/user-control.nix @@ -114,7 +114,10 @@ in ); assert !(hasInfix "\"set-property\"" (polkitConfig allFixture)); # A user's per-app marking is theirs alone. - assert hasInfix "if (instance !== uid)" (polkitConfig allFixture); + assert hasInfix "if (owner !== uid)" (polkitConfig allFixture); + assert hasInfix ''"proxy-suite-per-app-via-user@" ? instance.split("-")[0]'' ( + polkitConfig allFixture + ); assert groupReadsSecrets allFixture; assert hasInfix "chown proxy-suite-daemon:proxy-suite \"$backend_config\"" (socksStart allFixture); assert diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 4364f01..af06c3e 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -142,6 +142,10 @@ Changes and secrets need root or the userControl group. apps [list] per-app routing profiles apps run -- [args] run a command through a profile + apps run --via -- run a command through one outbound + (--route tun|tproxy picks the method) + apps add [--route r] [--via o] add a profile without a rebuild + apps rm remove one added that way inbounds [list] server inbounds inbounds link [user] [--onion|--variant=] [--qr|--json] @@ -308,8 +312,8 @@ def denied(path, what="read"): die(f"Cannot {what} {path} - {ask_group()}.") -def _spool_write(path, text=""): - """Replaces path whole, 0640, in a directory userControl's group may write to. +def _spool_write(path, text="", mode=0o640): + """Replaces path whole, 0640 by default, in a directory userControl's group may write to. Through a new file renamed over it: a symlink a member left at path is replaced rather than followed, so proxy-ctl run as root never writes where it points. The file takes @@ -319,7 +323,7 @@ def _spool_write(path, text=""): try: with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(text) - os.chmod(tmp, 0o640) + os.chmod(tmp, mode) os.replace(tmp, path) except BaseException: try: @@ -692,7 +696,13 @@ COMPLETE = { "link": "its URL, QR code, JSON or client config", } }, - "proxy outbounds add": {"flags": {"--detour": "chain it through another outbound"}}, + "proxy outbounds add": { + "flags": { + "--detour": "chain it through another outbound", + "--interface": "an AmneziaWG config on an interface of its own", + "--userspace": "an AmneziaWG config in wireproxy", + } + }, "proxy outbounds link": { "args": _outbound_choices, "flags": {"--qr": "print a QR code", "--json": "backend JSON", "--config": "client config for this server"}, @@ -833,8 +843,23 @@ COMPLETE = { "wl join": {"args": lambda: _names(w["name"] for w in _wl() if w["role"] == "joiner")}, "wl new": {"args": lambda: _names(w["name"] for w in _wl() if w["role"] == "creator" and not w.get("fixedLink"))}, **{f"wl {verb}": {"args": lambda: {w["name"]: w["role"] for w in _wl()}} for verb in ("on", "off", "toggle", "restart")}, - "apps": {"words": {"list": "per-app routing profiles", "run": "run a command through a profile"}}, - "apps run": {"args": lambda: {_s(p["name"]): _s(p.get("route") or "") for p in read_json(env("PER_APP_ROUTING_PROFILES_FILE"))}}, + "apps": { + "words": { + "list": "per-app routing profiles", + "run": "run a command through a profile", + "add": "add a profile at runtime", + "rm": "remove a profile added at runtime", + } + }, + "apps add": {"flags": {"--route": "how the app is routed", "--via": "the outbound it goes through"}}, + "apps rm": {"args": lambda: _names(p["name"] for p in _runtime_apps())}, + "apps run": { + "args": lambda: { + _s(p["name"]): _s(p.get("outbound") or p.get("route") or "") + for p in [*_runtime_apps(), *read_json(env("PER_APP_ROUTING_PROFILES_FILE"))] + }, + "flags": {"--via": "through one outbound, not a profile", "--route": "tun or tproxy, for --via"}, + }, "inbounds": { "words": { "list": "server inbounds", @@ -890,6 +915,16 @@ def _complete_tree(*words): while rest and f"{path} {rest[0]}".strip() in COMPLETE: path = f"{path} {rest.pop(0)}".strip() node = COMPLETE[path] + if path == "apps add" and rest[-1:] == ["--route"]: + return _names(APP_ROUTES) + if path in ("apps run", "apps add") and rest[-1:] == ["--via"]: + return { + **(_outbound_choices() if _pin_routes() else {}), + **_names(_via_outbounds()), + **({p: "AmneziaWG profile" for p in _awg_profiles()} if env("PER_APP_VIA_PROFILES") == "1" else {}), + } + if path == "apps run" and rest[-1:] == ["--route"]: + return _names(_pin_routes()) if rest[-1:] in (["--exits"], ["--via"], ["--detour"]): return _outbound_choices() if rest[-1:] == ["--by"]: @@ -1246,7 +1281,14 @@ def cmd_outbounds(verb="list", *args): del args[i : i + 2] if not container: usage("proxy outbounds add [tag] [--container ]") - _runtime_entry_add("outbound", *args, detour=detour, container=container) + awg_kind = "" + for flag in ("--interface", "--userspace"): + if flag in args: + if awg_kind: + die("Pick one of --interface and --userspace.") + awg_kind = flag[2:] + args.remove(flag) + _runtime_entry_add("outbound", *args, detour=detour, container=container, awg_kind=awg_kind) elif verb == "chain": cmd_outbound_chain(*args) elif verb in ("rm", "remove", "del"): @@ -2528,7 +2570,7 @@ def _runtime_json_outbound(text): def _check_runtime_tag(kind, tag): - if tag in ("proxy", "direct", "block"): + if tag in ("proxy", "direct", "block") or tag.startswith("proxy-suite-"): die(f"'{tag}' is reserved; pick another {kind} tag.") if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", tag): die(f"Invalid {kind} tag '{tag}': letters, digits, dot, dash and underscore only.") @@ -2613,7 +2655,7 @@ def _unique_runtime_tag(kind, name, fallback): return tag -def _runtime_entry_add(kind, *args, detour="", container=""): +def _runtime_entry_add(kind, *args, detour="", container="", awg_kind=""): what = " [--detour ]" if kind == "outbound" else "" shape = f"proxy {_runtime_noun(kind)} add [tag] {what}" if len(args) == 1 and _runtime_source(kind, args[0]): @@ -2634,10 +2676,12 @@ def _runtime_entry_add(kind, *args, detour="", container=""): if kind == "outbound" and _awg_file(url): url = _awg_input(url) if kind == "outbound" and _awg_source(url): - _awg_outbound_add(tag, url, detour, container) + _awg_outbound_add(tag, url, detour, container, awg_kind) return if container: die("--container only applies to an AmneziaWG vpn:// link.") + if awg_kind: + die(f"--{awg_kind} only applies to an AmneziaWG config.") if not tag: tag = _runtime_tag_for(kind, url) _check_runtime_tag(kind, tag) @@ -2711,7 +2755,7 @@ def _runtime_entry_rm(kind, tag="", *_): try: os.unlink(path) # Its hop, and a disable left from it: a new entry of this name would inherit them. - for extra in (".detour", ".disabled", ".port") if kind == "outbound" else (): + for extra in (".detour", ".disabled", ".port", ".iface") if kind == "outbound" else (): if os.path.exists(os.path.join(_runtime_dir(kind), tag + extra)): os.unlink(os.path.join(_runtime_dir(kind), tag + extra)) except FileNotFoundError: @@ -4031,7 +4075,8 @@ def _awg_service(profile): # --- AmneziaWG configs added at runtime ----------------------------------------- # # A .conf or vpn:// link becomes a global profile (`awg add`, amneziawg.d/.conf) or an -# outbound (`proxy outbounds add`, outbounds.d/.awg with its tunnel's port in .port). +# outbound (`proxy outbounds add`, outbounds.d/.awg with its tunnel's port in .port, +# or on an interface of its own, with its slot in .iface). # amneziawg_config.py --import checks and normalizes it, hooks refused. The config always # reaches it on stdin: keys in argv would show in ps. @@ -4132,8 +4177,35 @@ def _awg_free_port(): return port -def _awg_outbound_add(tag, text, detour, container): +def _awg_iface_slots(): + return range(int(env("AWG_IFACE_SLOTS", "16"))) + + +def _awg_free_iface_slot(): + """A slot no .iface holds: the interface psawgr, and its table and marks.""" + taken = set() + directory = _runtime_dir("outbound") + try: + names = os.listdir(directory) + except OSError: + names = [] + for name in names: + if name.endswith(".iface"): + try: + taken.add(int(read_text(os.path.join(directory, name)).split()[0])) + except (OSError, ValueError, IndexError): + pass + slot = next((n for n in _awg_iface_slots() if n not in taken), None) + if slot is None: + die(f"No free slot for another AmneziaWG interface: all {len(_awg_iface_slots())} are taken. Remove one first.") + return slot + + +def _awg_outbound_add(tag, text, detour, container, kind=""): require_enabled("AWG_RUNTIME_OUTBOUNDS", "Adding AmneziaWG outbounds at runtime") + kind = kind or env("AWG_RUNTIME_OUTBOUND_KIND", "userspace") + if kind == "interface": + require_enabled("AWG_RUNTIME_IFACE_OUTBOUNDS", "An AmneziaWG outbound on an interface of its own (root hosts only)") if detour: die("An AmneziaWG outbound cannot chain through another: its tunnel dials the peer itself.") described = _awg_describe(text, container) @@ -4144,13 +4216,17 @@ def _awg_outbound_add(tag, text, detour, container): directory = _runtime_dir("outbound") if not os.access(directory, os.W_OK | os.X_OK): denied(directory, "write to") - port = _awg_free_port() + # The port, or the interface's slot, first: the config is what the start script and the + # sync unit look for. + if kind == "interface": + extra, value, stale = ".iface", _awg_free_iface_slot(), ".port" + else: + extra, value, stale = ".port", _awg_free_port(), ".iface" try: - # The port first: the config is what the start script and the sync unit look for. - for extra in (".detour", ".disabled"): - if os.path.lexists(os.path.join(directory, tag + extra)): - os.unlink(os.path.join(directory, tag + extra)) # left from an earlier entry of this name - _spool_write(os.path.join(directory, f"{tag}.port"), f"{port}\n") + for leftover in (".detour", ".disabled", stale): + if os.path.lexists(os.path.join(directory, tag + leftover)): + os.unlink(os.path.join(directory, tag + leftover)) # left from an earlier entry of this name + _spool_write(os.path.join(directory, tag + extra), f"{value}\n") except OSError: denied(directory, "write to") _awg_write(text, os.path.join(directory, f"{tag}.awg"), container) @@ -4426,11 +4502,90 @@ SLICE_ROUTES = { } -def _per_app_profiles(): +APP_NAME = re.compile(r"[a-z0-9][a-z0-9-]*") +APP_ROUTES = ("direct", "proxychains", "tun", "tproxy", "zapret") + + +def _runtime_apps(): + """Profiles `apps add` added, .json in RUNTIME_APPS_DIR, each marked "runtime".""" + directory = env("RUNTIME_APPS_DIR") try: - return read_json(env("PER_APP_ROUTING_PROFILES_FILE")) + names = sorted(os.listdir(directory)) if directory else [] + except OSError: + names = [] + apps = [] + for file in names: + name = file.removesuffix(".json") + entry = read_json_or(os.path.join(directory, file), {}) if file.endswith(".json") else {} + if APP_NAME.fullmatch(name) and _s(entry.get("route")) in APP_ROUTES: + apps.append({"name": name, "route": _s(entry["route"]), "outbound": _s(entry.get("outbound") or "") or None, "runtime": True}) + return apps + + +def _per_app_profiles(): + """The declared profiles, then those added at runtime under a name none of them has.""" + try: + declared = read_json(env("PER_APP_ROUTING_PROFILES_FILE")) except (OSError, ValueError): die(f"Cannot read perAppRouting profiles: {env('PER_APP_ROUTING_PROFILES_FILE')}") + names = {p.get("name") for p in declared} + return declared + [p for p in _runtime_apps() if p["name"] not in names] + + +APPS_ADD_USAGE = "add [--route direct|proxychains|tun|tproxy|zapret] [--via ]" + + +def _apps_add(*args): + args, route, via = list(args), "", "" + for flag in ("--route", "--via"): + if flag in args: + i = args.index(flag) + value = args[i + 1] if i + 1 < len(args) else "" + del args[i : i + 2] + if not value: + usage(f"apps {APPS_ADD_USAGE}") + route, via = (value, via) if flag == "--route" else (route, value) + if len(args) != 1 or not (route or via): + usage(f"apps {APPS_ADD_USAGE}") + name = args[0] + if not APP_NAME.fullmatch(name): + die(f"Invalid profile name '{name}': lowercase letters, digits and dashes.") + if any(p.get("name") == name and not p.get("runtime") for p in _per_app_profiles()): + die(f"Profile '{name}' is declared in the NixOS configuration; pick another name.") + if route and route not in APP_ROUTES: + die(f"--route is one of {', '.join(APP_ROUTES)}, not '{route}'.") + # An "interface" outbound or a global profile takes the app directly; `apps run` sorts out + # a name that is both. + direct = via in _via_outbounds() or via.startswith("awg:") or (env("PER_APP_VIA_PROFILES") == "1" and via in _awg_profiles()) + if via and not direct: + # Any other outbound goes through a pin slot of the route. + route = route or next(iter(_pin_routes()), "") + if route not in _pin_routes(): + die(f"--via '{via}' needs --route tun or tproxy with pin slots here, or an \"interface\" AmneziaWG outbound.") + directory = env("RUNTIME_APPS_DIR") + if not directory or not os.access(directory, os.W_OK | os.X_OK): + denied(directory or "RUNTIME_APPS_DIR", "write to") + try: + # Readable by everyone: whoever runs apps reads the profiles. + _spool_write(os.path.join(directory, f"{name}.json"), json.dumps({"route": route or "direct", "outbound": via or None}) + "\n", 0o644) + except OSError: + denied(directory, "write to") + print(f"Added app profile: {name}") + + +def _apps_rm(name="", *_): + if not name: + usage("apps rm ") + path = os.path.join(env("RUNTIME_APPS_DIR"), f"{name}.json") + if not APP_NAME.fullmatch(name) or not os.path.exists(path): + if any(p.get("name") == name for p in _per_app_profiles()): + die(f"Profile '{name}' is declared in the NixOS configuration; remove it there.") + die(f"No app profile added at runtime named '{name}'.") + try: + os.unlink(path) + except OSError: + denied(path, "remove") + print(f"Removed app profile: {name}") def _ensure_app_routing(): @@ -4446,13 +4601,21 @@ def _has_units(*args): return bool(re.search(".", systemctl(*args, capture=True)[1])) -def _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, backend_svc): +def _units_active(*globs): + return _has_units("list-units", "--type=service", "--state=active", "--plain", "--no-legend", *globs) + + +def _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, backend_svc, users_glob="", busy=(), then=None): + """busy: globs of other units that keep the backend up; then: what to do once it stopped.""" if _has_units("--user", "list-units", "--type=scope", "--state=running", "--plain", "--no-legend", f"{slice_base}-*"): return systemctl("stop", user_svc) systemctl("--user", "stop", anchor_unit) - if not _has_units("list-units", "--type=service", "--state=active", "--plain", "--no-legend", f"{slice_base}-user@*.service"): + users_glob = users_glob or f"{slice_base}-user@*.service" + if not _units_active(users_glob, *busy): systemctl("stop", backend_svc) + if then: + then() def _stub_resolver_nameservers(path="/etc/resolv.conf"): @@ -4483,16 +4646,22 @@ def _warn_stub_resolver(route): ) -def _wrap_slice(slice_base, profile, backend_svc, cmd): - """Runs cmd in a user scope inside the route's slice, then stops what went idle.""" +def _wrap_slice(slice_base, profile, backend_svc, cmd, units=None, busy=(), then=None, before=()): + """Runs cmd in a user scope inside the route's slice, then stops what went idle. + + units: (anchor, this user's marking unit, a glob of every user's) when they are not + named after the slice. busy and then: as _cleanup_slice_if_idle takes them. before: + units the backend needs up first. + """ uid = os.getuid() scope_unit = f"{slice_base}-{profile}-{os.getpid()}" - anchor_unit = f"{slice_base}-anchor.service" - user_svc = f"{slice_base}-user@{uid}.service" + anchor_unit, user_svc, users_glob = units or (f"{slice_base}-anchor.service", f"{slice_base}-user@{uid}.service", "") # SIGTERM still cleans up, as it did behind bash's EXIT trap. signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) try: status = systemctl("--user", "start", anchor_unit)[0] + for unit in before: + status = status or systemctl("start", unit)[0] status = status or systemctl("start", backend_svc)[0] status = status or systemctl("start", user_svc)[0] if not status: @@ -4510,10 +4679,115 @@ def _wrap_slice(slice_base, profile, backend_svc, cmd): ] ) finally: - _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, backend_svc) + _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, backend_svc, users_glob, busy, then) sys.exit(status) +def _via_outbounds(): + """What `apps run --via` takes: {tag: {...}}, the "interface" AmneziaWG outbounds, which + the app's packets enter directly: declared ones, and those added at runtime.""" + outbounds = read_json_or(env("PER_APP_VIA_FILE"), {}) + if env("PER_APP_VIA_RUNTIME") == "1": + try: + names = os.listdir(_runtime_dir("outbound")) + except OSError: + names = [] + for name in names: + if name.endswith(".iface"): + outbounds.setdefault(name[: -len(".iface")], {"runtime": True}) + return outbounds + + +def _via_key(tag): + """The units' instance for tag. In hex: a "-" in a tag would nest one slice in another's.""" + return "awg-" + tag.encode().hex() + + +# Routes that take any outbound through a pin slot, and the flag that says this host has them. +PIN_ROUTES = {"tun": "PER_APP_PIN_TUN", "tproxy": "PER_APP_PIN_TPROXY"} + + +def _pin_routes(): + return [route for route, flag in PIN_ROUTES.items() if env(flag) == "1"] + + +def _stop_per_app_tun_if_idle(): + """The per-app TUN backend, once neither a tun profile nor a pin of it uses it.""" + if not _units_active("proxy-suite-per-app-tun-user@*.service", "proxy-suite-per-app-via-tun@*.service"): + systemctl("stop", "proxy-suite-per-app-tun.service") + + +def _run_via(tag, label, cmd, route=""): + """Runs cmd with all its traffic through tag, past the routing rules: into an "interface" + AmneziaWG outbound's interface directly, with its DNS; else through a pin slot of per-app + TUN or TProxy (route; TUN when both are there), whose selector sends it to tag. A global + AmneziaWG profile is brought up apart for the apps (proxy-suite-awg-app@), as an + "interface" outbound has it, unless it is up globally already. + + tag may say which it is, "awg:" or "outbound:"; a bare name that is both + is refused. Neither a tag nor a profile name has a colon.""" + kind, name = tag.split(":", 1) if ":" in tag else ("", tag) + if kind not in ("", "awg", "outbound") or not name: + die(f"--via takes an outbound, awg: or outbound:, not '{tag}'.") + label = name if label == tag else label + profiles = _awg_profiles() if env("PER_APP_VIA_PROFILES") == "1" else [] + is_profile = kind != "outbound" and name in profiles + if kind == "awg" and not is_profile: + die(f"No global AmneziaWG profile '{name}' to run apps through. See: proxy-ctl awg") + if not kind and is_profile and (name in _via_outbounds() or name in _outbound_tags()): + die(f"'{name}' is both a global AmneziaWG profile and an outbound: say --via awg:{name} or --via outbound:{name}.") + tag = name + before = () + if not is_profile and tag in _via_outbounds(): + key = _via_key(tag) + unit, global_units, then = f"proxy-suite-per-app-via@{key}.service", ("proxy-suite-tun",), None + elif is_profile: + key = f"app-{tag.encode().hex()}" + unit = f"proxy-suite-per-app-via@{key}.service" + # Up globally, it carries the app already. + global_units = ("proxy-suite-tun", _awg_service(tag)) + before = (f"proxy-suite-awg-app@{tag}.service",) + then = lambda: systemctl("stop", *before) # noqa: E731 + else: + routes = _pin_routes() + route = route or next(iter(routes), "") + if route not in routes: + interfaces = ", ".join(sorted(_via_outbounds())) or "none" + why = ( + f"no pin slots of per-app {route} here (perAppRouting.{route}.enable, the sing-box or hybrid backend)" + if route + else "this configuration has no pin slots: per-app TUN or TProxy, with the sing-box or hybrid backend" + ) + die(f"Cannot run via '{tag}': {why}. \"interface\" AmneziaWG outbounds: {interfaces}.") + tags = _outbound_tags() + if tags and tag not in {*tags, *_outbound_groups(), "proxy", "direct", "block"}: + die(f"Unknown outbound: {tag}. See: proxy-ctl proxy outbounds") + key = f"{route}-{tag.encode().hex()}" + unit = f"proxy-suite-per-app-via-{route}@{tag.encode().hex()}.service" + global_units = ("proxy-suite-tun", "proxy-suite-tproxy") + then = _stop_per_app_tun_if_idle if route == "tun" else None + # A global mode takes the app past the per-app rules; run it as it is rather than refuse, + # like the other per-app routes. + active = next((u for u in global_units if svc_active(f"{u}.service")), "") + if active: + print(f"note: {active}.service is active; running without --via {tag}.", file=sys.stderr) + _exec(list(cmd)) + uid = os.getuid() + _wrap_slice( + f"proxy-suite-per-app-via-{key}", + label, + unit, + list(cmd), + ( + f"proxy-suite-per-app-via-anchor@{key}.service", + f"proxy-suite-per-app-via-user@{uid}-{key}.service", + f"proxy-suite-per-app-via-user@*-{key}.service", + ), + then=then, + before=before, + ) + + def cmd_apps(verb="list", *args): _ensure_app_routing() if verb == "list": @@ -4521,24 +4795,51 @@ def cmd_apps(verb="list", *args): if not profiles: print("No perAppRouting profiles configured.") return - print(f" {'PROFILE':<24} ROUTE") + print(f" {'PROFILE':<24} {'ROUTE':<12} {'VIA':<16} SOURCE") for p in profiles: - print(f" {_s(p.get('name')):<24} {_s(p.get('route'))}") + source = "runtime" if p.get("runtime") else "declared" + print(f" {_s(p.get('name')):<24} {_s(p.get('route')):<12} {_s(p.get('outbound') or '-'):<16} {source}") elif verb == "run": cmd_apps_run(*args) + elif verb == "add": + _apps_add(*args) + elif verb in ("rm", "remove", "del"): + _apps_rm(*args) else: - usage("apps [list] | run -- [args]") + usage(f"apps [list] | {APPS_RUN_USAGE} | {APPS_ADD_USAGE} | rm ") -def cmd_apps_run(profile="", *cmd): - if cmd[:1] == ("--",): - cmd = cmd[1:] - if not profile or not cmd: - usage("apps run -- [args]") +APPS_RUN_USAGE = "run -- [args] | run --via [--route tun|tproxy] -- [args]" - route = next((_s(p.get("route")) for p in _per_app_profiles() if p.get("name") == profile), "") - if not route: + +def cmd_apps_run(*args): + profile, via, route = "", "", "" + args = list(args) + # --via [--route tun|tproxy], before the command. + while args[:1] in (["--via"], ["--route"]): + if len(args) < 2 or not args[1]: + usage(f"apps {APPS_RUN_USAGE}") + if args[0] == "--via": + via = args[1] + else: + route = args[1] + del args[:2] + if route and route not in PIN_ROUTES: + die(f"--route is tun or tproxy, not '{route}'.") + if not via: + profile, args = (args[0], args[1:]) if args and not route else ("", args) + cmd = args[1:] if args[:1] == ["--"] else args + if not (profile or via) or not cmd: + usage(f"apps {APPS_RUN_USAGE}") + if via: + _run_via(via, via, cmd, route) + + entry = next((p for p in _per_app_profiles() if p.get("name") == profile), None) + if entry is None: die(f"Unknown perAppRouting profile: {profile}") + route = _s(entry.get("route")) + if entry.get("outbound"): + _run_via(_s(entry["outbound"]), profile, cmd, route if route in PIN_ROUTES else "") if route == "direct": _exec(list(cmd)) @@ -4560,7 +4861,9 @@ def cmd_apps_run(profile="", *cmd): if env(enabled) != "1": die(f"Profile '{profile}' uses route={route}, but {option} is false.") _warn_stub_resolver(route) - _wrap_slice(slice_base, profile, f"{slice_base}.service", list(cmd)) + # Pins of per-app TUN (apps run --via) keep its backend up too. + busy = ("proxy-suite-per-app-via-tun@*.service",) if route == "tun" else () + _wrap_slice(slice_base, profile, f"{slice_base}.service", list(cmd), busy=busy) else: die(f"Route backend '{route}' is not implemented.") diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index b3cfb05..75fe5b8 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -477,11 +477,27 @@ def _user_add_argv(text): def app_rows(_): return [ - {"key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route"))} + { + "key": ctl._s(p.get("name")), + "profile": ctl._s(p.get("name")), + "route": ctl._s(p.get("route")), + "via": ctl._s(p.get("outbound") or ""), + "source": "runtime" if p.get("runtime") else "declared", + } for p in ctl._per_app_profiles() ] +def _via_run_argv(text): + """ [args], as typed, to `apps run --via`.""" + words = shlex.split(text) + return ["apps", "run", "--via", *words[:1], "--", *words[1:]] + + +def _via_offered(): + return bool(ctl._via_outbounds()) + + def snapshot(states): """proxy-ctl's status snapshot for these unit states; None when it cannot be read.""" return _safe(ctl._status_snapshot, states) @@ -729,6 +745,14 @@ TABS = [ prompt="[tag] - e.g. de-1 vless://… or just vless://…", stdin=lambda r, t: _add_stdin(t), ), + Action( + "N", + "add an AmneziaWG outbound on an interface of its own…", + lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t), "--interface"], + prompt="[tag] - apps can then run through it (proxy-ctl apps run --via)", + stdin=lambda r, t: _add_stdin(t), + offered=lambda: ctl.env("AWG_RUNTIME_IFACE_OUTBOUNDS") == "1", + ), Action( "g", "add a group…", @@ -921,10 +945,13 @@ TABS = [ "Apps", # `apps run` is per user (its uid, systemctl --user): nothing a root session can use. lambda states: not is_root() and _enabled("PER_APP_ROUTING_ENABLED")(states), - [("profile", "Profile"), ("route", "Route")], + [("profile", "Profile"), ("route", "Route"), ("via", "Via"), ("source", "Source")], app_rows, actions=[ + Action("n", "add a profile…", lambda r, t, _: ["apps", "add", *shlex.split(t)], prompt=" [--route tun|tproxy|…] [--via ] - e.g. game --via de"), + Action("d", "remove it", lambda r, *_: ["apps", "rm", r["profile"]], when=lambda r: r["source"] == "runtime", confirm=True), Action("space", "run a command through it…", lambda r, t, _: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt=" [args]", mode="pause"), + Action("v", "run a command via an outbound…", lambda r, t, _: _via_run_argv(t), prompt=" [args] - e.g. de firefox", mode="pause", offered=_via_offered), ], ), ] diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index 1ac0e29..6a4d6a2 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -1293,6 +1293,35 @@ class AmneziaWgRuntimeTest(RuntimeSpoolTest): os.environ["AWG_RUNTIME_OUTBOUNDS"] = "0" self.assertIn("not enabled", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF)[2]) + def test_interface_outbounds(self): + os.environ.update(AWG_RUNTIME_IFACE_OUTBOUNDS="1", AWG_IFACE_SLOTS="2", PER_APP_VIA_RUNTIME="1") + # --interface: a slot in .iface instead of a port, which frees nothing of the tunnels'. + self.assertIn("Added outbound: de", ok(ctl.cmd_outbounds, "add", "de", AWG_CONF, "--interface")) + self.assertEqual(ctl.read_text(self.path("outbounds.d/de.iface")), "0\n") + self.assertFalse(os.path.exists(self.path("outbounds.d/de.port"))) + self.assertEqual(ctl._awg_free_port(), 18800) + # The configuration's default kind, unless the command says. + os.environ["AWG_RUNTIME_OUTBOUND_KIND"] = "interface" + ok(ctl.cmd_outbounds, "add", "nl", AWG_CONF) + self.assertEqual(ctl.read_text(self.path("outbounds.d/nl.iface")), "1\n") + self.assertIn("No free slot", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF)[2]) + ok(ctl.cmd_outbounds, "add", "fr", AWG_CONF, "--userspace") + self.assertEqual(ctl.read_text(self.path("outbounds.d/fr.port")), "18800\n") + # Apps can run through the interface ones. + self.assertEqual(sorted(ctl._via_outbounds()), ["de", "nl"]) + # rm takes the slot along. + ok(ctl.cmd_outbounds, "rm", "de") + self.assertFalse(os.path.exists(self.path("outbounds.d/de.iface"))) + self.assertEqual(ctl._awg_free_iface_slot(), 0) + for args, why in [ + (("x", AWG_CONF, "--interface", "--userspace"), "Pick one"), + (("x", "vless://u@x.test:443", "--interface"), "--interface only applies"), + ]: + with self.subTest(args=args[-1]): + self.assertIn(why, run(ctl.cmd_outbounds, "add", *args)[2]) + os.environ["AWG_RUNTIME_IFACE_OUTBOUNDS"] = "0" + self.assertIn("root hosts only", run(ctl.cmd_outbounds, "add", "x", AWG_CONF, "--interface")[2]) + class ZapretAutoTest(EnvTest): @unittest.skipIf(os.geteuid() == 0, "root writes anything") @@ -1450,8 +1479,10 @@ class AppsRunTest(EnvTest): PROXYCHAINS_CONFIG=self.write("proxychains.conf", ""), PER_APP_ROUTING_PROFILES_FILE=self.write( "profiles.json", - [{"name": n, "route": n} for n in ("direct", "proxychains", "tun", "tproxy", "zapret")], + [{"name": n, "route": n} for n in ("direct", "proxychains", "tun", "tproxy", "zapret")] + + [{"name": "game", "route": "tun", "outbound": "de-2"}], ), + PER_APP_VIA_FILE=self.write("via.json", {"de-2": {"interface": "awg-de", "mark": 23040}}), ) def systemctl(*args, **kw): @@ -1508,6 +1539,155 @@ class AppsRunTest(EnvTest): self.assertIn("proxy-suite-tun.service is active", err) self.assertFalse(any(c[0] == "systemd-run" for c in self.calls)) + def test_via_interface_outbound(self): + # Its own slice and units, keyed by the tag in hex: "de-2" must not nest under "de". + key = "awg-" + "de-2".encode().hex() + uid = os.getuid() + for args, label in ((("--via", "de-2", "--", "curl", "x"), "de-2"), (("game", "--", "curl", "x"), "game")): + self.calls.clear() + status, _, _ = run(ctl.cmd_apps, "run", *args) + self.assertEqual(status, 0) + base = f"proxy-suite-per-app-via-{key}" + scope = next(c for c in self.calls if c[0] == "systemd-run") + self.assertIn(f"--unit={base}-{label}-{os.getpid()}", scope) + self.assertIn(f"--slice={base}", scope) + self.assertEqual(scope[-2:], ("curl", "x")) + self.assertIn(("--user", "start", f"proxy-suite-per-app-via-anchor@{key}.service"), self.calls) + self.assertIn(("start", f"proxy-suite-per-app-via@{key}.service"), self.calls) + self.assertIn(("start", f"proxy-suite-per-app-via-user@{uid}-{key}.service"), self.calls) + self.assertIn(("stop", f"proxy-suite-per-app-via@{key}.service"), self.calls) + listed = next(c for c in self.calls if c[0] == "list-units" and c[-1].startswith("proxy-suite-per-app-via-user@")) + self.assertEqual(listed[-1], f"proxy-suite-per-app-via-user@*-{key}.service") + + def test_via_without_pin_slots(self): + status, _, err = run(ctl.cmd_apps, "run", "--via", "nl", "--", "curl") + self.assertNotEqual(status, 0) + self.assertIn("this configuration has no pin slots", err) + self.assertIn('"interface" AmneziaWG outbounds: de-2.', err) + self.assertFalse(any(c[0] == "systemd-run" for c in self.calls)) + + def test_via_pin_slots(self): + os.environ.update(PER_APP_PIN_TUN="1", PER_APP_PIN_TPROXY="1") + self.patch("_outbound_tags", lambda: ["nl", "de-2"]) + self.patch("_outbound_groups", lambda: {}) + hexed = "nl".encode().hex() + uid = os.getuid() + # TUN when both are there; a profile's route, or --route, picks. + for args, route, label in ( + (("--via", "nl", "--", "curl"), "tun", "nl"), + (("--via", "nl", "--route", "tproxy", "--", "curl"), "tproxy", "nl"), + (("--route", "tproxy", "--via", "nl", "curl"), "tproxy", "nl"), + ): + with self.subTest(args=args): + self.calls.clear() + status, _, _ = run(ctl.cmd_apps, "run", *args) + self.assertEqual(status, 0) + key = f"{route}-{hexed}" + scope = next(c for c in self.calls if c[0] == "systemd-run") + self.assertIn(f"--slice=proxy-suite-per-app-via-{key}", scope) + self.assertIn(f"--unit=proxy-suite-per-app-via-{key}-{label}-{os.getpid()}", scope) + self.assertIn(("start", f"proxy-suite-per-app-via-{route}@{hexed}.service"), self.calls) + self.assertIn(("start", f"proxy-suite-per-app-via-user@{uid}-{key}.service"), self.calls) + self.assertIn(("stop", f"proxy-suite-per-app-via-{route}@{hexed}.service"), self.calls) + # The per-app TUN backend goes too once nothing uses it; the socks backend stays. + self.assertEqual(("stop", "proxy-suite-per-app-tun.service") in self.calls, route == "tun") + self.assertIn("Unknown outbound: fr", run(ctl.cmd_apps, "run", "--via", "fr", "--", "curl")[2]) + self.assertIn("--route is tun or tproxy", run(ctl.cmd_apps, "run", "--via", "nl", "--route", "zapret", "--", "curl")[2]) + os.environ["PER_APP_PIN_TUN"] = "0" + self.assertIn("no pin slots of per-app tun here", run(ctl.cmd_apps, "run", "--via", "nl", "--route", "tun", "--", "curl")[2]) + # A global TProxy takes pinned apps past their route, as it does the other routes. + self.active = {"proxy-suite-tproxy.service"} + run(ctl.cmd_apps, "run", "--via", "nl", "--", "curl", "x") + self.assertEqual(self.execed, ["curl", "x"]) + + def test_runtime_profiles(self): + os.environ.update(PER_APP_PIN_TPROXY="1", RUNTIME_APPS_DIR=self.path("apps.d")) + os.makedirs(self.path("apps.d")) + self.patch("_outbound_tags", lambda: ["nl"]) + self.patch("_outbound_groups", lambda: {}) + self.assertIn("Added app profile: play", ok(ctl.cmd_apps, "add", "play", "--via", "nl")) + ok(ctl.cmd_apps, "add", "chat", "--route", "proxychains") + ok(ctl.cmd_apps, "add", "vpn", "--via", "de-2") + # Readable by whoever runs apps; the pin route chosen now, an interface outbound needs none. + self.assertEqual(os.stat(self.path("apps.d/play.json")).st_mode & 0o777, 0o644) + added = {p["name"]: p for p in ctl._per_app_profiles() if p.get("runtime")} + self.assertEqual((added["play"]["route"], added["play"]["outbound"]), ("tproxy", "nl")) + self.assertEqual((added["chat"]["route"], added["chat"]["outbound"]), ("proxychains", None)) + self.assertEqual(added["vpn"]["outbound"], "de-2") + listing = ok(ctl.cmd_apps, "list") + self.assertRegex(listing, r"play\s+tproxy\s+nl\s+runtime") + self.assertRegex(listing, r"tun\s+tun\s+-\s+declared") + self.assertIn("play", ctl._complete_tree("apps", "rm")) + # Run like a declared one. + self.calls.clear() + self.assertEqual(run(ctl.cmd_apps, "run", "play", "--", "curl")[0], 0) + self.assertIn(("start", f"proxy-suite-per-app-via-tproxy@{'nl'.encode().hex()}.service"), self.calls) + for args, why in [ + (("tun", "--route", "tun"), "declared in the NixOS configuration"), + (("Bad", "--route", "tun"), "Invalid profile name"), + (("x", "--route", "warp"), "--route is one of"), + (("x", "--via", "nl", "--route", "proxychains"), "needs --route tun or tproxy"), + (("x",), "usage"), + ]: + with self.subTest(args=args): + status, out, err = run(ctl.cmd_apps, "add", *args) + self.assertNotEqual(status, 0) + self.assertIn(why, (out + err).lower() if why == "usage" else err) + self.assertIn("remove it there", run(ctl.cmd_apps, "rm", "tun")[2]) + self.assertIn("Removed app profile: play", ok(ctl.cmd_apps, "rm", "play")) + self.assertFalse(os.path.exists(self.path("apps.d/play.json"))) + self.assertIn("No app profile", run(ctl.cmd_apps, "rm", "play")[2]) + + def test_via_global_awg_profile(self): + # Brought up apart for the app, first, and taken down with the last app through it. + os.environ.update(PER_APP_VIA_PROFILES="1", AWG_PROFILES_FILE=self.write("awg.json", ["netcup"])) + key = "app-" + "netcup".encode().hex() + status, _, _ = run(ctl.cmd_apps, "run", "--via", "netcup", "--", "curl", "x") + self.assertEqual(status, 0) + starts = [c[1] for c in self.calls if c[0] == "start"] + self.assertEqual(starts[:2], ["proxy-suite-awg-app@netcup.service", f"proxy-suite-per-app-via@{key}.service"]) + scope = next(c for c in self.calls if c[0] == "systemd-run") + self.assertIn(f"--slice=proxy-suite-per-app-via-{key}", scope) + self.assertIn(("stop", "proxy-suite-awg-app@netcup.service"), self.calls) + self.assertIn("netcup", ctl._complete_tree("apps", "run", "--via")) + # Up globally, it carries the app as it is. + self.calls.clear() + self.active = {"proxy-suite-awg-netcup.service"} + status, _, err = run(ctl.cmd_apps, "run", "--via", "netcup", "--", "curl", "x") + self.assertEqual(self.execed, ["curl", "x"]) + self.assertIn("proxy-suite-awg-netcup.service is active", err) + self.assertNotIn(("start", "proxy-suite-awg-app@netcup.service"), self.calls) + + def test_via_names_both_a_profile_and_an_outbound(self): + # "nl" is an outbound and a global profile: a bare name is refused, a prefix picks. + os.environ.update(PER_APP_VIA_PROFILES="1", PER_APP_PIN_TPROXY="1", AWG_PROFILES_FILE=self.write("awg.json", ["nl"])) + self.patch("_outbound_tags", lambda: ["nl"]) + self.patch("_outbound_groups", lambda: {}) + status, _, err = run(ctl.cmd_apps, "run", "--via", "nl", "--", "curl") + self.assertNotEqual(status, 0) + self.assertIn("say --via awg:nl or --via outbound:nl", err) + hexed = "nl".encode().hex() + for via, unit in (("awg:nl", f"proxy-suite-per-app-via@app-{hexed}.service"), ("outbound:nl", f"proxy-suite-per-app-via-tproxy@{hexed}.service")): + with self.subTest(via=via): + self.calls.clear() + self.assertEqual(run(ctl.cmd_apps, "run", "--via", via, "--", "curl")[0], 0) + self.assertIn(("start", unit), self.calls) + scope = next(c for c in self.calls if c[0] == "systemd-run") + self.assertTrue(any(a.startswith("--unit=") and ":" not in a for a in scope)) + self.assertIn("No global AmneziaWG profile 'fr'", run(ctl.cmd_apps, "run", "--via", "awg:fr", "--", "curl")[2]) + self.assertIn("--via takes an outbound", run(ctl.cmd_apps, "run", "--via", "wg:nl", "--", "curl")[2]) + + def test_tun_profile_keeps_backend_for_pins(self): + self.calls.clear() + run(ctl.cmd_apps, "run", "tun", "--", "curl") + listed = next(c for c in self.calls if c[0] == "list-units" and "proxy-suite-per-app-tun-user@*.service" in c) + self.assertIn("proxy-suite-per-app-via-tun@*.service", listed) + + def test_via_under_global_tun_runs_plain(self): + self.active = {"proxy-suite-tun.service"} + run(ctl.cmd_apps, "run", "--via", "de-2", "--", "curl", "x") + self.assertEqual(self.execed, ["curl", "x"]) + def test_disabled_route(self): os.environ["PER_APP_ROUTING_ZAPRET_ENABLED"] = "0" self.assertIn("perAppRouting.zapret.enable is false", run(ctl.cmd_apps, "run", "zapret", "--", "curl")[2]) diff --git a/scripts/amneziawg_config.py b/scripts/amneziawg_config.py index 8d453c6..61e700a 100644 --- a/scripts/amneziawg_config.py +++ b/scripts/amneziawg_config.py @@ -377,6 +377,18 @@ def _remove_interface_key(config: str, key: str) -> str: return "\n".join(lines) + "\n" +def dns_servers(config: str) -> list[str]: + """The addresses in [Interface] DNS, in order; search domains left out.""" + servers: list[str] = [] + for value in section_values(config, "interface", "dns"): + for item in value.split(","): + try: + servers.append(str(ipaddress.ip_address(item.strip()))) + except ValueError: + pass + return servers + + def as_outbound(config: str, fwmark: int) -> str: """Keep the host's routes and resolver: the proxy binds to the interface instead. @@ -823,6 +835,11 @@ def main() -> int: metavar="MARK", help="render for an outbound-only interface: no routes or DNS, packets marked MARK", ) + parser.add_argument( + "--dns-out", + metavar="FILE", + help="also write the profile's DNS server addresses to FILE, one a line", + ) parser.add_argument( "--wireproxy", metavar="ADDRESS", @@ -894,6 +911,9 @@ def main() -> int: if not isinstance(manifest, dict): raise ConfigError("manifest must be a JSON object") config = prepare(manifest) + if args.dns_out is not None: + # Before the outbound rendering drops them: per-app routing sends the app's DNS here. + write_private(args.dns_out, "".join(f"{server}\n" for server in dns_servers(config))) if args.wireproxy is not None: config = as_wireproxy(config, args.wireproxy, args.outbound_fwmark) elif args.outbound_fwmark is not None: diff --git a/scripts/per_app_dns.py b/scripts/per_app_dns.py new file mode 100644 index 0000000..f633419 --- /dev/null +++ b/scripts/per_app_dns.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""DNS for apps run `--via` an AmneziaWG interface: queries over UDP and TCP on loopback, sent +on to the profile's resolvers from sockets carrying a mark that policy routing takes into the +interface. The app's lookups cannot reach the tunnel themselves: one asked of a stub resolver +on 127.0.0.53 has a loopback source, which the kernel never routes out of a real interface. + +With no route in the interface's table the mark meets an unreachable rule, so a lookup fails +rather than leaving any other way. +""" + +import argparse +import asyncio +import os +import socket +import struct +import sys + +TIMEOUT = 4.0 +MAX_MESSAGE = 65535 + + +def upstream_socket(server: str, kind: int, mark: int) -> socket.socket: + family = socket.AF_INET6 if ":" in server else socket.AF_INET + sock = socket.socket(family, kind) + try: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_MARK, mark) + sock.setblocking(False) + except OSError: + sock.close() + raise + return sock + + +async def ask_udp(query: bytes, servers: list[str], mark: int) -> bytes | None: + """The first answer any server gives, in order; None when none does.""" + loop = asyncio.get_running_loop() + for server in servers: + try: + sock = upstream_socket(server, socket.SOCK_DGRAM, mark) + except OSError: + continue + try: + await loop.sock_connect(sock, (server, 53)) + await loop.sock_sendall(sock, query) + return await asyncio.wait_for(loop.sock_recv(sock, MAX_MESSAGE), TIMEOUT) + except (OSError, asyncio.TimeoutError): + continue + finally: + sock.close() + return None + + +class UdpListener(asyncio.DatagramProtocol): + def __init__(self, servers: list[str], mark: int): + self.servers = servers + self.mark = mark + self.transport = None + + def connection_made(self, transport): + self.transport = transport + + def datagram_received(self, data, addr): + asyncio.ensure_future(self.answer(data, addr)) + + async def answer(self, query, addr): + reply = await ask_udp(query, self.servers, self.mark) + if reply is not None and self.transport is not None: + self.transport.sendto(reply, addr) + + +async def read_message(reader: asyncio.StreamReader) -> bytes | None: + try: + (length,) = struct.unpack("!H", await reader.readexactly(2)) + return await reader.readexactly(length) + except (asyncio.IncompleteReadError, ConnectionError): + return None + + +async def ask_tcp(query: bytes, servers: list[str], mark: int) -> bytes | None: + loop = asyncio.get_running_loop() + for server in servers: + try: + sock = upstream_socket(server, socket.SOCK_STREAM, mark) + except OSError: + continue + try: + await asyncio.wait_for(loop.sock_connect(sock, (server, 53)), TIMEOUT) + reader, writer = await asyncio.open_connection(sock=sock) + except (OSError, asyncio.TimeoutError): + sock.close() + continue + try: + writer.write(struct.pack("!H", len(query)) + query) + await writer.drain() + reply = await asyncio.wait_for(read_message(reader), TIMEOUT) + if reply is not None: + return reply + except (OSError, asyncio.TimeoutError): + pass + finally: + writer.close() + return None + + +def tcp_handler(servers: list[str], mark: int): + async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): + try: + while (query := await asyncio.wait_for(read_message(reader), 30)) is not None: + reply = await ask_tcp(query, servers, mark) + if reply is None: + break + writer.write(struct.pack("!H", len(reply)) + reply) + await writer.drain() + except (OSError, asyncio.TimeoutError): + pass + finally: + writer.close() + + return handle + + +def notify_ready(): + """sd_notify(READY=1), for Type=notify: the start is done once the listeners are up.""" + path = os.environ.get("NOTIFY_SOCKET") + if not path: + return + if path.startswith("@"): + path = "\0" + path[1:] + with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sock: + sock.connect(path) + sock.sendall(b"READY=1") + + +async def serve(port: int, mark: int, servers: list[str]): + loop = asyncio.get_running_loop() + for host in ("127.0.0.1", "::1"): + try: + await loop.create_datagram_endpoint(lambda: UdpListener(servers, mark), local_addr=(host, port)) + await asyncio.start_server(tcp_handler(servers, mark), host, port) + except OSError as exc: + # IPv6 may be off. + if host == "127.0.0.1": + raise + print(f"per-app-dns: not on [{host}]:{port}: {exc}", file=sys.stderr) + notify_ready() + await asyncio.Event().wait() + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--port", type=int, required=True) + parser.add_argument("--mark", type=int, required=True) + parser.add_argument("servers", nargs="*", help="resolver addresses, asked in order") + args = parser.parse_args() + asyncio.run(serve(args.port, args.mark, args.servers)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/test-amneziawg-config.py b/scripts/test-amneziawg-config.py index 52b4520..af36dfd 100644 --- a/scripts/test-amneziawg-config.py +++ b/scripts/test-amneziawg-config.py @@ -499,6 +499,35 @@ class AmneziaWgConfigTests(unittest.TestCase): # The peer is untouched. self.assertIn("Endpoint = vpn.example.com:51820", rendered) + def test_dns_servers_skip_search_domains(self): + config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1, corp.example,2606:4700::1111") + self.assertEqual(amneziawg_config.dns_servers(config), ["1.1.1.1", "2606:4700::1111"]) + self.assertEqual(amneziawg_config.dns_servers("[Interface]\nAddress = 10.0.0.2/32\n"), []) + + def test_dns_out_written_before_outbound_render_drops_dns(self): + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "de.conf" + source.write_text(BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1,8.8.8.8")) + output = Path(directory) / "out.conf" + dns = Path(directory) / "dns" + subprocess.run( + [ + sys.executable, + amneziawg_config.__file__, + "--config", + str(source), + "--output", + str(output), + "--outbound-fwmark", + "2", + "--dns-out", + str(dns), + ], + check=True, + ) + self.assertEqual(dns.read_text(), "1.1.1.1\n8.8.8.8\n") + self.assertEqual(amneziawg_config.section_values(output.read_text(), "interface", "dns"), []) + def test_resolve_endpoints(self): # Under the kill switch awg-quick gets addresses; a name that does not resolve is left. config = "[Peer]\nEndpoint = vpn.example:51820\n[Peer]\nEndpoint = 192.0.2.1:1\nendpoint = [2001:db8::1]:2\n[Peer]\nEndpoint = gone.invalid:3\n"