diff --git a/.github/workflows/dependency-updates.yml b/.github/workflows/dependency-updates.yml index 2c8a11f..4033871 100644 --- a/.github/workflows/dependency-updates.yml +++ b/.github/workflows/dependency-updates.yml @@ -10,9 +10,11 @@ on: type: boolean default: false +# Read-only by default: the job that runs fetched code (flake updates, update-pins.sh, nix +# builds and checks) never holds a token that can push. Only the last job may, and it runs +# nothing it fetched: it applies the first job's diff and opens the pull request. permissions: - contents: write - pull-requests: write + contents: read concurrency: group: dependency-updates @@ -21,12 +23,18 @@ concurrency: jobs: update-dependencies: runs-on: ubuntu-latest + outputs: + has_changes: ${{ steps.changes.outputs.has_changes }} steps: + # No token left in .git/config for the steps that run fetched code (flake updates, + # update-pins.sh, nix builds); create-pull-request authenticates on its own. - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Nix - uses: DeterminateSystems/nix-installer-action@v22 + uses: DeterminateSystems/nix-installer-action@ef8a148080ab6020fd15196c2084a2eea5ff2d25 # v22 - name: Decide whether nixpkgs should be updated id: nixpkgs_gate @@ -112,9 +120,62 @@ jobs: } > "$RUNNER_TEMP/pr-body.md" cat "$RUNNER_TEMP/pr-body.md" >> "$GITHUB_STEP_SUMMARY" - - name: Create or update pull request + # The changes as a patch, new files included, for the job that may push. + - name: Export the changes if: steps.changes.outputs.has_changes == 'true' - uses: peter-evans/create-pull-request@v8 + run: | + set -euo pipefail + git add -A -- flake.lock '*.nix' + git diff --cached --binary > "$RUNNER_TEMP/dependency-updates.patch" + cp "$RUNNER_TEMP/pr-body.md" "$RUNNER_TEMP/dependency-updates.md" + + - name: Upload the changes + if: steps.changes.outputs.has_changes == 'true' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: dependency-updates + path: | + ${{ runner.temp }}/dependency-updates.patch + ${{ runner.temp }}/dependency-updates.md + retention-days: 1 + + - name: No dependency changes + if: steps.changes.outputs.has_changes != 'true' + run: echo "No dependency updates detected." + + open-pull-request: + needs: update-dependencies + if: needs.update-dependencies.outputs.has_changes == 'true' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + + - name: Download the changes + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: dependency-updates + path: ${{ runner.temp }}/dependency-updates + + # Data only: git applies the diff; nothing from it runs. + - name: Apply the changes + run: | + set -euo pipefail + git apply --index "$RUNNER_TEMP/dependency-updates/dependency-updates.patch" + # The commit takes the whole index, whatever add-paths says: refuse a patch + # that reaches past the lock file and the Nix files the updates and nix fmt touch. + if git diff --cached --name-only | grep -vxE 'flake\.lock|.+\.nix'; then + echo "The patch changes files other than flake.lock and *.nix (above)." >&2 + exit 1 + fi + + - name: Create or update pull request + uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 with: branch: ci/update-dependencies delete-branch: false @@ -124,11 +185,7 @@ jobs: *.nix commit-message: "chore(deps): refresh flake inputs and pinned sources" title: "chore(deps): refresh flake inputs and pinned sources" - body-path: ${{ runner.temp }}/pr-body.md + body-path: ${{ runner.temp }}/dependency-updates/dependency-updates.md labels: | dependencies nix - - - name: No dependency changes - if: steps.changes.outputs.has_changes != 'true' - run: echo "No dependency updates detected." diff --git a/README.md b/README.md index f9769b2..240b7de 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ Changes and secrets need root or the userControl group. proxy mode [default|whitelist|blacklist|all-proxy|all-bypass] show or override the routing mode proxy subs [list|update] subscriptions; update refetches them - proxy subs add [tag] add a subscription (no tag: named after its host) + proxy subs add [tag] add a subscription (no tag: named after its host; -: stdin) proxy subs rm remove a runtime subscription proxy subs link [--qr] its URL proxy rulesets [list|update] rule sets and when they were fetched; update refetches diff --git a/deploy/installer.nix b/deploy/installer.nix index 717b925..db1bafa 100644 --- a/deploy/installer.nix +++ b/deploy/installer.nix @@ -20,6 +20,7 @@ mkpasswd, nix, nixos-install-tools, + openssh, openssl, systemd, util-linux, @@ -43,6 +44,7 @@ import ./script.nix { inherit lib writeShellApplication; } { mkpasswd nix nixos-install-tools + openssh openssl systemd util-linux diff --git a/deploy/installer.sh b/deploy/installer.sh index ccb68ad..6fc57eb 100644 --- a/deploy/installer.sh +++ b/deploy/installer.sh @@ -107,7 +107,8 @@ ask_all() { done while true; do ask SSH_PORT "SSH port" "22" - if [[ $SSH_PORT =~ ^[0-9]+$ ]] && ((SSH_PORT >= 1 && SSH_PORT <= 65535)) && + # No leading zero: bash would read 0443 as octal, Nix as 443. + if [[ $SSH_PORT =~ ^[1-9][0-9]{0,4}$ ]] && ((SSH_PORT <= 65535)) && [[ ! " 80 443 2053 8443 18533 18534 18535 " == *" $SSH_PORT "* ]]; then break fi @@ -149,7 +150,7 @@ ask_all() { warn "$DOMAIN does not resolve to $PUBLIC_IP (yet). The certificate order retries until it does." ask_yes KEEP_DOMAIN "Keep $DOMAIN anyway" "y" [[ $KEEP_DOMAIN == true ]] && break - unset PSI_DOMAIN PSI_KEEP_DOMAIN + retry "Give another domain, or none." DOMAIN KEEP_DOMAIN forget KEEP_DOMAIN done @@ -174,18 +175,30 @@ ask_all() { warn "$REALITY_SNI did not answer over TLS 1.3 from here; REALITY needs TLS 1.3 and HTTP/2." ask_yes KEEP_SNI "Keep $REALITY_SNI anyway" "n" [[ $KEEP_SNI == true ]] && break - unset PSI_REALITY_SNI PSI_KEEP_SNI + retry "Give another REALITY site." REALITY_SNI KEEP_SNI forget KEEP_SNI done # --- Disk --------------------------------------------------------------------- step "Disk" - mapfile -t disks < <(lsblk -dnpo NAME,TYPE,RO | awk '$2 == "disk" && $3 == 0 && $1 !~ /\/(zram|loop|sr|fd)[0-9]/ { print $1 }') + # The medium this installer runs from, which some VPS panels attach as a writable disk + # rather than a CD: erasing it would kill the install halfway. + local live_majmin live_disk="" + if live_majmin=$(findmnt -no MAJ:MIN /iso 2>/dev/null) && [[ -e /dev/block/$live_majmin ]]; then + live_disk=$(lsblk -ndpo PKNAME "/dev/block/$live_majmin" 2>/dev/null || true) + [[ -n $live_disk ]] || live_disk=$(readlink -f "/dev/block/$live_majmin") + fi + mapfile -t disks < <(lsblk -dnpo NAME,TYPE,RO | awk -v live="$live_disk" '$2 == "disk" && $3 == 0 && $1 != live && $1 !~ /\/(zram|loop|sr|fd)[0-9]/ { print $1 }') if ((${#disks[@]} == 0)); then warn "No writable disk found." exit 1 fi lsblk -dpo NAME,SIZE,MODEL "${disks[@]}" + # Unattended, the disk to erase is never guessed, even when there is only one. + if [[ -n ${PSI_UNATTENDED-} && -z ${PSI_DISK-} ]]; then + warn "PSI_UNATTENDED: set PSI_DISK to the disk to erase." + exit 1 + fi while true; do ask DISK "Disk to install on (ERASED)" "$(if ((${#disks[@]} == 1)); then printf '%s' "${disks[0]}"; fi)" [[ -b $DISK && " ${disks[*]} " == *" $DISK "* ]] && break @@ -260,6 +273,11 @@ fi xray uuid >"$MNT$SECRETS_DIR/uuid" printf '%s\n' "$private_key" >"$MNT$SECRETS_DIR/reality-key" ) +# The SSH host keys, made here rather than by sshd on the first boot, so the first +# login (with the password, when no key was given) can be checked against them. +install -d -m 0755 "$MNT/etc/ssh" +ssh-keygen -q -t ed25519 -N "" -C "root@$HOST_NAME" -f "$MNT/etc/ssh/ssh_host_ed25519_key" +ssh-keygen -q -t rsa -b 4096 -N "" -C "root@$HOST_NAME" -f "$MNT/etc/ssh/ssh_host_rsa_key" short_id=$(openssl rand -hex 8) ws_path="/$(openssl rand -hex 6)" @@ -267,6 +285,9 @@ ws_path="/$(openssl rand -hex 6)" step "Writing /etc/nixos" etc_nixos="$MNT/etc/nixos" +# Root's alone: it names the REALITY shortId and the WS path, which a local user could +# otherwise read and probe with. +install -m 0600 /dev/null "$etc_nixos/host.nix" cat >"$etc_nixos/host.nix" <` - [acceptProxyProtocol](#services-proxy-suite-inbounds-listeners-name-acceptproxyprotocol) @@ -172,6 +173,16 @@ XRay package that runs the inbounds, whichever client backend is used\. **Default:** proxy-suite’s ` xray ` (` pkgs/xray.nix `)\ **Example:** `pkgs.xray` + +## services\.proxy-suite\.inbounds\.accessLog + +Log every connection, with the user, their address and the site, to the journal of +proxy-suite-inbounds: who went where, for anyone who can read the journal\. On with +` proxy.autoProxy ` whatever this says, which learns from those lines\. + +**Type:** boolean\ +**Default:** `false` + ## services\.proxy-suite\.inbounds\.listeners @@ -531,7 +542,7 @@ clients the rest\. Tunnel IPv6 subnet (ULA)\. ` null `: IPv4 only\. With ` mode = "lan" ` it turns on IPv6 forwarding, which stops this host from configuring itself from router advertisements\. -**Type:** null or string\ +**Type:** null or IPv6 CIDR\ **Default:** `null`\ **Example:** `"fd66:66::/64"` @@ -1106,7 +1117,10 @@ Open the firewall for every listener not on loopback\. ## services\.proxy-suite\.inbounds\.routing\.blockPrivate -Block private and loopback addresses, so clients cannot reach this host’s LAN or local services\. +Block private and loopback addresses, so clients cannot reach this host’s LAN or local +services\. Off, the LAN is open but this host is not\. Either way, this host’s own +addresses (loopback, and its public ones as its interfaces carry them at start) are +reachable only on the listener ports and ` serverPorts `, whichever ` via ` a client takes\. **Type:** boolean\ **Default:** `true` @@ -1228,7 +1242,10 @@ fallbacks\. Members of ` userControl.group ` need the “inbounds” scope\. ## services\.proxy-suite\.inbounds\.runtime\.fallbackDests ` dest ` values a runtime listener’s fallbacks may use, such as a decoy site\. A -fallback to a ` listener ` must name another runtime listener\. +fallback to a ` listener ` must name another runtime listener\. A runtime listener’s +` reality.dest ` may be any public site on port 443; one on another port, on this host +or on a private network must be listed here\. Its ` hysteria.masquerade ` must be a +public http(s) site, on port 80 or 443 unless its ` host:port ` is listed here\. **Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string)\ **Default:** `[ ]`\ @@ -1336,7 +1353,13 @@ covers that name and every name under it, for a host behind a wildcard record\. Ports of this host’s other services that clients reach through the tunnel on ` serverAddress ` and ` serverAliases `, such as mail, beside the listeners’ own\. Direct like those: a connection to this host from itself skips its firewall, so list only -what the firewall already opens to the internet\. TCP and UDP alike\. +what the firewall already opens to the internet\. TCP and UDP alike\. Any other port on +any address of this host is refused where the inbounds dial “direct” themselves; the +addresses are read as the inbounds start, so restart them after one changes (DHCP)\. +Without ` routing.serverSource ` these connections come from this host’s own address, +which its services may trust: a mail server that relays for its own host (Postfix’s +default ` mynetworks `) relays for every inbound user then\. Set ` serverSource `, or keep +such services from trusting this host’s own addresses\. **Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]±\[0-9]+)\ **Default:** `[ ]`\ diff --git a/docs/options/index.md b/docs/options/index.md index 43d19b9..46494a2 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -23,6 +23,7 @@ Update the module option docs there instead of editing these files by hand. | [userControl](./userControl.md) | Let a group use `proxy-ctl` without root. | | [gui](./gui.md) | The desktop app with a tray icon. | | [tui](./tui.md) | The `proxy-tui` terminal UI. | +| [tools](./tools.md) | Heavy helpers `proxy-ctl` can do without: lnav and curl-impersonate. | ## services\.proxy-suite\.enable @@ -69,6 +70,7 @@ services.proxy-suite = { refreshInterval = 3; }; inbounds = { + accessLog = false; enable = false; listeners = { }; openFirewall = true; @@ -109,7 +111,12 @@ services.proxy-suite = { users = { }; }; killSwitch = { + allowedSubnets = config.services.proxy-suite.proxy.tproxy.localSubnets; + directFallbacks = true; enable = false; + timeSyncUsers = ‹the users of the enabled timesyncd, chrony, ntp and openntpd on NixOS; elsewhere +[ "systemd-timesync" "chrony" "_chrony" "ntp" "ntpsec" ] +›; }; perAppRouting = { createDefaultProfiles = false; @@ -228,6 +235,11 @@ services.proxy-suite = { ruleSets = { }; rules = [ ]; }; + runtimeSubscriptions = { + allowHttp = false; + allowInsecure = false; + allowPrivateServers = false; + }; selection = "first"; selectionExclude = [ ]; singBox = { @@ -281,7 +293,7 @@ services.proxy-suite = { user = null; }; serviceUser = "proxy-suite-daemon"; - strictHostKeyChecking = "accept-new"; + strictHostKeyChecking = "yes"; }; tgWsProxy = { bufferKiB = 256; @@ -310,6 +322,14 @@ services.proxy-suite = { secret = null; secretFile = null; }; + tools = { + curlImpersonate = { + enable = ‹true, false on nix-on-droid›; + }; + lnav = { + enable = ‹true, false on nix-on-droid›; + }; + }; tor = { asOutbound = false; bridges = { diff --git a/docs/options/killSwitch.md b/docs/options/killSwitch.md index 73edc42..255516a 100644 --- a/docs/options/killSwitch.md +++ b/docs/options/killSwitch.md @@ -8,14 +8,55 @@ Part of the [proxy-suite options reference](./index.md). - killSwitch - [enable](#services-proxy-suite-killswitch-enable) + - [allowedSubnets](#services-proxy-suite-killswitch-allowedsubnets) + - [directFallbacks](#services-proxy-suite-killswitch-directfallbacks) + - [timeSyncUsers](#services-proxy-suite-killswitch-timesyncusers) ## services\.proxy-suite\.killSwitch\.enable Block outgoing traffic that bypasses the active global tunnel (TUN, TProxy or a global -AmneziaWG profile), including while it restarts or after it fails\. LAN, DHCP and NTP stay -open; ` proxy.tproxy.lanInterfaces ` devices keep the LAN but lose the internet\. Only turning -the tunnel off, or ` proxy-ctl killswitch off `, lifts it\. +AmneziaWG profile) from boot until the tunnel is up, while it restarts and after it +fails\. LAN, DHCP and the time daemons’ NTP stay open\. Forwarded traffic TProxy does not +divert reaches the LAN only from ` proxy.tproxy.lanInterfaces `\. With TUN or a global +AmneziaWG profile configured, containers’ and VMs’ traffic is held to the LAN too while +neither that tunnel nor TProxy is up\. Only turning the tunnel off with ` proxy-ctl `, or +` proxy-ctl killswitch off `, lifts it, until the next boot or tunnel start\. **Type:** boolean\ **Default:** `false` + + +## services\.proxy-suite\.killSwitch\.allowedSubnets + +Networks the kill switch leaves open besides the private and reserved ranges, such as +a routed IPv6 prefix on a VM bridge, whichever global mode is on\. The default keeps +what TProxy leaves out reachable; set it to open a network without also taking it out +of TProxy\. + +**Type:** list of IPv4 or IPv6 address or CIDR\ +**Default:** `config.services.proxy-suite.proxy.tproxy.localSubnets`\ +**Example:** `[ "192.168.0.0/16" "2001:db8:1::/64" ]` + + +## services\.proxy-suite\.killSwitch\.directFallbacks + +Whether, with the kill switch on, a subscription that cannot be fetched through the +tunnel is fetched once more directly, and WARP registers directly when the local proxy +cannot carry it\. Either shows that server this host’s own address\. Off, both go through +the tunnel or not at all: a cold start with nothing cached then has no outbounds from +that subscription, and a WARP device that is itself the tunnel cannot register\. + +**Type:** boolean\ +**Default:** `true` + + +## services\.proxy-suite\.killSwitch\.timeSyncUsers + +Users that may send NTP (UDP port 123) past the kill switch\. Users that do not exist +are skipped when it starts\. A daemon sending from port 123 itself, as ntpd does, needs +no entry\. + +**Type:** list of string\ +**Default:** the users of the enabled timesyncd, chrony, ntp and openntpd on NixOS; elsewhere ` [ "systemd-timesync" "chrony" "_chrony" "ntp" "ntpsec" ] `\ +**Example:** `[ "chrony" ]` diff --git a/docs/options/perAppRouting.md b/docs/options/perAppRouting.md index e47d713..298f349 100644 --- a/docs/options/perAppRouting.md +++ b/docs/options/perAppRouting.md @@ -141,7 +141,7 @@ Firewall mark for wrapped apps’ traffic\. Subnets that skip the proxy (DNS still goes through it)\. -**Type:** list of string\ +**Type:** list of IPv4 or IPv6 address or CIDR\ **Default:** `[ "192.168.0.0/16" ]`\ **Example:** `[ "192.168.0.0/16" "10.0.0.0/8" ]` @@ -164,9 +164,9 @@ Whether to enable per-app TUN\. ## services\.proxy-suite\.perAppRouting\.tun\.address -Interface address (CIDR)\. +Interface IPv4 address (CIDR)\. -**Type:** string\ +**Type:** IPv4 CIDR\ **Default:** `"172.20.0.1/30"` @@ -182,7 +182,7 @@ Firewall mark for wrapped apps’ traffic\. Interface name\. -**Type:** string\ +**Type:** network interface name\ **Default:** `"psperapptun0"` @@ -190,7 +190,7 @@ Interface name\. Subnets that skip the proxy (DNS still goes through it)\. -**Type:** list of string\ +**Type:** list of IPv4 or IPv6 address or CIDR\ **Default:** `[ "192.168.0.0/16" ]`\ **Example:** `[ "192.168.0.0/16" "10.0.0.0/8" ]` @@ -217,7 +217,7 @@ Subnets an app run ` --via ` an AmneziaWG interface (an “interface” outbound 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\ +**Type:** list of IPv4 or IPv6 address or CIDR\ **Default:** `[ "192.168.0.0/16" ]`\ **Example:** `[ "192.168.0.0/16" "10.0.0.0/8" ]` diff --git a/docs/options/proxy.md b/docs/options/proxy.md index ef6dfe1..d63e2df 100644 --- a/docs/options/proxy.md +++ b/docs/options/proxy.md @@ -103,6 +103,10 @@ Part of the [proxy-suite options reference](./index.md). - [ips](#services-proxy-suite-proxy-routing-rules-ips) - [outbound](#services-proxy-suite-proxy-routing-rules-outbound) - [ruleSets](#services-proxy-suite-proxy-routing-rules-rulesets) + - runtimeSubscriptions + - [allowHttp](#services-proxy-suite-proxy-runtimesubscriptions-allowhttp) + - [allowInsecure](#services-proxy-suite-proxy-runtimesubscriptions-allowinsecure) + - [allowPrivateServers](#services-proxy-suite-proxy-runtimesubscriptions-allowprivateservers) - [selection](#services-proxy-suite-proxy-selection) - [selectionExclude](#services-proxy-suite-proxy-selectionexclude) - singBox @@ -111,6 +115,8 @@ Part of the [proxy-suite options reference](./index.md). - [subscriptionUpdateInterval](#services-proxy-suite-proxy-subscriptionupdateinterval) - [subscriptions](#services-proxy-suite-proxy-subscriptions) - item + - [allowInsecure](#services-proxy-suite-proxy-subscriptions-allowinsecure) + - [allowPrivateServers](#services-proxy-suite-proxy-subscriptions-allowprivateservers) - [detour](#services-proxy-suite-proxy-subscriptions-detour) - [tag](#services-proxy-suite-proxy-subscriptions-tag) - [url](#services-proxy-suite-proxy-subscriptions-url) @@ -192,7 +198,8 @@ authentication, even with ` proxy.listener.auth ` set\. ## services\.proxy-suite\.proxy\.autoProxy\.probesPerRun -Maximum destinations probed per run\. The rest wait for the next run, most-used first\. +Maximum destinations probed per run: of those asked for with ` proxy-ctl proxy auto learn `, and again of those queued from traffic\. The rest wait for the next run, the +queued ones most-used first\. A run also ends after two hours, its probes kept\. **Type:** positive integer, meaning >0\ **Default:** `200` @@ -449,9 +456,10 @@ Subscriptions whose every entry is a member, as the subscription holds them at s ## services\.proxy-suite\.proxy\.ipv6 -Route IPv6 through TUN and TProxy too\. When off, TProxy ignores IPv6 and the TUNs block -it, so apps fall back to IPv4\. If the uplink has no IPv6, also set -` proxy.dns.strategy = "ipv4_only" `, or direct IPv6 connections hang instead of falling back\. +Route IPv6 through TUN and TProxy too\. When off, TProxy refuses IPv6 past the LAN and +on-link prefixes and the TUNs block it, so apps fall back to IPv4\. If the uplink has no +IPv6, also set ` proxy.dns.strategy = "ipv4_only" `, or direct IPv6 connections hang +instead of falling back\. **Type:** boolean\ **Default:** `config.networking.enableIPv6` @@ -461,7 +469,7 @@ it, so apps fall back to IPv4\. If the uplink has no IPv6, also set Address of the local SOCKS5/HTTP proxy\. Use “0\.0\.0\.0” only to expose it to the network\. -**Type:** string\ +**Type:** IP address or host name\ **Default:** `"127.0.0.1"` @@ -837,9 +845,9 @@ Download through the proxy or directly\. ## services\.proxy-suite\.proxy\.routing\.ruleSets\.\\.url -URL of the sing-box rule set\. +URL of the sing-box rule set (https only)\. -**Type:** string matching the pattern https?://\.+\ +**Type:** string matching the pattern https://\.+\ **Example:** `"https://example.com/antifilter.srs"` @@ -921,6 +929,35 @@ Rule sets from ` proxy.routing.ruleSets ` that this rule matches (sing-box and h **Default:** `[ ]`\ **Example:** `[ "antifilter" ]` + +## services\.proxy-suite\.proxy\.runtimeSubscriptions\.allowHttp + +Let subscriptions added at runtime (` proxy-ctl proxy subs add `) be fetched over plain +http\. Anyone on the way can then add entries of their own\. + +**Type:** boolean\ +**Default:** `false` + + +## services\.proxy-suite\.proxy\.runtimeSubscriptions\.allowInsecure + +Keep entries of subscriptions added at runtime that turn certificate checks off, as +` subscriptions.*.allowInsecure ` does for a declared one\. Anyone on the way can then +stand in for those servers\. + +**Type:** boolean\ +**Default:** `false` + + +## services\.proxy-suite\.proxy\.runtimeSubscriptions\.allowPrivateServers + +Keep entries of subscriptions added at runtime whose server is a private address, as +` subscriptions.*.allowPrivateServers ` does for a declared one\. Whoever can add a +subscription then picks servers on your network\. + +**Type:** boolean\ +**Default:** `false` + ## services\.proxy-suite\.proxy\.selection @@ -986,6 +1023,31 @@ start, cached, and refreshed on a timer\. ` proxy-ctl proxy subs add ` adds more **Default:** `[ ]`\ **Example:** `[ { tag = "private"; urlFile = "/run/secrets/private-sub-url"; } ]` + +## services\.proxy-suite\.proxy\.subscriptions\.\*\.allowInsecure + +Keep entries that turn certificate checks off (` insecure=1 `, for hysteria2 and +AnyTLS on sing-box), as for a provider with self-signed certificates\. Anyone on the +way can then stand in for those servers\. Dropped otherwise\. For subscriptions added +at runtime, see ` proxy.runtimeSubscriptions.allowInsecure `\. + +**Type:** boolean\ +**Default:** `false` + + +## services\.proxy-suite\.proxy\.subscriptions\.\*\.allowPrivateServers + +Keep entries whose server is a private address (10\.0\.0\.0/8, 172\.16\.0\.0/12, +192\.168\.0\.0/16, 100\.64\.0\.0/10, fc00::/7), such as a subscription served on your own +network\. Entries pointing at this host (loopback, “localhost”, unspecified) or at a +link-local or multicast address are dropped either way: whoever serves the list picks +the servers, and the fastest wins\. Only literal addresses (and “localhost”) are +checked\. For subscriptions added at runtime, see +` proxy.runtimeSubscriptions.allowPrivateServers `\. + +**Type:** boolean\ +**Default:** `false` + ## services\.proxy-suite\.proxy\.subscriptions\.\*\.detour @@ -1047,7 +1109,7 @@ LAN interfaces whose devices use this host as their gateway\. Their TCP and UDP proxy; everything else is forwarded as usual\. Turns on IP forwarding\. Needs the nftables firewall on NixOS\. -**Type:** list of string\ +**Type:** list of network interface name\ **Default:** `[ ]`\ **Example:** `[ "br0" ]` @@ -1056,7 +1118,7 @@ firewall on NixOS\. Subnets that skip the proxy, such as your LAN and VM bridges (DNS still goes through it)\. IPv6 works too\. -**Type:** list of string\ +**Type:** list of IPv4 or IPv6 address or CIDR\ **Default:** `[ "192.168.0.0/16" ]`\ **Example:** `[ "192.168.0.0/16" "10.0.0.0/8" "fd00::/8" ]` @@ -1095,9 +1157,9 @@ Whether to enable global TUN mode\. ## services\.proxy-suite\.proxy\.tun\.address -TUN interface address (CIDR)\. +TUN interface IPv4 address (CIDR)\. -**Type:** string\ +**Type:** IPv4 CIDR\ **Default:** `"172.19.0.1/30"` @@ -1105,7 +1167,7 @@ TUN interface address (CIDR)\. TUN interface name\. -**Type:** string\ +**Type:** network interface name\ **Default:** `"singtun0"` diff --git a/docs/options/sshProxy.md b/docs/options/sshProxy.md index ae2fa02..a4bb92b 100644 --- a/docs/options/sshProxy.md +++ b/docs/options/sshProxy.md @@ -64,8 +64,8 @@ Extra OpenSSH arguments\. ## services\.proxy-suite\.sshProxy\.hostKey -Accepted host keys, for sing-box\. List every key ` ssh-keyscan ` prints, since the key type -is negotiated\. +Accepted host keys, for sing-box, and for OpenSSH without ` knownHostsFile `\. List every +key ` ssh-keyscan ` prints, since the key type is negotiated\. **Type:** list of string\ **Default:** `[ ]`\ @@ -74,7 +74,7 @@ is negotiated\. ## services\.proxy-suite\.sshProxy\.hostKeyFile -Known-hosts file to read host keys from (sing-box)\. Takes priority over ` hostKey `\. +Known-hosts file to read host keys from (sing-box, and OpenSSH without ` knownHostsFile `)\. Takes priority over ` hostKey `\. **Type:** null or string\ **Default:** `null`\ @@ -109,7 +109,9 @@ Address of the OpenSSH SOCKS5 listener\. ## services\.proxy-suite\.sshProxy\.listener\.port -Port of the OpenSSH SOCKS5 listener\. +Port of the OpenSSH SOCKS5 listener\. It takes no login: where it is the XRay backend’s +hop (` asOutbound `) on a host with root, only proxy-suite’s daemons and root may +connect to it\. A standalone tunnel stays open to every local user\. **Type:** 16 bit unsigned integer; between 0 and 65535 (both inclusive)\ **Default:** `1091` @@ -143,17 +145,20 @@ SSH login user\. ## services\.proxy-suite\.sshProxy\.serviceUser -User that runs OpenSSH\. The default is sandboxed; ` null ` runs it as root\. +User that runs OpenSSH\. The default is sandboxed; ` null ` runs it as root\. Another user’s +traffic gets past the kill switch, all of it: never a login user’s\. -**Type:** null or string matching the pattern \[^\[:space:]]+\ +**Type:** null or string matching the pattern \[a-z_]\[a-z0-9_-]\*\[$]?\ **Default:** `"proxy-suite-daemon"`\ **Example:** `"proxy"` ## services\.proxy-suite\.sshProxy\.strictHostKeyChecking -OpenSSH host key policy\. +OpenSSH host key policy\. “yes” needs the server’s keys: ` knownHostsFile `, or else +` hostKeyFile ` or ` hostKey `\. “accept-new” takes whatever key the first connection +meets, which anyone on the way can answer then\. **Type:** one of “yes”, “accept-new”, “no”\ -**Default:** `"accept-new"`\ -**Example:** `"yes"` +**Default:** `"yes"`\ +**Example:** `"accept-new"` diff --git a/docs/options/tools.md b/docs/options/tools.md new file mode 100644 index 0000000..9e3e376 --- /dev/null +++ b/docs/options/tools.md @@ -0,0 +1,31 @@ +# services.proxy-suite.tools + +Heavy helpers `proxy-ctl` can do without: lnav and curl-impersonate. + +Part of the [proxy-suite options reference](./index.md). + +## Options + +- tools + - curlImpersonate + - [enable](#services-proxy-suite-tools-curlimpersonate-enable) + - lnav + - [enable](#services-proxy-suite-tools-lnav-enable) + + +## services\.proxy-suite\.tools\.curlImpersonate\.enable + +Probe with curl-impersonate (` proxy-ctl proxy auto probe `, and autoProxy), which +presents a browser’s TLS fingerprint\. Without it probes use plain curl, which some +bot protection refuses, so a working exit can be judged blocked\. + +**Type:** boolean\ +**Default:** ` true `, ` false ` on nix-on-droid + + +## services\.proxy-suite\.tools\.lnav\.enable + +Follow ` proxy-ctl logs ` in lnav\. Without it they follow in less\. + +**Type:** boolean\ +**Default:** ` true `, ` false ` on nix-on-droid diff --git a/docs/options/tor.md b/docs/options/tor.md index 4acdd2e..2da7f15 100644 --- a/docs/options/tor.md +++ b/docs/options/tor.md @@ -66,7 +66,7 @@ File with more bridge lines, one per line\. Blank lines and \# comments are skip Bridge lines from https://bridges\.torproject\.org, without the leading “Bridge”\. Setting any turns bridges on\. -**Type:** list of string\ +**Type:** list of string matching the pattern \[^ ]\*\ **Default:** `[ ]`\ **Example:** @@ -159,7 +159,9 @@ Bridge transport for snowflake\. ## services\.proxy-suite\.tor\.socksPort -Loopback SOCKS port of Tor\. +Loopback SOCKS port of Tor\. Tor takes no login on it, so with ` asOutbound ` on a host with +root only proxy-suite’s daemons and root may connect to it; other users reach Tor +through the proxy’s own listener\. **Type:** 16 bit unsigned integer; between 0 and 65535 (both inclusive)\ **Default:** `18530` diff --git a/docs/options/zapret.md b/docs/options/zapret.md index ab4ead8..f5ca082 100644 --- a/docs/options/zapret.md +++ b/docs/options/zapret.md @@ -89,7 +89,7 @@ Whether to enable skipping zapret for some subnets, such as NATed VMs it would b Subnets zapret skips\. -**Type:** list of string\ +**Type:** list of IPv4 or IPv6 address or CIDR\ **Default:** `[ ]`\ **Example:** `[ "192.168.123.0/24" ]` @@ -411,7 +411,7 @@ UDP packets sent, with at most ` udpIn ` replies, that count as a failure\. Extra fake payloads by name (blob=\): a file in zapret2’s files/fake, or an absolute path\. -**Type:** attribute set of string\ +**Type:** attribute set of string matching the pattern \[^\[:space:]]+\ **Default:** `{ }`\ **Example:** `{ tls_clienthello = "/etc/proxy-suite/my_clienthello.bin"; }` @@ -449,7 +449,7 @@ Log everything nfqws2 does to the journal, every packet included\. Very verbose: Domains always treated as blocked\. At runtime: ` proxy-ctl zapret auto add `\. -**Type:** list of string\ +**Type:** list of string matching the pattern \[^\[:space:]]+\ **Default:** `[ ]`\ **Example:** `[ "rutracker.org" ]` @@ -458,7 +458,7 @@ Domains always treated as blocked\. At runtime: ` proxy-ctl zapret auto add `\. Domains never touched or learned\. At runtime: ` proxy-ctl zapret auto exclude `\. -**Type:** list of string\ +**Type:** list of string matching the pattern \[^\[:space:]]+\ **Default:** `[ ]`\ **Example:** `[ "bank.example.com" ]` diff --git a/docs/usage/control.md b/docs/usage/control.md index 1fef2b7..31d4a38 100644 --- a/docs/usage/control.md +++ b/docs/usage/control.md @@ -112,7 +112,8 @@ proxy-ctl restart # restart what is running In a terminal, `proxy-ctl logs` follows in [`lnav`](https://lnav.org): it follows while at the bottom, scrolling back pauses it, `G` follows again, `e`/`E` jump between errors, `/` searches, and `q` or Ctrl-C quits. `:enable-word-wrap` wraps long lines, and lnav remembers -it for the next time. Piped, it is plain `journalctl -f`. +it for the next time. Without lnav ([`tools.lnav.enable`](../options/tools.md#services-proxy-suite-tools-lnav-enable), +off on Nix-on-Droid) it follows in `less`. Piped, it is plain `journalctl -f`. ## See also diff --git a/docs/usage/examples/workstation.md b/docs/usage/examples/workstation.md index 0ba183f..886e3f0 100644 --- a/docs/usage/examples/workstation.md +++ b/docs/usage/examples/workstation.md @@ -84,8 +84,9 @@ The tray app shows the same, and switches with a click. - `wrapEnv` sets the proxy variables for one program only, so the rest of the system keeps its direct routing. `protocol = "all"` sets both kinds, for a program whose choice you do not know. -- The kill switch guards whichever global tunnel is on (TUN or the VPN), and does nothing - while both are off. +- The kill switch guards whichever global tunnel is on (TUN or the VPN). It is up from boot, + so the internet stays blocked until one of them starts; turning a tunnel off with + `proxy-ctl` lifts it. - While global TUN is on, per-app `tun` profiles run the app as it is. Everything already goes through the proxy then. - See [Wrap programs with the proxy](../wrap-apps.md) for the helpers, and diff --git a/docs/usage/other-hosts.md b/docs/usage/other-hosts.md index eb9010a..ed2df7b 100644 --- a/docs/usage/other-hosts.md +++ b/docs/usage/other-hosts.md @@ -67,6 +67,15 @@ nixOnDroidConfigurations.default = nix-on-droid.lib.nixOnDroidConfiguration { optimisation for it. - Point other apps at `127.0.0.1:1080`, in their own proxy settings or in the Wi-Fi proxy settings. +- To save space, `proxy-ctl` comes without lnav and curl-impersonate: `proxy-ctl logs` + follows in `less`, and probes use plain curl. Set + [`tools.lnav.enable`](../options/tools.md#services-proxy-suite-tools-lnav-enable) and + [`tools.curlImpersonate.enable`](../options/tools.md#services-proxy-suite-tools-curlimpersonate-enable) + to have them back. +- Every app on the phone can reach `127.0.0.1`, not only the ones you point at the proxy: set + `proxy.listener.auth` so that only those you give the login to can use it. The loopback + hops behind it take a login of their own, drawn per boot, except Tor's SOCKS port and the + OpenSSH tunnel's under XRay, which take none: any app reaches those exits. ## See also diff --git a/docs/usage/per-app.md b/docs/usage/per-app.md index 6f8022a..ecb8933 100644 --- a/docs/usage/per-app.md +++ b/docs/usage/per-app.md @@ -109,8 +109,11 @@ services.proxy-suite = { 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. +- With `tun` and `tproxy`, the app's DNS queries go through its route wherever its resolver + is, a local one (such as systemd-resolved on 127.0.0.53) or the LAN router. Lookups glibc + hands to nscd (NixOS's default) do not: nscd resolves them itself, outside the route. + `proxy-ctl` warns when nscd runs. Apps that resolve names themselves are not affected: + programs built with Go, and browsers using their own resolver or DNS-over-HTTPS. - The app follows your [routing rules](./routing.md) like any other proxied traffic. ## See also diff --git a/docs/usage/routing.md b/docs/usage/routing.md index 0db2a4d..bec2feb 100644 --- a/docs/usage/routing.md +++ b/docs/usage/routing.md @@ -7,7 +7,9 @@ applies to the local proxy, TUN, TProxy and per-app routing alike. 1. `proxy.routing.rules`, in order. The first match wins, and a rule can name a specific outbound. -2. The `proxy`, `direct` and `block` lists. +2. The lists: `proxy.domains` and `proxy.ips` first, then `block`, then `direct`, then + `proxy.geosites`, `proxy.geoips` and `proxy.ruleSets`. A name in both a block and a direct + list (an ad domain under `category-ru`, say) is blocked. 3. Anything left goes to `proxy.routing.default`: `"proxy"` (the default) or `"direct"`. Russian sites and IPs go direct unless you set `routing.directRu = false`. diff --git a/docs/usage/server.md b/docs/usage/server.md index 0095130..6529005 100644 --- a/docs/usage/server.md +++ b/docs/usage/server.md @@ -148,6 +148,9 @@ Without root, members of `userControl.group` need the `inbounds` scope. - Clients cannot reach this host's LAN or Russian sites by default (`inbounds.routing.blockPrivate`, `blockRu`). +- Through "direct", clients reach this host itself only on the listeners' ports and + `inbounds.serverPorts` (80/443 with subscriptions), whatever it listens on. Its addresses + are read when the inbounds start: restart them after the address changes. - With `routing.via = "proxy"` (the default), client traffic goes through this host's own proxy instead, following its routing. That needs `proxy.enable`. A listener can also exit through one outbound with `via = ""`. diff --git a/docs/usage/system-wide.md b/docs/usage/system-wide.md index a0b3506..e7a8687 100644 --- a/docs/usage/system-wide.md +++ b/docs/usage/system-wide.md @@ -44,8 +44,20 @@ proxy-ctl killswitch off # lift the kill switch without stopping the tunnel ## Good to know -- The kill switch blocks outgoing traffic while the tunnel restarts or after it fails, so - nothing leaks. LAN, DHCP and NTP stay open. Turning the tunnel off lifts it. +- The kill switch blocks outgoing traffic from boot until the tunnel is up, while it restarts + and after it fails, so nothing leaks. LAN, DHCP and the time daemon's NTP stay open. + Subscriptions are fetched through the tunnel; only if that fails are they fetched + directly, so the proxy can come up from a cold cache. The subscription host then sees + your address. Turning the tunnel off with `proxy-ctl` lifts the kill switch until the + next boot or tunnel start. +- With TUN or a global AmneziaWG profile, the kill switch also holds forwarded traffic + (Docker, libvirt, podman) to the LAN while the tunnel is down. TProxy diverts only + `proxy.tproxy.lanInterfaces`, so in TProxy mode other containers and VMs bypass the proxy + whether the tunnel is up or not. With TProxy alone the kill switch lets them through, and + with TUN or AmneziaWG also configured it cuts them off in TProxy mode. +- Networks the kill switch should leave open besides the private ranges, such as a routed + IPv6 prefix on a VM bridge, go in `killSwitch.allowedSubnets`. It defaults to + `proxy.tproxy.localSubnets`, so what TProxy leaves out stays reachable. - If the uplink has no IPv6, set `proxy.dns.strategy = "ipv4_only"` (sing-box). Otherwise direct IPv6 connections hang instead of falling back to IPv4. - `proxy.tproxy.localSubnets` lists networks that skip TProxy. Add your LAN and VM bridges if diff --git a/modules/proxy-suite/amnezia-wg-inbounds.nix b/modules/proxy-suite/amnezia-wg-inbounds.nix index dbe6531..04acb4b 100644 --- a/modules/proxy-suite/amnezia-wg-inbounds.nix +++ b/modules/proxy-suite/amnezia-wg-inbounds.nix @@ -49,6 +49,10 @@ let in '' chain listener_${toString index} { + # Cloud instance metadata (credentials, IAM tokens): for this host alone, never + # for its clients, "lan" or not. + ip daddr { ${lib.concatStringsSep ", " derived.constants.cloudMetadata.ipv4} } drop + ip6 daddr { ${lib.concatStringsSep ", " derived.constants.cloudMetadata.ipv6} } drop fib daddr type { local, broadcast, multicast } ${verdict} ip daddr $RESERVED_IP ${verdict} # Not in RESERVED_IP, whose other users route it by the local subnets instead. @@ -97,6 +101,13 @@ let } ''; + # The table swapped in whole, in one transaction, also after a firewall reload flushed it. + nftReplaceFile = pkgs.writeText "proxy-suite-routing" '' + table inet ${nftTable} + delete table inet ${nftTable} + include "${nftRulesFile}" + ''; + routingDown = lib.concatMapStrings (family: '' @@ -129,6 +140,10 @@ let ${stop} + # Before any interface is up: its iifname matches already, so no client packet comes + # in ahead of the confinement. + ${nft} -f ${nftRulesFile} + PYTHONPATH=${scriptsDir} ${python3} ${scriptsDir}/awg_inbound.py prepare \ --spec ${proxyInboundsSpecFile} --awg ${awg} --runtime-dir "$RUNTIME_DIRECTORY" \ > "$RUNTIME_DIRECTORY/interfaces" @@ -153,8 +168,6 @@ let ${ip} ${family} rule add pref ${toString awgInboundRulePriority} iif ${lib.escapeShellArg listener.interface} fwmark ${toString awgInboundFwmark} table ${toString awgInboundRouteTable} '') listeners} '') ([ "-4" ] ++ lib.optional ipv6 "-6")} - - ${nft} -f ${nftRulesFile} ''; in { @@ -180,9 +193,19 @@ in services.${unitName} = { description = "proxy-suite AmneziaWG inbound interfaces"; - after = [ "network-online.target" ]; + # After nftables, whose start flushes what came before it on flushRuleset hosts. + after = [ + "network-online.target" + "nftables.service" + ]; wants = [ "network-online.target" ]; wantedBy = [ "multi-user.target" ]; + # Put back after a firewall reload that flushed the ruleset, and restarted along with a + # restart of nftables, which a reload hook never hears of. + unitConfig = { + ReloadPropagatedFrom = [ "nftables.service" ]; + PartOf = [ "nftables.service" ]; + }; path = [ awgCfg.toolsPackage awgCfg.userspacePackage @@ -199,6 +222,7 @@ in StateDirectory = "proxy-suite"; UMask = "0077"; ExecStart = start; + ExecReload = "${nft} -f ${nftReplaceFile}"; ExecStop = stop; LockPersonality = true; ProtectClock = true; diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index 153d1c3..8f41a41 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -176,7 +176,9 @@ let # 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 + # No leading zero (bash reads it as octal) and three digits at most (a long one wraps + # around in bash arithmetic): an out-of-range table reaches `ip route flush` as root. + if [[ ! $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] || (( slot >= ${toString awgRuntimeIfaceSlots} )); then echo "proxy-suite: AmneziaWG outbound '$profile_name' needs a slot in 0-${ toString (awgRuntimeIfaceSlots - 1) } in $profile_name.iface" >&2 @@ -258,7 +260,7 @@ let fi echo "$slot" > "$slot_file" fi - if [[ ! $slot =~ ^[0-9]+$ ]]; then + if [[ ! $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] || (( slot >= ${toString derived.constants.awgAppSlots} )); then echo "proxy-suite: AmneziaWG profile '$profile_name' is not up for apps" >&2 exit 1 fi @@ -387,6 +389,7 @@ let fwmark=$(${awgCfg.toolsPackage}/bin/awg show ${lib.escapeShellArg profile.interfaceName} fwmark) # Off when the profile routes nothing by default (a table of its own, or Table=off). if [[ "$fwmark" != off ]]; then + ${awgIPv6FallbackUp} ${serverUdpRulesUp} ${pkgs.nftables}/bin/nft -f - </dev/null || true ${serverUdpRulesDown} + ${awgIPv6FallbackDown} + ''; + + # A global profile without IPv6 (AllowedIPs 0.0.0.0/0 alone): IPv6 unreachable rather than + # out the uplink, behind the main table's more specific routes. $fwmark: the interface's. + ip6 = "${pkgs.iproute2}/bin/ip -6"; + awgIPv6FallbackUp = '' + table=$((fwmark)) + if [ -e /proc/net/if_inet6 ] && [ -z "$(${ip6} route show default table "$table" 2>/dev/null)" ]; then + ${ip6} route replace unreachable default table "$table" + ${ip6} rule add not fwmark "$table" table "$table" + ${ip6} rule add table main suppress_prefixlength 0 + fi + ''; + # The interface (and its fwmark) may be gone: found by the rule naming its mark as its + # table and that table's unreachable default, which awg-quick's never has. + awgIPv6FallbackDown = '' + while read -r mark table; do + [[ $mark =~ ^(0x[0-9a-f]+|[0-9]+)$ && $table =~ ^[0-9]+$ ]] && (( mark == table )) || continue + ${ip6} route show table "$table" 2>/dev/null | ${pkgs.gnugrep}/bin/grep -q '^unreachable default' || continue + while ${ip6} rule del not fwmark "$table" table "$table" 2>/dev/null; do :; done + ${ip6} rule del table main suppress_prefixlength 0 2>/dev/null || true + ${ip6} route flush table "$table" 2>/dev/null || true + done < <(${ip6} rule show 2>/dev/null | ${pkgs.gawk}/bin/awk '$2 == "not" && $5 == "fwmark" && $7 == "lookup" { print $6, $8 }') ''; # awg-quick turns src_valid_mark on for a default route and never back off; left on, it @@ -447,18 +474,9 @@ let } ''; - # Under the kill switch, glibc would hand the Endpoint lookup to nscd or systemd-resolved, - # whose own queries the kill switch rejects. With both out of the way it asks resolved's - # upstreams itself, under the unit's group, and awg-quick gets the Endpoint as an address. - ownLookups = pkgs.writeShellScript "proxy-suite-awg" '' - mount=${pkgs.util-linux}/bin/mount - # Best effort: at worst the lookup goes the usual way. - if [ -S /run/nscd/socket ]; then $mount --bind /dev/null /run/nscd/socket || true; fi - if [ -s /run/systemd/resolve/resolv.conf ]; then - $mount --bind /run/systemd/resolve/resolv.conf /etc/resolv.conf || true - fi - exec "$@" - ''; + # The Endpoint lookup under the kill switch, under the unit's group: awg-quick gets it as + # an address. + ownLookups = derived.constants.ownLookups pkgs; # A global profile, or an "interface" outbound: a unit for a declared profile (staticSpec), # or the template the runtime ones start from (runtimeSpec). `conflicts`: the global units @@ -527,6 +545,9 @@ let ${spec.release or ""} } trap cleanup ERR + # Stopped (or conflicted out) during the handshake wait: no ExecStop follows a start + # that never finished, so what is up so far would stay up with the unit inactive. + trap 'cleanup; exit 143' TERM INT ${awgCommon.modprobe} @@ -604,7 +625,6 @@ let "proxy-suite-tun.service" "proxy-suite-tproxy.service" "proxy-suite-zapret.service" - "proxy-suite-per-app-zapret.service" "proxy-suite-zapret-vm-exempt.service" ]; } @@ -640,7 +660,15 @@ let (withArg prepare) ] ++ lib.optionals (!outbound && derived.awgRuntimeGlobal) [ (withArg stopRuntimeProfiles) ] - ++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ]; + ++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ] + # Per-app zapret and this profile's copy for apps have nothing to add once it is up, + # and never take it down themselves (constants.refuseUnderGlobal). + ++ lib.optionals (!outbound) [ + (derived.constants.stopPerAppUnits pkgs [ + "proxy-suite-per-app-zapret.service" + "proxy-suite-awg-app@${if spec.template then "%i" else name}.service" + ]) + ]; ExecStart = withArg start; ExecStop = withArg stop; } @@ -696,7 +724,7 @@ let unit = "proxy-suite-awg-tunnel@"; runtimeDirectory = "proxy-suite-awg-tunnel-%i"; engine = "userspace"; - tag = "$TUNNEL_TAG"; + # `profile` sets $TUNNEL_TAG. tunnelPort = "$TUNNEL_PORT"; execArgs = " %i"; # The sync unit starts one per entry. @@ -716,7 +744,7 @@ let fi # O_NOFOLLOW: the spool is group-writable, and the port is echoed back on error. TUNNEL_PORT=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$TUNNEL_TAG.port" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true) - if [[ ! $TUNNEL_PORT =~ ^[0-9]+$ ]] || (( TUNNEL_PORT < ${toString awgRuntimeTunnelBasePort} || TUNNEL_PORT > ${toString runtimeTunnelLastPort} )); then + if [[ ! $TUNNEL_PORT =~ ^[1-9][0-9]{0,4}$ ]] || (( TUNNEL_PORT < ${toString awgRuntimeTunnelBasePort} || TUNNEL_PORT > ${toString runtimeTunnelLastPort} )); then echo "proxy-suite: AmneziaWG outbound '$TUNNEL_TAG' needs a port in ${toString awgRuntimeTunnelBasePort}-${toString runtimeTunnelLastPort} in $TUNNEL_TAG.port" >&2 exit 1 fi @@ -790,7 +818,14 @@ let # moves off it now rather than at its next test. hint() { local health="${runtimeDir}/proxy-suite-outbound-groups/health" - [[ -d $health ]] && ${pkgs.coreutils}/bin/touch "$health/$profile_name" 2>/dev/null || true + local hint="$health/$profile_name" + [[ -d $health ]] || return 0 + # Never through a symlink the service user's group left: O_EXCL (noclobber), touch -h. + if [[ -e $hint || -L $hint ]]; then + ${pkgs.coreutils}/bin/touch -h "$hint" 2>/dev/null || true + else + (set -C; : > "$hint") 2>/dev/null || true + fi } ${lib.optionalString egressProbe '' new_session() { @@ -971,7 +1006,18 @@ in (lib.mapAttrs' ( name: profile: lib.nameValuePair (serviceName name) ( - mkService (staticSpec name profile) (allProfileConflicts name) + lib.mkMerge [ + (mkService (staticSpec name profile) (allProfileConflicts name)) + { + # Ordered (one way, by name) so the old profile's cleanup of table 51820 ends before the + # new one starts; Conflicts= alone lets them overlap. + after = lib.optionals (builtins.elem name globalProfileNames) ( + map (other: "${serviceName other}.service") ( + builtins.filter (other: other < name) globalProfileNames + ) + ); + } + ] ) ) interfaceProfiles) (lib.mapAttrs' ( @@ -983,8 +1029,8 @@ in (mkService runtimeSpec (map (other: "${serviceName other}.service") globalProfileNames)) { wants = [ "proxy-suite-awg-watchdog@%i.service" ]; - # The kill switch cannot order itself after instances it does not know. - before = [ killSwitchUnit ]; + # After the declared ones it conflicts with: their stop goes first (as above). + after = map (other: "${serviceName other}.service") globalProfileNames; } ]; "proxy-suite-awg-watchdog@" = mkWatchdog runtimeSpec; @@ -998,10 +1044,13 @@ in (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" + # Not while the profile is up globally, declared or added with `awg add`: that + # carries the apps already, and takes this one down as it starts. + serviceConfig.ExecStartPre = lib.mkBefore [ + (derived.constants.refuseUnderGlobal pkgs [ + "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"; diff --git a/modules/proxy-suite/autoproxy-migrate.nix b/modules/proxy-suite/autoproxy-migrate.nix new file mode 100644 index 0000000..be04eb8 --- /dev/null +++ b/modules/proxy-suite/autoproxy-migrate.nix @@ -0,0 +1,15 @@ +# Moves autoProxy's state dir from the old group-writable layout to root's alone, with the +# spool beside it. Run by the socks start script and the autoProxy units, whichever is first. +{ pkgs }: + +let + fillTemplate = import ./lib/fill-template.nix; +in +pkgs.writeShellScript "proxy-suite-autoproxy-migrate" ( + fillTemplate ./autoproxy-migrate.template.sh { + path = pkgs.lib.makeBinPath [ + pkgs.coreutils + pkgs.findutils + ]; + } +) diff --git a/modules/proxy-suite/autoproxy-migrate.template.sh b/modules/proxy-suite/autoproxy-migrate.template.sh new file mode 100644 index 0000000..d7eb261 --- /dev/null +++ b/modules/proxy-suite/autoproxy-migrate.template.sh @@ -0,0 +1,35 @@ +set -euo pipefail +# $1 - autoProxy's state dir, $2 - the spool members queue requests in +export PATH=@path@ +dir=$1 +spool=$2 + +# Until the spool, the autoProxy scope's group wrote to the state dir too. A no-op once done. + +# Root's alone now; 0751: the group reads it, sing-box searches through to rules/. +install -d -m 0751 "$dir" + +# The old queues go to the spool, read through no link (to a file only root may read) +# and never blocking on a FIFO. With no spool to take them, they are dropped. +for name in requests edits requests.taking edits.taking; do + f="$dir/$name" + [ -e "$f" ] || [ -L "$f" ] || continue + if [ -d "$spool" ]; then + # The spool is sticky: no member can swap the name in the meantime. + tmp=$(mktemp "$spool/.migrated.XXXXXX") + dd if="$f" iflag=nofollow,nonblock status=none > "$tmp" 2>/dev/null || true + chmod 0640 "$tmp" + # -T: a directory (or a link to one) a member left under that name takes nothing in. + mv -fT "$tmp" "$spool/${name%.taking}.migrated${tmp##*/.migrated}" + fi + rm -rf -- "$f" +done + +# Then whatever else a member left: links, files not root's, special files, and any of +# root's names holding the wrong kind of file. +find "$dir" -mindepth 1 -maxdepth 1 \( -type l -o ! -uid "$(id -u)" -o ! \( -type f -o -type d \) \) \ + -exec rm -rf -- {} + +for name in state.json lock samples; do + [ ! -e "$dir/$name" ] || [ -f "$dir/$name" ] || rm -rf -- "${dir:?}/$name" +done +[ ! -e "$dir/rules" ] || [ -d "$dir/rules" ] || rm -f -- "$dir/rules" diff --git a/modules/proxy-suite/autoproxy-run.template.sh b/modules/proxy-suite/autoproxy-run.template.sh index a74730b..6ee1455 100644 --- a/modules/proxy-suite/autoproxy-run.template.sh +++ b/modules/proxy-suite/autoproxy-run.template.sh @@ -6,30 +6,41 @@ mode=${1:-full} # Overridable to rehearse a run against a scratch copy; the units never set them. state_dir=${AUTOPROXY_STATE_DIR:-@stateDir@} +spool=${AUTOPROXY_SPOOL_DIR:-@spoolDir@} export PROBE_EXITS_FILE=${PROBE_EXITS_FILE:-@runtimeDir@/proxy-suite-socks/probe-exits.json} index=$PROBE_EXITS_FILE state="$state_dir/state.json" -requests="$state_dir/requests" -edits="$state_dir/edits" now=$(date +%s) ttl=$(( @ttlDays@ * 86400 )) -install -d -m @stateDirMode@ "$state_dir" +@migrate@ "$state_dir" "$spool" # Timer runs and learn requests take turns on the state. exec 9> "$state_dir/lock" flock 9 -# Leftovers of a run that died partway; taken requests go back in line. +# Leftovers of a run that died partway. rm -f "$state_dir/verdicts.json" "$state_dir/proxied-domains.txt" "$state".?????? "$state_dir/samples.taking" -for queue in "$requests" "$edits"; do - if [ -e "$queue.taking" ]; then - cat "$queue.taking" >> "$queue" - rm -f "$queue.taking" - # Made here by root: the group appends to it too. - chmod 0660 "$queue" - fi -done + +# `proxy-ctl proxy auto` requests: a file each in the spool, named to sort by time. Sets +# taken to queue $1's files, oldest first. +take() { + local f + taken=() + for f in "$spool/$1".*; do + [ -e "$f" ] || [ -L "$f" ] || continue + taken+=("$f") + done +} +# A spool file, read through no symlink, never blocking on a FIFO, 64 KiB at most. +read_queue() { + dd if="$1" iflag=nofollow,nonblock,fullblock bs=64K count=1 status=none 2>/dev/null || true +} +# Taken files go one argv at a time (xargs): a member can queue more of them than one +# command line holds, which would fail every run from then on. +drop_taken() { + [ "${#taken[@]}" -eq 0 ] || printf '%s\0' "${taken[@]}" | xargs -0 rm -rf -- +} if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then echo "$state is unreadable; set aside as $state.broken, starting fresh" >&2 @@ -55,8 +66,8 @@ update() { # Before anything else, and even with the proxy stopped: its start renders the # rule-sets from the state again. edited="" -if [ -s "$edits" ]; then - mv -f "$edits" "$edits.taking" +take edits +for f in "${taken[@]}"; do while read -r op dom; do case "$op" in forget) @@ -71,9 +82,11 @@ if [ -s "$edits" ]; then *) continue ;; esac edited=1 - done < "$edits.taking" - rm -f "$edits.taking" -fi + done < <(read_queue "$f") + # Once applied: a run killed before this applies it again, to the same end. -r: a + # directory a member left under such a name would fail the run each time. + rm -rf -- "$f" +done if [ ! -r "$index" ]; then echo "no probe listeners - is proxy-suite-socks running with autoProxy on?" @@ -92,6 +105,16 @@ if [ -r "$inventory" ]; then | (.domains // {}) | to_entries[] | select(.value.exit as $e | $off | index([$e])) | "\(.key)\t\(.value.exit)"' "$state") fi +# Once: routes learned under a public suffix (a whole workers.dev) before to_reg knew the +# list, to be learned again per site. +if ! jq -e '.suffixesForgotten' "$state" > /dev/null; then + while read -r dom; do + update --arg op forget --arg d "$dom" -f @editJq@ + echo "forgot $dom: a public suffix, not one site" + edited=1 + done < <(jq -r '(.domains // {}) | keys[]' "$state" | grep -xFf @publicSuffixes@ || true) + update '.suffixesForgotten = true' +fi [ -z "$edited" ] || @render@ "$index" "$state" # $1 JSON array of exit tags, $2 registrable domain, $3 wall:|refused|slow. @@ -132,28 +155,50 @@ record() { end' <<<"$3") } -# Prefixes each host line with "registrable-domain". -# ponytail: last two labels, or three under a short list of two-label -# suffixes. Switch to the Public Suffix List if a domain gets merged wrongly. +# Prefixes each host line with "registrable-domain", by the public suffix list (private +# section too: foo.workers.dev is a site). A public suffix itself is no site: skipped. to_reg() { - awk -F'\t' ' + awk -F'\t' -v list=@publicSuffixes@ ' BEGIN { - n = split("co.uk org.uk ac.uk gov.uk com.au net.au org.au co.jp ne.jp or.jp com.br com.tr co.kr com.cn com.hk co.in co.za com.ua com.mx co.nz", s, " ") - for (i = 1; i <= n; i++) two[s[i]] = 1 + while ((getline rule < list) > 0) { + if (substr(rule, 1, 1) == "!") exc[substr(rule, 2)] = 1 + else if (substr(rule, 1, 2) == "*.") wild[substr(rule, 3)] = 1 + else exact[rule] = 1 + } } { - n = split($1, l, ".") + host = tolower($1) + n = split(host, l, ".") if (n < 2) next - k = (n >= 3 && (l[n - 1] "." l[n]) in two) ? l[n - 2] "." l[n - 1] "." l[n] : l[n - 1] "." l[n] + # Labels in the longest public suffix: an exception rule, an exact one, or a + # wildcard over the rest; none at all is the implicit "*". + s = 1 + for (i = 1; i <= n; i++) { + c = l[i] + for (j = i + 1; j <= n; j++) c = c "." l[j] + rest = substr(c, length(l[i]) + 2) + if (c in exc) { s = n - i; break } + if ((c in exact) || (rest != "" && rest in wild)) { s = n - i + 1; break } + } + if (s >= n) next + k = l[n - s]; for (j = n - s + 1; j <= n; j++) k = k "." l[j] print k "\t" $0 }' } # The pinned direct listener, since TUN/TProxy capture --noproxy too. direct_url=$(jq -r '.[0] | "http://127.0.0.1:\(.port)"' "$index") +# The probe listeners' login, drawn per start (start-scripts.nix): to curl through a +# config on a pipe, as argv is public. +probe_login="$(dirname "$index")/probe-login" +probe_curlrc() { + if [ -r "$probe_login" ]; then + printf 'proxy-user = "%s"\n' "$(tr -d '\r\n"\\' < "$probe_login")" + fi +} # --- 1. verdicts are about this host's address; drop them if it changed --- -egress=$(curl -sS -f --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true) +egress=$(curl -sS -f -K <(probe_curlrc) --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true) # An error page or a captive portal must not pass for a new address: anything # that is not one discards every verdict this host learned. [[ "$egress" =~ ^[0-9a-fA-F.:]+$ ]] || egress="" @@ -166,8 +211,11 @@ fi # --- 2. which network (AS) each exit leaves from, once per TTL --- while IFS=$'\t' read -r tag port; do at=$(jq -r --arg t "$tag" '.exits[$t].at // 0' "$state") + # Digits only: a state.json from when the group could write it may hold anything, and + # $(( )) would run what a[$(...)] names. + [[ "$at" =~ ^[0-9]{1,12}$ ]] || at=0 [ $(( now - at )) -ge "$ttl" ] || continue - info=$(curl -sS --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true) + info=$(curl -sS -K <(probe_curlrc) --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true) ip=$(jq -r '.ip // empty' <<<"$info" 2>/dev/null || true) asn=$(jq -r '(.org // "") | split(" ")[0]' <<<"$info" 2>/dev/null || true) [ -n "$ip" ] || continue @@ -269,7 +317,11 @@ if [ "$mode" = full ]; then first: (.[$e.key].first // $now) } end)) | .backlog |= with_entries(select(.value.first + $ttl > $now - and $s.domains[.value.domain].exit == null))' + and $s.domains[.value.domain].exit == null)) + # Bounded, as every distinct name dialled is an entry; the most dialled stay. + | if (.backlog | length) > 5000 then + .backlog |= (to_entries | sort_by(-.value.hits) | .[:5000] | from_entries) + else . end' # --- 4b. what the sampler saw crawl (see autoproxy-slow-judge.jq) --- if [ -s "$state_dir/samples" ]; then @@ -324,19 +376,36 @@ if [ "$mode" = full ]; then echo "slow $dom: crawls ${was:+via $was}${was:-directly}, and no other exit reaches it; left direct" update --arg d "$dom" --argjson until $(( now + ttl )) '.slowSkip[$d] = $until | del(.slowWant[$d])' fi - done < <(jq -r '(.slowWant // {}) | to_entries[] + # A few per run, each probed via every exit: the rest wait for the next run rather + # than hold the lock for hours. + done < <(jq -r '(.slowWant // {}) | to_entries[:20][] | "\(.key)\t\(.value.host)\t\(.value.tried | join(","))"' "$state") [ "$(jq -c '.domains' "$state")" = "$before" ] || publish fi fi -# --- 5. probe: requests (uncapped), then broken routes, then the backlog --- +# --- 5. probe: requests, then broken routes, then the backlog --- asked=() -if [ -s "$requests" ]; then - mv -f "$requests" "$requests.taking" - mapfile -t asked < <(grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' "$requests.taking" | to_reg || true) - rm -f "$requests.taking" +take requests +if [ "${#taken[@]}" -gt 0 ]; then + mapfile -t asked < <( + for f in "${taken[@]}"; do + read_queue "$f" + echo + done | grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' | awk '!seen[$0]++' | to_reg || true + ) + drop_taken +fi +# probesPerRun of them at most: a member could queue hosts by the hundred thousand, each a +# probe holding the lock. The rest go back to the spool, for the next run. +if [ "${#asked[@]}" -gt @probesPerRun@ ]; then + rest=$(mktemp "$spool/.requests.XXXXXX") + printf '%s\n' "${asked[@]:@probesPerRun@}" | cut -f2 > "$rest" + chmod 0640 "$rest" + mv -fT "$rest" "$spool/requests.$(date +%s%N).$$" + echo "$(( ${#asked[@]} - @probesPerRun@ )) requested host(s) past probesPerRun wait for the next run" + asked=("${asked[@]:0:@probesPerRun@}") fi backlog=() if [ "$mode" = full ]; then diff --git a/modules/proxy-suite/autoproxy-sample.template.sh b/modules/proxy-suite/autoproxy-sample.template.sh index b26f550..caac257 100644 --- a/modules/proxy-suite/autoproxy-sample.template.sh +++ b/modules/proxy-suite/autoproxy-sample.template.sh @@ -7,7 +7,8 @@ if [ -z "$clash_api" ]; then echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample" exit 0 fi -install -d -m @stateDirMode@ "$state_dir" +# Before appending to samples by name: on an old install, a member may have left a link. +@migrate@ "$state_dir" "${AUTOPROXY_SPOOL_DIR:-@spoolDir@}" # Eleven snapshots a second apart: ten one-second deltas per connection. lines=$( diff --git a/modules/proxy-suite/autoproxy-slow-judge.jq b/modules/proxy-suite/autoproxy-slow-judge.jq index fb2c749..3b68306 100644 --- a/modules/proxy-suite/autoproxy-slow-judge.jq +++ b/modules/proxy-suite/autoproxy-slow-judge.jq @@ -25,3 +25,6 @@ del(.domains[$e.key]) | .slowWant[$e.key] = {host: $e.value.host, tried: ($e.value.tried // [$e.value.exit])}) | .slowSkip = ((.slowSkip // {}) | with_entries(select(.value > $now))) +# Bounded, as the backlog: each crawling name a client loads would be an entry otherwise. +| if (.slowHits | length) > 5000 then .slowHits |= (to_entries | sort_by(-.value.n) | .[:5000] | from_entries) else . end +| if (.slowWant | length) > 500 then .slowWant |= (to_entries | .[:500] | from_entries) else . end diff --git a/modules/proxy-suite/autoproxy.nix b/modules/proxy-suite/autoproxy.nix index ef7ec34..bd8ddfb 100644 --- a/modules/proxy-suite/autoproxy.nix +++ b/modules/proxy-suite/autoproxy.nix @@ -7,6 +7,7 @@ cfg, proxyCtl, autoProxyStateDir, + autoProxySpoolDir, runtimeDir, journalctl, userControlAllows, @@ -17,14 +18,14 @@ let apCfg = cfg.proxy.autoProxy; derived = import ./derived.nix { inherit lib cfg; }; inherit (derived.constants) rootInSharedDirConfig; - # The autoProxy scope's groups write the directory: `proxy auto learn` queues there. Those - # in userControl.groups through ACLs, which the group bits (the ACL mask) leave open. - stateDirMode = if derived.userControlAnyAllows "autoProxy" then "0771" else "0751"; + # The autoProxy scope's groups read the state (userControl.groups through ACLs), root alone + # writes it (autoproxy-migrate.nix sets the mode). grantAcl = pkgs.writeShellScript "proxy-suite-autoproxy-acl" ( derived.constants.grantDirAcl pkgs (lib.escapeShellArg autoProxyStateDir) (derived.userControlExtraGroupsFor "autoProxy") - "rwX" + "rX" ); + migrate = import ./autoproxy-migrate.nix { inherit pkgs; }; render = import ./autoproxy-render.nix { inherit pkgs; inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser ifPrivileged; @@ -36,20 +37,32 @@ let inherit path; }; - bin = lib.makeBinPath [ - pkgs.coreutils - pkgs.curl - pkgs.gawk - pkgs.gnugrep - pkgs.gnused - pkgs.jq - pkgs.systemd - pkgs.util-linux - proxyCtl - ]; + bin = lib.makeBinPath ( + [ + pkgs.coreutils + pkgs.curl + pkgs.findutils + pkgs.gawk + pkgs.gnugrep + pkgs.gnused + pkgs.jq + ] + # journalctl; proxy-suitectl, by path, answers it on its own. + ++ lib.optional (cfg.host.serviceManager != "supervisor") pkgs.systemd + ++ [ + pkgs.util-linux + proxyCtl + ] + ); excludePattern = lib.concatStringsSep "|" (map lib.escapeRegex apCfg.exclude); + # Public suffixes, the private section's too, in the xn-- form names come in: to_reg groups + # a host under its registrable domain by them. + publicSuffixes = + pkgs.runCommand "proxy-suite-autoproxy-public-suffixes" { nativeBuildInputs = [ pkgs.python3 ]; } + "python3 ${./zapret2/public-suffixes.py} --private ${pkgs.publicsuffix-list}/share/publicsuffix/public_suffix_list.dat >$out"; + # Sets $clash_api (empty when the API is off) and $clash_secret (curl sends it through # clash_auth_header, never argv, which every local user can read). clashApiBlock = '' @@ -64,7 +77,8 @@ let fillTemplate ./autoproxy-sample.template.sh { path = bin; stateDir = lib.escapeShellArg autoProxyStateDir; - inherit runtimeDir clashApiBlock stateDirMode; + spoolDir = lib.escapeShellArg autoProxySpoolDir; + inherit runtimeDir clashApiBlock migrate; minBytes = toString (300 * 1024); slowBelowBytes = toString (apCfg.slowBelowKiBps * 1024); slowSampleJq = jqFile ./autoproxy-slow-sample.jq; @@ -75,41 +89,77 @@ let fillTemplate ./autoproxy-run.template.sh { path = bin; stateDir = lib.escapeShellArg autoProxyStateDir; + spoolDir = lib.escapeShellArg autoProxySpoolDir; inherit runtimeDir; ttlDays = toString apCfg.ttlDays; - inherit stateDirMode; + inherit migrate; editJq = jqFile ./autoproxy-edit.jq; inherit render; strikeJq = jqFile ./autoproxy-strike.jq; roundsJq = jqFile ./autoproxy-rounds.jq; interval = apCfg.interval; inherit journalctl; - excludeHosts = lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |"; + # Quoted whole: escapeRegex leaves a quote or backtick in a name as it is. + excludeHosts = lib.optionalString ( + excludePattern != "" + ) "grep -vE ${lib.escapeShellArg "(^|\\.)(${excludePattern})$"} |"; excludeSampleHosts = lib.optionalString ( excludePattern != "" - ) "grep -vE '(^|\\.)(${excludePattern})'$'\\t' |"; + ) "grep -vE ${lib.escapeShellArg "(^|\\.)(${excludePattern})"}$'\\t' |"; slowJudgeJq = jqFile ./autoproxy-slow-judge.jq; probesPerRun = toString apCfg.probesPerRun; + inherit publicSuffixes; } ); - # Group: `proxy-ctl proxy auto list|queue` reads state.json, `learn` queues requests. - # Set on every unit that declares the directory - systemd re-applies the ownership - # on each start. + # Group: `proxy-ctl proxy auto list|queue` reads state.json. Set on every unit that + # declares the directory - systemd re-applies the ownership on each start. stateDirConfig = { StateDirectory = "proxy-suite/autoproxy"; # 0751 and a 027 umask: sing-box (proxy-suite-daemon) reaches the rule-sets through - # rules/, which its group reads (autoproxy-render.nix), and nothing else. - StateDirectoryMode = stateDirMode; + # rules/, which its group reads (autoproxy-render.nix), and nothing else. An existing + # directory takes it from autoproxy-migrate.nix: systemd leaves its mode be. + StateDirectoryMode = "0751"; UMask = "0027"; - # Inside the sandbox below, which keeps a name a member left there from leading it - # anywhere else. ExecStartPre = "${grantAcl}"; } // lib.optionalAttrs (userControlAllows "autoProxy") { Group = cfg.userControl.group; } - # Root writes by fixed names in a directory the group writes to: nowhere else, whatever - # a name there points at. - // rootInSharedDirConfig; + # Root works in the spool members write to: nothing else is writable. + // rootInSharedDirConfig + // lib.optionalAttrs cfg.host.privileged { + ReadWritePaths = [ "-${autoProxySpoolDir}" ]; + # Nothing it runs (curl, jq, proxy-ctl, systemctl) is setuid. + NoNewPrivileges = true; + LockPersonality = true; + RestrictRealtime = true; + # Root for files alone: chgrp, ACLs, the spool and the Clash secret (CHOWN, FOWNER, DAC_*). + CapabilityBoundingSet = [ + "CAP_CHOWN" + "CAP_DAC_OVERRIDE" + "CAP_DAC_READ_SEARCH" + "CAP_FOWNER" + ]; + ProtectKernelModules = true; + RestrictAddressFamilies = [ + "AF_INET" + "AF_INET6" + "AF_UNIX" + "AF_NETLINK" + ]; + }; + + # Sticky, so no member takes another's request; setgid for the group. By tmpfiles, so the + # group can queue before any unit has run. + spoolMode = + if userControlAllows "autoProxy" then + "3770 root ${cfg.userControl.group}" + # userControl.groups only, through ACLs (proxy-suite-acls): the mode keeps them open. + else if derived.userControlAnyAllows "autoProxy" then + "3770 root root" + else if cfg.host.privileged then + "0700 root root" + else + "0700 - -"; mkUnit = description: args: { inherit description; @@ -122,11 +172,16 @@ let serviceConfig = { Type = "oneshot"; ExecStart = "${runner}${args}"; + # A run of tarpits must not hold the lock for good; each probe's verdict is saved as it + # comes, so one cut short keeps what it learned. Far past any honest run's length. + TimeoutStartSec = "2h"; } // stateDirConfig; }; in { + services.proxy-suite.internal.tmpfiles = [ "d ${autoProxySpoolDir} ${spoolMode} -" ]; + services.proxy-suite.internal.services.proxy-suite-autoproxy = mkUnit "proxy-suite - find the exit that reaches each destination, and remember it" ""; @@ -141,6 +196,8 @@ in serviceConfig = { Type = "oneshot"; ExecStart = "${sampler}"; + # Its timer comes every minute. + TimeoutStartSec = "50s"; } // stateDirConfig; }; diff --git a/modules/proxy-suite/config-templates/proxy-inbounds.nix b/modules/proxy-suite/config-templates/proxy-inbounds.nix index 88057dd..c137fa3 100644 --- a/modules/proxy-suite/config-templates/proxy-inbounds.nix +++ b/modules/proxy-suite/config-templates/proxy-inbounds.nix @@ -16,10 +16,19 @@ let localProxyAddress = derived.localProxy.host; - # Checked on the address actually dialed, so a name resolving private is caught too - # (routing's geoip:private sees only literal IPs under AsIs). Explicit either way: - # XRay's own default blocks private for vless/vmess/trojan/shadowsocks only, which - # left socks/http open and ignored blockPrivate = false. + # Checked on the address actually dialed, so a name resolving private is caught too; explicit, + # as XRay's default covers some protocols only. This host's own addresses after it. + # AmneziaWG "proxy" peers: cut off from each other and this host's network, via "direct" too. + awgProxyPeerRules = + let + subnets = lib.concatMap ( + listener: [ listener.subnet ] ++ lib.optional (listener.subnet6 != null) listener.subnet6 + ) (builtins.filter (listener: listener.mode != "lan") derived.proxyInboundsAwg); + in + lib.optional (subnets != [ ]) { + action = "block"; + ip = subnets; + }; directFinalRules = if derived.proxyInboundsCfg.routing.blockPrivate then [ @@ -28,8 +37,38 @@ let ip = [ "geoip:private" ]; } ] + ++ awgProxyPeerRules + ++ hostRules else - [ { action = "allow"; } ]; + # Cloud instance metadata (credentials, IAM tokens) stays this host's alone, as for + # the AmneziaWG listeners: blockPrivate = false opens the LAN, not that. + [ + { + action = "block"; + ip = derived.constants.cloudMetadata.ipv4 ++ derived.constants.cloudMetadata.ipv6; + } + ] + ++ awgProxyPeerRules + ++ hostRules + ++ [ { action = "allow"; } ]; + # XRay's own queries to the resolvers below are routed too, through "direct" when that is + # the via: one on this host stays reachable on its own port. + isIpUpstream = upstream: builtins.match "[0-9.]+|[0-9a-fA-F:]+" upstream.address != null; + resolverRules = lib.unique ( + map + (upstream: { + action = "allow"; + ip = [ upstream.address ]; + port = toString upstream.port; + }) + ( + builtins.filter isIpUpstream [ + proxyCfg.dns.remote + proxyCfg.dns.local + ] + ) + ); + hostRules = resolverRules ++ inboundRules.hostFenceRules; # inbounds.routing.serverSource: a user's connections to this host, from the user's own # address on the dummy interface. inbound_runtime.py makes the runtime users' the same way. @@ -63,22 +102,26 @@ let }; in { - log.loglevel = "warning"; + # Without "access" XRay logs every connection: its user, their address, the site. + log = { + loglevel = "warning"; + } + // lib.optionalAttrs (!(derived.proxyInboundsCfg.accessLog || proxyCfg.autoProxy.enable)) { + access = "none"; + }; dns.servers = [ (mkDnsServer "remote" proxyCfg.dns.remote) (mkDnsServer "local" proxyCfg.dns.local) ]; - # Counters per user, inbound and outbound for proxy-suite-inbound-stats, and who is - # connected right now, from where. A socket rather than loopback, which any local - # user could ask: the start script's setgid directory gives it the group that may - # read the stats. The listeners are appended at start. + # Counters and online users for proxy-suite-inbound-stats, on a root-only socket (asking + # resets counters). The listeners are appended at start. inbounds = [ { tag = "api-in"; protocol = "dokodemo-door"; - listen = "${derived.constants.inboundStatsApiSocket},0660"; + listen = "${derived.constants.inboundStatsApiSocket},0600"; settings = { address = "127.0.0.1"; network = "unix"; @@ -118,6 +161,7 @@ in settings = { }; } ] + ++ inboundRules.exceptionOutbounds ++ selfOutbounds; routing = { diff --git a/modules/proxy-suite/config-templates/xray.nix b/modules/proxy-suite/config-templates/xray.nix index c70a3e6..5b66568 100644 --- a/modules/proxy-suite/config-templates/xray.nix +++ b/modules/proxy-suite/config-templates/xray.nix @@ -73,10 +73,9 @@ let if fakeDnsOnly then { enabled = true; - destOverride = [ "fakedns" ]; - # Fake IPs only live in memory: after a restart an app still holding one gets its - # domain back from TLS/HTTP/QUIC instead of a dead end. Real IPs are left alone; - # the cost is up to 200 ms before a server-speaks-first protocol (SSH, SMTP) starts. + # Fake IPs map back to names; real addresses (DoH, stale caches, a restart's lost fake IPs) + # get theirs sniffed. Costs up to 200 ms before a server-speaks-first protocol starts. + destOverride = [ "fakedns+others" ]; metadataOnly = false; } else @@ -136,12 +135,46 @@ let } // target tag; + # No loopback by any name (sniffed, fake DNS, one resolving there): as the daemon it would + # reach the hops the nft guard keeps from other users. dns.*'s loopback resolver stays. + loopbackDnsPorts = lib.unique ( + map (upstream: upstream.port) ( + builtins.filter + ( + upstream: + lib.hasPrefix "127." upstream.address + || builtins.elem upstream.address [ + "::1" + "localhost" + ] + ) + [ + proxyCfg.dns.local + proxyCfg.dns.remote + ] + ) + ); + directFinalRules = lib.optionals constants.privileged ( + lib.optional (loopbackDnsPorts != [ ]) { + action = "allow"; + ip = derived.proxyInboundsLoopback; + port = lib.concatMapStringsSep "," toString loopbackDnsPorts; + } + ++ [ + { + action = "block"; + ip = derived.proxyInboundsLoopback; + blockDelay = 0; + } + ] + ); + directOutbound = useOutboundRoutingMark: { protocol = "freedom"; tag = "direct"; - settings = { }; + settings = lib.optionalAttrs (directFinalRules != [ ]) { finalRules = directFinalRules; }; } // lib.optionalAttrs useOutboundRoutingMark { streamSettings.sockopt.mark = globalTproxy.proxyMark; @@ -160,8 +193,14 @@ let enableUrlTest ? proxyCfg.selection == "urltest", domainStrategy ? "IPIfNonMatch", enableTunFakeDns ? false, + # A loopback port of this config's own, where dns-out hands the queries XRay's resolver + # does not answer (HTTPS, MX, TXT, SRV...) to dns.remote through the proxy. + remoteDnsBridgePort ? null, }: let + remote = proxyCfg.dns.remote; + # With routing.default = "direct" they keep going where they were sent, as all else does. + remoteDnsBridge = remoteDnsBridgePort != null && proxyCfg.routing.default == "proxy"; tunSniffing = mkSniffing { fakeDnsOnly = enableTunFakeDns; }; tproxyInboundTags = [ "tproxy-in" ] ++ lib.optional proxyCfg.ipv6 "tproxy-in6"; # Every config takes packets for any destination, DNS included. @@ -195,13 +234,64 @@ let qType = "2-27,29-65535"; } ]; + } + # "direct" would forward the query past routing and the kill switch: to the bridge + # instead, which routing takes through the proxy. + // lib.optionalAttrs remoteDnsBridge { + address = "127.0.0.1"; + port = remoteDnsBridgePort; + network = if remote.type == "udp" then "udp" else "tcp"; }; } ]; + remoteDnsBridgeInbound = lib.optional remoteDnsBridge { + tag = "dns-remote-in"; + protocol = "tunnel"; + listen = "127.0.0.1"; + port = remoteDnsBridgePort; + # dns.remote as it is: pure XRay, the only user of this template, refuses "tls" + # (service-assertions.nix), as XRay's DNS has no DoT. + settings = { + inherit (remote) address port; + allowedNetwork = "tcp,udp"; + }; + }; + remoteDnsBridgeRule = lib.optional remoteDnsBridge ( + { + type = "field"; + inboundTag = [ "dns-remote-in" ]; + ruleTag = "dns-remote-bridge"; + } + // target "proxy" + ); + # inbounds.routing.blockPrivate for the names the server's listeners hand mixed-in, which + # this config looks up again (as backend-filter-private-guard.template.jq for sing-box). + inboundsPrivateGuard = + lib.optional + ( + enableMixed + && derived.pureXrayEnabled + && derived.proxyInboundsEnabled + && derived.proxyInboundsNeedLocalProxy + ) + { + type = "field"; + ruleTag = "inbounds-private-guard"; + inboundTag = [ "mixed-in" ]; + # Without blockPrivate, this host's loopback still, as the "direct" via's fence. + ip = + if derived.proxyInboundsCfg.routing.blockPrivate then + [ "geoip:private" ] + else + derived.proxyInboundsLoopback; + outboundTag = "block"; + }; routingRules = - dnsUpstreamRules + remoteDnsBridgeRule + ++ dnsUpstreamRules ++ lib.optional enableTun (dnsHijackRule [ "tun-in" ]) ++ lib.optional enableTProxy (dnsHijackRule tproxyInboundTags) + ++ inboundsPrivateGuard ++ rules.xrayRoutingRules ++ [ (finalRule (if (proxyCfg.routing.default == "proxy") then "proxy" else "direct")) ]; in @@ -249,7 +339,8 @@ let userLevel = 0; }; sniffing = tunSniffing; - }; + } + ++ remoteDnsBridgeInbound; outbounds = dnsOutbounds ++ [ (directOutbound useOutboundRoutingMark) { @@ -294,6 +385,8 @@ in enableMixed = true; enableTProxy = constants.privileged; useOutboundRoutingMark = constants.privileged; + # Pure XRay only, where the hybrid sidecar's DNS bridge ports are free. + remoteDnsBridgePort = constants.xrayDnsBridgePorts.socks; }; tun = mkConfig { @@ -304,6 +397,7 @@ in tunMtu = globalTun.mtu; useOutboundRoutingMark = true; enableTunFakeDns = true; + remoteDnsBridgePort = constants.xrayDnsBridgePorts.tun; }; perAppTun = mkConfig { @@ -314,5 +408,6 @@ in tunMtu = perAppRoutingTun.mtu; useOutboundRoutingMark = true; enableTunFakeDns = true; + remoteDnsBridgePort = constants.xrayDnsBridgePorts.perAppTun; }; } diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index b636ee1..6f367db 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -34,7 +34,8 @@ let proxyInboundsSelfSources proxyInboundsRuntimeEnabled proxyInboundsRuntimeVias - proxyInboundRuntimePorts + proxyInboundsHostPorts + proxyInboundsLoopback ; inherit (rules) zapretDirectRules; }; @@ -99,6 +100,8 @@ let in { spool = derived.constants.runtimeInboundsDir; + # Rootless, the spool is the user's alone: its own .lock serves. + lock = if cfg.host.privileged then derived.constants.runtimeInboundsLock else null; inherit (rt) ports fallbackDests tlsCertificates; vias = derived.proxyInboundsRuntimeVias; defaultVia = derived.proxyInboundsCfg.routing.via; @@ -125,6 +128,7 @@ let shareLinks = derived.proxyInboundsCfg.shareLinks; # Listeners the onion service carries, which get a second set of links to it. onionListeners = map (ib: ib.tag) derived.torOnionInbounds; + inherit (inboundRules) sniffDomainsExcluded; listeners = map ( ib: { diff --git a/modules/proxy-suite/core.nix b/modules/proxy-suite/core.nix index db81508..07623f3 100644 --- a/modules/proxy-suite/core.nix +++ b/modules/proxy-suite/core.nix @@ -10,6 +10,7 @@ { config, + options, lib, pkgs, ... @@ -94,6 +95,24 @@ in inherit (assembly) context; }) + # Settings that work, but less safely than they look. Every host type has assertions; + # warnings, not all of them. + (lib.optionalAttrs (options ? warnings) { + warnings = + let + inbounds = derived.proxyInboundsCfg; + serverSource = inbounds.routing.serverSource; + in + lib.optional + ( + derived.proxyInboundsEnabled + && inbounds.serverPorts != [ ] + && serverSource.ipv4 == null + && serverSource.ipv6 == null + ) + "proxy-suite: inbounds.serverPorts without inbounds.routing.serverSource: inbound users reach those services from this host's own address, which they may trust (a mail server relaying for its own host relays for every user then)"; + }) + (lib.mkIf (cfg.zapret.engine == "zapret-discord-youtube" && cfg.zapret.enable) ( import ./zapret.nix { inherit diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 57f677f..f165288 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -60,6 +60,8 @@ let killSwitchEnabled = cfg.killSwitch.enable && (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalAvailable); + # Fetches that go directly, past it, when the tunnel cannot carry them (killSwitch.directFallbacks). + killSwitchDirectFallbacks = killSwitchEnabled && cfg.killSwitch.directFallbacks; perAppRoutingTun = cfg.perAppRouting.tun; perAppRoutingTproxy = cfg.perAppRouting.tproxy; zapretCfg = cfg.zapret; @@ -172,7 +174,8 @@ let whitelistBypassCfg.joiners.${tag} // { inherit tag; - port = 18700 + i; + # Past the AmneziaWG listeners' loopback inbounds (awgInboundBasePort, 18700 up). + port = 18750 + i; } ) (builtins.attrNames whitelistBypassCfg.joiners) ); @@ -213,6 +216,28 @@ let awgRuntimeEnabled = cfg.amneziaWg.enable && cfg.amneziaWg.runtime.enable; awgRuntimeGlobal = awgRuntimeEnabled && cfg.host.privileged; awgRuntimeOutbounds = awgRuntimeEnabled && proxyEnabled && cfg.host.serviceManager != "supervisor"; + + # The loopback hops the backends dial (tunnels, Tor, joiners, OpenSSH -D, the sidecar): + # on a root host only proxy-suite-daemon and root reach them (constants.daemonMetadataGuard). + hopPorts = lib.unique ( + lib.optionals warpOutboundEnabled ( + lib.concatMap (d: [ + d.tunnelPort + d.directPort + ]) warpDevices + ) + ++ lib.concatMap (ob: [ + ob.tunnelPort + ob.directPort + ]) awgTunnelOutbounds + ++ lib.optionals awgRuntimeOutbounds ( + lib.genList (i: constants.awgRuntimeTunnelBasePort + i) constants.awgRuntimeTunnelSlots + ) + ++ lib.optional torOutboundEnabled torCfg.socksPort + ++ map (j: j.port) whitelistBypassJoiners + ++ lib.optional (sshProxyOutboundEnabled && !sshProxyNativeOutbound) sshProxyCfg.listener.port + ++ lib.optionals hybridEnabled (builtins.attrValues constants.xraySidecarPorts) + ); # 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. @@ -380,13 +405,16 @@ let # Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay). proxyInboundsResolveInSingBox = !pureXrayEnabled && !builtins.elem "direct" proxyInboundsVias; - # Even when XRay resolves (a direct listener), it hands sing-box the name, which sing-box - # looks up again: guard there too. - proxyInboundsGuardPrivate = - proxyInboundsEnabled - && proxyInboundsCfg.routing.blockPrivate - && proxyInboundsNeedLocalProxy - && !pureXrayEnabled; + # sing-box looks a name up again even when XRay resolved it: guard there too, the private + # ranges with blockPrivate, else this host's loopback still. + proxyInboundsGuardPrivate = proxyInboundsEnabled && proxyInboundsNeedLocalProxy && !pureXrayEnabled; + # This host's loopback and unspecified addresses (connecting to either reaches it). + proxyInboundsLoopback = [ + "127.0.0.0/8" + "::1/128" + "0.0.0.0/32" + "::/128" + ]; # The guard's resolved addresses are dialed in its order, so it follows WARP's preference. proxyInboundsGuardStrategy = if proxyCfg.dns.strategy == null && warpCfg.enable && warpCfg.asOutbound != null then @@ -491,6 +519,61 @@ let to = builtins.elemAt bounds 1; } ) (builtins.filter builtins.isString proxyInboundRuntimePorts); + # The ports of this host its inbounds' clients may reach on its own addresses: the ones + # they dial and the public ones (rules/proxy-inbounds.nix fences the rest). + proxyInboundsHostPorts = lib.unique ( + map (ib: if ib.listener.sharePort != null then ib.listener.sharePort else ib.listener.port) ( + # AmneziaWG is UDP to the interface, never relayed through XRay. + builtins.filter (ib: ib.listener.type != "amneziawg") proxyInbounds + ) + ++ lib.optionals proxyInboundsCfg.subscriptions.enable [ + 80 + 443 + ] + ++ proxyInboundsCfg.serverPorts + ++ proxyInboundRuntimePorts + ); + # Every other port, as ranges { from, to }, for the backends' guard: their rules cannot + # say "all but these". + proxyInboundsHostClosedPorts = + let + open = builtins.sort (a: b: a.from < b.from) ( + map ( + p: + if builtins.isInt p then + { + from = p; + to = p; + } + else + let + bounds = map lib.toInt (lib.splitString "-" p); + in + { + from = builtins.elemAt bounds 0; + to = builtins.elemAt bounds 1; + } + ) proxyInboundsHostPorts + ); + step = acc: r: { + next = lib.max acc.next (r.to + 1); + gaps = + acc.gaps + ++ lib.optional (r.from > acc.next) { + from = acc.next; + to = r.from - 1; + }; + }; + swept = builtins.foldl' step { + next = 1; + gaps = [ ]; + } open; + in + swept.gaps + ++ lib.optional (swept.next <= 65535) { + from = swept.next; + to = 65535; + }; # A raw-JSON listener could serve anything, so open both protocols for it. proxyInboundFirewallUdpPorts = lib.unique ( map (ib: ib.listener.port) ( @@ -590,10 +673,36 @@ let builtins.attrNames userControlCfg.groups ); managerFlag = lib.optionalString (cfg.host.serviceManager == "systemd-user") " --user"; + resolvedUpstreams = "/run/systemd/resolve/resolv.conf"; constants = { inherit stateDir runtimeDir; inherit (cfg.host) privileged serviceManager; + # proxy-suite's tables that are up, included by a NixOS firewall's ruleset (hosts/nixos.nix) + # so a reload that flushes it puts them back in the same transaction. + persistedNftDir = "${runtimeDir}/proxy-suite-nft"; + # A bit TProxy's table sets on forwarded packets while it is up, which the kill switch's + # forward chain lets past (nftables.nix): no ip rule or other mark here uses it. + killSwitchForwardMark = 16777216; # 0x1000000 + + # Cloud instance metadata endpoints (AWS and most others, ECS, Tencent, Alibaba, Azure's + # WireServer, OCI; IPv6 for AWS, GCP, OCI): this host's alone, not its daemons'. + cloudMetadata = { + ipv4 = [ + "169.254.169.254" + "169.254.170.2" + "169.254.0.23" + "100.100.100.200" + "168.63.129.16" + "192.0.0.192" + ]; + ipv6 = [ + "fd00:ec2::254" + "fd20:ce::254" + "fd00:c1::a9fe:a9fe" + ]; + }; + # Daemons (sing-box, XRay, the WARP tunnel, OpenSSH, tg-ws-proxy, wgcf) run as this # user. Its group is not the userControl group: backend configs hold credentials. Start # scripts still read secrets and program routing as root, then exec the daemon through @@ -601,6 +710,19 @@ let # On a rootless host everything already runs as the user: no service user, and # nothing to hand files over to it. serviceUser = "proxy-suite-daemon"; + # Tor's own user, apart from the other daemons and their credentials. + torUser = "proxy-suite-tor"; + # Whose traffic is proxy-suite's own, kept out of TUN and TProxy and past the kill switch. + # Not Tor's through the local proxy: whatever else it dialled would leave by the uplink. + ownTrafficUsers = [ + "proxy-suite-daemon" + ] + ++ lib.optional ( + cfg.host.privileged && torCfg.enable && torCfg.upstream != "proxy" + ) "proxy-suite-tor"; + ownTrafficUsersNft = "{ ${ + lib.concatMapStringsSep ", " (u: ''"${u}"'') constants.ownTrafficUsers + } }"; # Shell text that only matters when the services run as root. ifPrivileged = lib.optionalString cfg.host.privileged; # The commands scripts manage units and read their logs with: the units live in the @@ -616,6 +738,76 @@ let "${pkgs.util-linux}/bin/setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon --clear-groups" + " --inh-caps=-all${keep} --ambient-caps=-all${keep} --bounding-set=-all${keep} --no-new-privs --" ); + # A per-app unit refuses to start under a global mode carrying the same traffic (not + # Conflicts=, which would let perApp members stop the global one). `patterns`: systemctl's. + refuseUnderGlobal = + pkgs: patterns: + "+${pkgs.writeShellScript "proxy-suite-per-app" '' + set -uo pipefail + (( $# )) || exit 0 + active=$(${cfg.host.systemctl}${managerFlag} list-units --plain --no-legend --state=active,activating,reloading "$@" \ + | ${pkgs.gawk}/bin/awk 'NR == 1 { print $1 }') + if [[ -n $active ]]; then + echo "proxy-suite: $active carries this traffic already: per-app routing stays down" >&2 + exit 1 + fi + ''} ${lib.concatStringsSep " " patterns}"; + # Cloud metadata is no destination for proxy-suite's daemons (check_server only checks + # literal addresses); lookups pass, GCP's resolver being one. "-": no nf_tables, no guard. + daemonMetadataGuard = + pkgs: + if cfg.host.privileged then + "-+${pkgs.nftables}/bin/nft -f ${pkgs.writeText "proxy-suite-routing" '' + table inet proxy_suite_daemon_guard + delete table inet proxy_suite_daemon_guard + table inet proxy_suite_daemon_guard { + chain output { + type filter hook output priority filter; policy accept; + ${lib.optionalString (hopPorts != [ ]) '' + # The hops: new connections only (no reply carries their port as its + # destination), from proxy-suite-daemon or root alone. + oifname "lo" tcp dport { ${ + lib.concatMapStringsSep ", " toString hopPorts + } } ct state new meta skuid != { 0, "proxy-suite-daemon" } reject with tcp reset + ''} + meta skuid ${constants.ownTrafficUsersNft} ip daddr { ${lib.concatStringsSep ", " constants.cloudMetadata.ipv4} } th dport != 53 reject with icmpx admin-prohibited + meta skuid ${constants.ownTrafficUsersNft} ip6 daddr { ${lib.concatStringsSep ", " constants.cloudMetadata.ipv6} } th dport != 53 reject with icmpx admin-prohibited + } + } + ''}" + else + null; + # The login of the loopback hops that take one: drawn once per boot by whatever starts + # first, so a restarted tunnel keeps the one the backend dials with. + hopUser = "hop"; + hopLoginFile = "${runtimeDir}/proxy-suite-hop-login"; + ensureHopLogin = + pkgs: + pkgs.writeShellScript "proxy-suite-hop-login" '' + set -euo pipefail + f=${lib.escapeShellArg "${runtimeDir}/proxy-suite-hop-login"} + [ -s "$f" ] && exit 0 + ${pkgs.coreutils}/bin/mkdir -p "$(${pkgs.coreutils}/bin/dirname "$f")" + umask 077 + tmp=$(${pkgs.coreutils}/bin/mktemp "$f.XXXXXX") + ${pkgs.coreutils}/bin/od -An -tx1 -N16 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n' > "$tmp" + ${lib.optionalString cfg.host.privileged '' + ${pkgs.coreutils}/bin/chgrp proxy-suite-daemon "$tmp" + ${pkgs.coreutils}/bin/chmod 0640 "$tmp" + ''} + # A hard link fails where the name is taken: the first to get there wins, the rest + # read what it drew. + ${pkgs.coreutils}/bin/ln "$tmp" "$f" 2>/dev/null || true + ${pkgs.coreutils}/bin/rm -f "$tmp" + ''; + # One at a time: a unit this host does not have would fail the rest of one call. + stopPerAppUnits = + pkgs: patterns: + "-+${pkgs.writeShellScript "proxy-suite-per-app" '' + for unit in "$@"; do + ${cfg.host.systemctl}${managerFlag} stop -- "$unit" 2>/dev/null || true + done + ''} ${lib.concatStringsSep " " patterns}"; # The same for a unit that needs no root at all; "+" ExecStartPre/ExecStopPost # commands still run privileged. unprivilegedServiceConfig = @@ -638,13 +830,48 @@ let RestrictSUIDSGID = true; LockPersonality = true; }; + # A direct fetch's lookups past the kill switch, which rejects resolved's and nscd's own + # queries with no tunnel up: glibc asks resolved's upstreams itself, if it lists any. + ownLookups = + pkgs: + pkgs.writeShellScript "proxy-suite-own-lookups" '' + if ${pkgs.gnugrep}/bin/grep -qs '^nameserver' ${resolvedUpstreams}; then + if [ -S /run/nscd/socket ]; then ${pkgs.util-linux}/bin/mount --bind /dev/null /run/nscd/socket || true; fi + ${pkgs.util-linux}/bin/mount --bind ${resolvedUpstreams} /etc/resolv.conf || true + fi + exec "$@" + ''; + killSwitchOwnLookups = + pkgs: + let + copy = "${runtimeDir}/proxy-suite-own-lookups.conf"; + in + lib.optionalAttrs killSwitchEnabled { + ExecStartPre = [ + "+${pkgs.writeShellScript "proxy-suite-own-lookups" '' + if ${pkgs.gnugrep}/bin/grep -qs '^nameserver' ${resolvedUpstreams}; then + ${pkgs.coreutils}/bin/install -m 0644 ${resolvedUpstreams} ${copy}.$$ && ${pkgs.coreutils}/bin/mv -f ${copy}.$$ ${copy} + else + ${pkgs.coreutils}/bin/rm -f ${copy} + fi + ''}" + ]; + BindReadOnlyPaths = [ "-${copy}:/etc/resolv.conf" ]; + InaccessiblePaths = [ "-/run/nscd" ]; + }; # For a unit that stays root but works in a directory the userControl group writes to: # the file system read-only but for its own State-, Runtime- and private Tmp # directories, so a symlink the group plants there leads root's writes nowhere else. + # (No ProtectKernelModules: preStarts modprobe.) rootInSharedDirConfig = lib.optionalAttrs cfg.host.privileged { ProtectSystem = "strict"; ProtectHome = true; PrivateTmp = true; + PrivateDevices = true; + ProtectKernelTunables = true; + ProtectKernelLogs = true; + ProtectControlGroups = true; + ProtectClock = true; }; # POSIX ACLs for the groups in userControl.groups, which cannot own a file the way # userControl.group does. Shell text, for root. @@ -700,7 +927,12 @@ let zapret2 = 300; }; + # Root's alone to write: state.json, and rules/ for sing-box. The autoProxy scope's + # group reads it; what members ask of the prober goes to the spool instead. autoProxyStateDir = "${stateDir}/autoproxy"; + # `proxy-ctl proxy auto learn|forget|relearn|clear`: a file per request, in a sticky + # directory, so no member takes away or rewrites another's. Root reads and removes them. + autoProxySpoolDir = "${stateDir}/autoproxy-requests"; # Runtime outbound control. The spool dirs hold one proxy URL per file and are # group-writable when userControl is on, so proxy-ctl edits them without sudo; @@ -710,6 +942,8 @@ let runtimeSubscriptionsDir = "${stateDir}/subscriptions.d"; # inbounds.runtime: users/.json and listeners/.json (scripts/inbound_runtime.py). runtimeInboundsDir = "${stateDir}/inbounds.d"; + # Its lock, made by root outside the spool, where no member can swap it. + runtimeInboundsLock = "${runtimeDir}/proxy-suite-inbounds-runtime.lock"; # 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, @@ -800,6 +1034,12 @@ let ipv6 = "fd66:21::${lib.toLower (lib.toHexString (slot + 2))}"; }; perAppTunClashApiPort = 19180; + # The DNS forwarders of per-app TUN and TProxy apps (proxy-suite-per-app--dns): the + # route's at the base, pin slot n's at base + 1 + n; they ask perAppDnsUpstream with its mark. + perAppTproxyDnsBasePort = 19200; + perAppTunDnsBasePort = 19220; + # TEST-NET-1: no real resolver, and in none of the ranges the routes leave alone. + perAppDnsUpstream = "192.0.2.53"; # 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. @@ -878,6 +1118,7 @@ in globalTproxy tproxyLanSysctl killSwitchEnabled + killSwitchDirectFallbacks ruleSets ruleSetsEnabled perAppRoutingTun @@ -949,6 +1190,10 @@ in proxyInboundsServerSource proxyInboundsSelfSources proxyInboundsGuardPrivate + proxyInboundsLoopback + hopPorts + proxyInboundsHostPorts + proxyInboundsHostClosedPorts proxyInboundsGuardStrategy proxyInboundViaTags proxyInboundViaOutbounds diff --git a/modules/proxy-suite/hosts/common.nix b/modules/proxy-suite/hosts/common.nix index db54c3f..ecec71a 100644 --- a/modules/proxy-suite/hosts/common.nix +++ b/modules/proxy-suite/hosts/common.nix @@ -27,14 +27,19 @@ rec { }; # One system user per daemon, each in a group of its own, plus the userControl group. - systemUsersAndGroups = cfg: { - users.users = lib.genAttrs cfg.internal.systemUsers (name: { - isSystemUser = true; - group = name; - description = "proxy-suite daemons"; - }); - users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { }); - }; + systemUsersAndGroups = + cfg: + let + users = lib.unique cfg.internal.systemUsers; + in + { + users.users = lib.genAttrs users (name: { + isSystemUser = true; + group = name; + description = "proxy-suite daemons"; + }); + users.groups = lib.genAttrs (users ++ cfg.internal.groups) (_: { }); + }; firewallPortForward = internal: { networking.firewall = { @@ -52,11 +57,12 @@ rec { host, internal, hostPath ? null, + withSystemd ? true, }: let units = import ./user-units.nix ( { - inherit lib pkgs; + inherit lib pkgs withSystemd; inherit (host) runtimeDir; stateDir = builtins.dirOf host.stateDir; } diff --git a/modules/proxy-suite/hosts/nix-on-droid.nix b/modules/proxy-suite/hosts/nix-on-droid.nix index 22a7e40..8e1d624 100644 --- a/modules/proxy-suite/hosts/nix-on-droid.nix +++ b/modules/proxy-suite/hosts/nix-on-droid.nix @@ -23,6 +23,7 @@ let internal ; hostPath = "${home}/.nix-profile/bin"; + withSystemd = false; }; supervisorDir = "${host.runtimeDir}/proxy-suite-supervisor"; @@ -76,6 +77,11 @@ in firewallPackage = null; resolvconfPackage = null; }; + # A phone's storage is tight: proxy-ctl falls back to less and plain curl. + services.proxy-suite.tools = { + lnav.enable = lib.mkDefault false; + curlImpersonate.enable = lib.mkDefault false; + }; # An app may not join netlink's route groups: without this sing-box fails to start. services.proxy-suite.proxy.singBox.package = lib.mkDefault ( import ../../../pkgs/sing-box-rootless-netlink.nix { inherit (proxySuiteUpstream) sing-box; } diff --git a/modules/proxy-suite/hosts/nixos.nix b/modules/proxy-suite/hosts/nixos.nix index b1e8a8c..e770b02 100644 --- a/modules/proxy-suite/hosts/nixos.nix +++ b/modules/proxy-suite/hosts/nixos.nix @@ -3,6 +3,7 @@ config, options, lib, + pkgs, ... }: @@ -42,6 +43,11 @@ in ) ([ firewall ] ++ lib.attrValues firewall.interfaces) ); resolvconfPackage = config.networking.resolvconf.package; + # ntpd-rs runs as a dynamic user, which has no name until it starts. + timeSyncUsers = + lib.optional config.services.timesyncd.enable "systemd-timesync" + ++ lib.optional config.services.chrony.enable "chrony" + ++ lib.optional (config.services.ntp.enable || config.services.openntpd.enable) "ntp"; }; # NixOS's place for helper functions; set even while disabled, so a config can # refer to it unconditionally. @@ -57,8 +63,40 @@ in security.polkit.enable = lib.mkIf cfg.internal.polkit.enable true; security.polkit.extraConfig = forwardWith lib.mkAfter internal.polkit.rules; + # polkitd reads actions from the system profile's share/polkit-1/actions. + environment.systemPackages = lib.mkIf (cfg.internal.polkit.actions != { }) [ + (pkgs.linkFarm "proxy-suite-polkit-actions" ( + lib.mapAttrsToList (name: path: { + name = "share/polkit-1/actions/${name}"; + inherit path; + }) cfg.internal.polkit.actions + )) + ]; networking.nftables.enable = lib.mkIf cfg.internal.nftables (lib.mkDefault true); + # proxy-suite's tables that are up, put back in the firewall's own load, whose flush would + # otherwise drop them (constants.persistedNftDir). An empty glob is no error. + networking.nftables.ruleset = lib.mkIf config.networking.nftables.enable ( + lib.mkAfter '' + include "${cfg.host.runtimeDir}/proxy-suite-nft/*.nft" + '' + ); + # A persisted table that no longer loads (a user it names is gone, its store path + # collected) would fail the whole load: dropped until its unit writes it again. + systemd.services.nftables.serviceConfig = lib.mkIf config.networking.nftables.enable ( + let + prune = pkgs.writeShellScript "proxy-suite-nft-prune" '' + for f in ${cfg.host.runtimeDir}/proxy-suite-nft/*.nft; do + [ -e "$f" ] || continue + ${pkgs.nftables}/bin/nft -c -f "$f" > /dev/null 2>&1 || ${pkgs.coreutils}/bin/rm -f -- "$f" + done + ''; + in + { + ExecStart = lib.mkBefore [ prune ]; + ExecReload = lib.mkBefore [ prune ]; + } + ); networking.nftables.tables = lib.mapAttrs (_: content: { family = "inet"; inherit content; @@ -73,6 +111,13 @@ in trustedInterfaces = forward internal.firewall.trustedInterfaces; }; + # networkd drops foreign ip rules and unreachable routes (TProxy's and AmneziaWG's IPv6 + # refusal) in every table whenever it reconfigures a link. + systemd.network.config.networkConfig = lib.mkIf config.systemd.network.enable { + ManageForeignRoutingPolicyRules = lib.mkDefault false; + ManageForeignRoutes = lib.mkDefault false; + }; + boot.extraModulePackages = forward internal.kernelModulePackages; boot.kernel.sysctl = lib.mapAttrs (_: lib.mkDefault) cfg.internal.sysctl; @@ -88,6 +133,20 @@ in || config.networking.nftables.enable; message = "proxy-suite: proxy.tproxy.lanInterfaces needs the nftables firewall (networking.nftables.enable); the iptables one drops the gateway clients' diverted traffic"; } + # The kill switch lets that user's traffic past, all of it: a login user's browser + # and apps too, whenever no tunnel is up. + ( + let + user = cfg.sshProxy.serviceUser; + declared = config.users.users.${user} or null; + in + { + assertion = + !(cfg.sshProxy.enable && user != null && user != "proxy-suite-daemon" && declared != null) + || !declared.isNormalUser; + message = "proxy-suite: sshProxy.serviceUser = \"${toString user}\" is a login user, whose traffic would all get past the kill switch; use a system user of its own (isSystemUser = true), or the default"; + } + ) ]; } ] diff --git a/modules/proxy-suite/hosts/system-manager.nix b/modules/proxy-suite/hosts/system-manager.nix index 12d54a9..e83a977 100644 --- a/modules/proxy-suite/hosts/system-manager.nix +++ b/modules/proxy-suite/hosts/system-manager.nix @@ -97,6 +97,11 @@ in (lib.mkIf cfg.internal.polkit.enable { "polkit-1/rules.d/50-proxy-suite.rules".text = cfg.internal.polkit.rules; }) + # Read from /etc by polkit 126 and later. An older one never finds the action, and + # its pkexec asks for the password every time instead. + (lib.mapAttrs' ( + name: path: lib.nameValuePair "polkit-1/actions/${name}" { source = path; } + ) cfg.internal.polkit.actions) ]; } diff --git a/modules/proxy-suite/hosts/user-units.nix b/modules/proxy-suite/hosts/user-units.nix index ec89f3f..f151875 100644 --- a/modules/proxy-suite/hosts/user-units.nix +++ b/modules/proxy-suite/hosts/user-units.nix @@ -9,6 +9,8 @@ runtimeDir, stateDir, hostPath ? null, + # Off under proxy-suitectl: the scripts call it by path, and nothing needs systemd's tools. + withSystemd ? true, }: let @@ -71,13 +73,15 @@ let iniSection = section: lib.mapAttrs (_: iniValue) (lib.filterAttrs (_: v: v != null) section); # As NixOS's service `path` default. - defaultPath = with pkgs; [ - coreutils - findutils - gnugrep - gnused - systemd - ]; + defaultPath = + with pkgs; + [ + coreutils + findutils + gnugrep + gnused + ] + ++ lib.optional withSystemd systemd; # As NixOS: "@" is not allowed in a store path name. jobScript = diff --git a/modules/proxy-suite/nftables.nix b/modules/proxy-suite/nftables.nix index 07f1c0e..302dc28 100644 --- a/modules/proxy-suite/nftables.nix +++ b/modules/proxy-suite/nftables.nix @@ -8,6 +8,7 @@ let inherit (import ./derived.nix { inherit lib cfg; }) constants + killSwitchEnabled awgGlobalProfiles awgGlobalAvailable awgRuntimeGlobal @@ -32,9 +33,9 @@ let meta mark { ${lib.concatMapStringsSep ", " toString perAppViaMarks} } return ''; - # Shared across all three nftables rule files that do IP routing. + # Shared across the rule files; redefine, as the firewall's ruleset includes several at once. reservedIpBlock = '' - define RESERVED_IP = { + redefine RESERVED_IP = { 10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, @@ -45,7 +46,7 @@ let 240.0.0.0/4, 255.255.255.255/32 } - define RESERVED_IP6 = { + redefine RESERVED_IP6 = { ::/128, ::1/128, ::ffff:0:0/96, @@ -86,7 +87,16 @@ let # Devices using this host as their gateway, past the destinations nobody diverts. tproxyLanLines = lib.optionalString (globalTproxy.lanInterfaces != [ ]) ( mkTproxyLines "iifname ${lanInterfaceSet} " " meta mark set ${toString globalTproxy.fwmark}" + + tproxyIPv6RefuseLine "iifname ${lanInterfaceSet} " ); + # Without proxy.ipv6 nothing takes IPv6: marked all the same, it meets the unreachable + # route mkTproxyRoutingUp puts in the table, and apps fall back to IPv4; on-link prefixes + # still go by the main table. + tproxyIPv6RefuseLine = + prefix: + lib.optionalString (!proxyCfg.ipv6) '' + ${prefix}meta nfproto ipv6 meta mark set ${toString globalTproxy.fwmark} + ''; perAppTproxyLocalSubnetLines = mkLocalSubnetLines perAppTproxy.localSubnets; # Without ipv6, IPv6 packets are left alone, as if the table were still `ip`. @@ -94,11 +104,27 @@ 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. - 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}"} + # `mark` before the tproxy: with no listener tproxy ends the rule, and an unmarked gateway + # client's packet would be forwarded out direct. + mkTproxyLinesTo = port: prefix: mark: '' + ${prefix}meta nfproto ipv4 meta l4proto { tcp, udp }${mark} tproxy ip to 127.0.0.1:${toString port} + ${lib.optionalString proxyCfg.ipv6 "${prefix}meta nfproto ipv6 meta l4proto { tcp, udp }${mark} tproxy ip6 to [::1]:${toString port}"} ''; mkTproxyLines = mkTproxyLinesTo globalTproxy.port; + # The families a TProxy mark carries into the proxy. + tproxyMarkedFamilies = lib.optionalString (!proxyCfg.ipv6) "meta nfproto ipv4 "; + + # A marked packet leaving by another interface: its ip rule is gone (`ip rule flush`, a + # VPN tool) and the main table sends it out the uplink, past the kill switch, which lets + # marked packets by. `match`: TProxy without proxy.ipv6 sends on-link IPv6 out marked. + mkMisroutedGuard = mark: interfaces: match: '' + chain misrouted { + type filter hook postrouting priority filter; policy accept; + ${match}meta mark ${toString mark} oifname != { ${ + lib.concatMapStringsSep ", " (i: ''"${i}"'') interfaces + } } drop + } + ''; nftablesRulesFile = pkgs.writeText "proxy-suite-routing" '' ${reservedIpBlock} @@ -112,12 +138,11 @@ let fib daddr type local return ${tproxyLocalSubnetLines} ${tproxyLanLines} - # Packets re-entering via loopback after output marking should not - # be skipped just because the host has an RFC1918 source address. - iifname != "lo" ip saddr $RESERVED_IP return - iifname != "lo" ip6 saddr $RESERVED_IP6 return - ${mkTproxyLines "" " meta mark set ${toString globalTproxy.fwmark}"} + # Past lanInterfaces, only what the output chain below marked: a neighbour + # routing through this host is never handed the proxy's exits. + ${mkTproxyLines "meta mark ${toString globalTproxy.fwmark} " ""} } + ${killSwitchForwardTag} chain output { type route hook output priority mangle; policy accept; ${reservedLines} @@ -126,12 +151,43 @@ let # Replies to connections from outside, and proxy-suite's own daemons (the # inbound XRay dials unmarked, lacking CAP_NET_ADMIN), leave as they are. ct direction reply return - meta skuid "${serviceUser}" return + meta skuid ${constants.ownTrafficUsersNft} return ${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} + ${tproxyIPv6RefuseLine ""} } + ${mkMisroutedGuard globalTproxy.fwmark [ "lo" ] tproxyMarkedFamilies} } ''; + # A marked app's lookup of a loopback resolver would be answered outside the route: the + # forwarder on `dnsPort` asks again through it. `everywhere`: every lookup (TProxy's case). + mkDnsRedirect = + { + mark, + dnsPort, + everywhere ? false, + }: + let + lookup = "meta mark ${toString mark} meta l4proto { tcp, udp } th dport 53"; + to = "redirect to :${toString dnsPort}"; + in + if everywhere then + '' + chain dns_redirect { + type nat hook output priority dstnat; policy accept; + ${lookup} ip daddr != ${constants.perAppDnsUpstream} ${to} + ${lookup} meta nfproto ipv6 ${to} + } + '' + else + '' + chain dns_redirect { + type nat hook output priority dstnat; policy accept; + ${lookup} ip daddr 127.0.0.0/8 ${to} + ${lookup} ip6 daddr ::1 ${to} + } + ''; + # Per-app TProxy, and a pin slot of it (perAppRouting.via): `mark` on the app's packets, which # the backend takes on `port`. mkPerAppTproxyRules = @@ -139,10 +195,15 @@ let table, mark, port, + dnsPort, }: '' ${reservedIpBlock} table inet ${table} { + # The per-user cgroup mark rules are added here at runtime (user-rules.nix). + # Defined first: a jump only resolves to a chain nft has already read. + chain app_mark { + } chain prerouting { type filter hook prerouting priority mangle; policy accept; ${reservedLines} @@ -160,13 +221,23 @@ let 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 + # The DNS forwarder's own queries carry the mark on the socket alone: the + # connection takes it too, for prerouting to restore. + meta mark ${toString mark} ct mark set ${toString mark} return + # A lookup goes through the route wherever its resolver is (dns_redirect). + meta l4proto { tcp, udp } th dport 53 goto app_mark + ${reservedLines} + ${perAppTproxyLocalSubnetLines} + goto app_mark } + ${mkDnsRedirect { + inherit mark dnsPort; + everywhere = true; + }} + ${mkMisroutedGuard mark [ "lo" ] tproxyMarkedFamilies} } ''; @@ -174,6 +245,7 @@ let table = "proxy_suite_per_app_tproxy"; mark = perAppTproxy.fwmark; inherit (globalTproxy) port; + dnsPort = constants.perAppTproxyDnsBasePort; }); perAppPinTproxyRulesFiles = lib.genList ( slot: @@ -181,6 +253,7 @@ let table = "proxy_suite_per_app_via_tproxy_${toString slot}"; mark = constants.perAppPinTproxyFwmarkBase + slot; port = constants.perAppPinTproxyPortBase + slot; + dnsPort = constants.perAppTproxyDnsBasePort + 1 + slot; }) ) (if perAppPinTproxy then perAppPinSlots else 0); @@ -196,31 +269,79 @@ let ++ lib.optional tgWsProxyBypassEnabled tgWsProxyCfg.fwmark ++ lib.optional awgGlobalAvailable constants.awgGlobalFwmark ++ perAppViaMarks - ++ lib.optionals perAppPinTproxy ( - lib.genList (slot: constants.perAppPinTproxyFwmarkBase + slot) perAppPinSlots - ) + ++ killSwitchPinTproxyMarks ++ lib.optionals perAppPinTun ( lib.genList (slot: constants.perAppPinTunFwmarkBase + slot) perAppPinSlots + ) + # zapret's fakes and split segments carry its desync marks; rejected, split connections stall. + ++ lib.optionals cfg.zapret.enable [ + 1073741824 # 0x40000000, the global instance's (zapret2's, and zapret v1's default) + 536870912 # 0x20000000 + ] + ++ lib.optionals zapretApp.enable [ + 134217728 # 0x8000000, the per-app instance's (zapret/packages.nix, zapret2.nix) + 67108864 # 0x4000000 + ]; + killSwitchPinTproxyMarks = lib.optionals perAppPinTproxy ( + lib.genList (slot: constants.perAppPinTproxyFwmarkBase + slot) perAppPinSlots ); + # TProxy's marks carry only the families it takes into the proxy; without proxy.ipv6 a + # marked IPv6 packet leaving at all is on-link or lost its ip rule. + killSwitchTproxyMarks = [ + globalTproxy.fwmark + ] + ++ lib.optional perAppTproxy.enable perAppTproxy.fwmark + ++ killSwitchPinTproxyMarks; + killSwitchMarkLines = + let + set = marks: "{ ${lib.concatMapStringsSep ", " toString (lib.unique marks)} }"; + in + if proxyCfg.ipv6 then + "meta mark ${set killSwitchMarks} accept" + else + '' + meta mark ${set (lib.subtractLists killSwitchTproxyMarks killSwitchMarks)} accept + meta nfproto ipv4 meta mark ${set killSwitchTproxyMarks} accept + ''; awgGlobalInterfaces = lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles ++ lib.optional awgRuntimeGlobal cfg.amneziaWg.runtime.interfaceName; globalTunEnabled = proxyCfg.enable && proxyCfg.tun.enable; + # Forwarded traffic (containers, VMs) follows the routes TUN and a global AmneziaWG profile + # take over, and leaves by the uplink once they go: held to the LAN until one is back. + # TProxy diverts none of it, so while TProxy is up (its table tags it) it passes. + killSwitchForward = globalTunEnabled || awgGlobalAvailable; + killSwitchForwardTag = lib.optionalString (killSwitchEnabled && killSwitchForward) '' + chain forward { + type filter hook forward priority mangle; policy accept; + ${ + lib.optionalString (globalTproxy.lanInterfaces != [ ]) "iifname != ${lanInterfaceSet} " + }meta mark set meta mark or ${toString constants.killSwitchForwardMark} + } + ''; + killSwitchTunnelInterfaces = + lib.optional globalTunEnabled proxyCfg.tun.interface + ++ lib.optionals awgGlobalAvailable awgGlobalInterfaces; killSwitchAllowLines = '' ip daddr $RESERVED_IP accept ip6 daddr $RESERVED_IP6 accept ${lib.concatMapStrings (cidr: '' ${ipFamily cidr} daddr ${cidr} accept - '') globalTproxy.localSubnets} + '') cfg.killSwitch.allowedSubnets} ct direction reply accept ''; killSwitchRulesFile = pkgs.writeText "proxy-suite-routing" '' ${reservedIpBlock} table inet proxy_suite_killswitch { + # The time daemons' uids, added by the up script: nft refuses a rule naming a user + # that does not exist. + set time_sync_uids { + type uid + } chain output { type filter hook output priority filter; policy accept; oifname "lo" accept - meta skuid "${serviceUser}" accept + meta skuid ${constants.ownTrafficUsersNft} accept ${lib.optionalString globalTunEnabled '' oifname "${proxyCfg.tun.interface}" accept # sing-box's auto_redirect hands DNS to the TUN by rewriting it to the TUN's peer, @@ -235,20 +356,34 @@ let ${lib.optionalString ( cfg.sshProxy.enable && sshProxyUser != null && sshProxyUser != serviceUser ) ''meta skuid "${sshProxyUser}" accept''} - meta mark { ${lib.concatMapStringsSep ", " toString (lib.unique killSwitchMarks)} } accept + ${killSwitchMarkLines} # A lookup the proxy did not take would name every site to the LAN resolver. meta l4proto { tcp, udp } th dport 53 reject with icmpx admin-prohibited ${killSwitchAllowLines} - # DHCP keeps the uplink, NTP the clock that TLS depends on. - udp dport { 67, 68, 123 } accept + # DHCP keeps the uplink, NTP the clock TLS needs: from privileged ports or time daemons + # only, so no app's port-123 request learns the uplink address. + meta nfproto ipv4 udp sport 68 udp dport 67 accept + meta nfproto ipv6 udp sport 546 udp dport 547 accept + udp sport 123 udp dport 123 accept + meta skuid @time_sync_uids udp dport 123 accept reject with icmpx admin-prohibited } - ${lib.optionalString (globalTproxy.lanInterfaces != [ ]) '' - # Gateway clients: what TProxy does not divert is forwarded, to the LAN only. + ${lib.optionalString (killSwitchForward || globalTproxy.lanInterfaces != [ ]) '' + # Gateway clients: what TProxy does not divert goes to the LAN only. Containers and VMs + # too while no TUN or AmneziaWG tunnel, nor TProxy, is up. chain forward { type filter hook forward priority filter; policy accept; + ${lib.optionalString killSwitchForward '' + oifname { ${lib.concatMapStringsSep ", " (i: ''"${i}"'') killSwitchTunnelInterfaces} } accept + ${lib.optionalString globalTproxy.enable "meta mark and ${toString constants.killSwitchForwardMark} != 0 accept"} + ''} ${killSwitchAllowLines} - iifname ${lanInterfaceSet} reject with icmpx admin-prohibited + ${ + if killSwitchForward then + "reject with icmpx admin-prohibited" + else + "iifname ${lanInterfaceSet} reject with icmpx admin-prohibited" + } } ''} } @@ -276,6 +411,7 @@ let { table, mark, + dnsPort, snat ? null, }: '' @@ -304,6 +440,11 @@ let '') perAppTun.localSubnets} goto app_mark } + ${mkDnsRedirect { inherit mark dnsPort; }} + ${mkMisroutedGuard mark [ + "lo" + perAppTun.interface + ] ""} ${lib.optionalString (snat != null) '' chain postrouting { type nat hook postrouting priority srcnat; policy accept; @@ -317,12 +458,14 @@ let perAppTunChainFile = pkgs.writeText "proxy-suite-routing" (mkPerAppTunChain { table = "proxy_suite_per_app_tun"; mark = perAppTun.fwmark; + dnsPort = constants.perAppTunDnsBasePort; }); perAppPinTunChainFiles = lib.genList ( slot: pkgs.writeText "proxy-suite-routing" (mkPerAppTunChain { table = "proxy_suite_per_app_via_tun_${toString slot}"; mark = constants.perAppPinTunFwmarkBase + slot; + dnsPort = constants.perAppTunDnsBasePort + 1 + slot; snat = constants.perAppPinTunSource slot; }) ) (if perAppPinTun then perAppPinSlots else 0); diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index 92b51c4..6dadf99 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -21,6 +21,7 @@ ./geodata.nix ./gui.nix ./tui.nix + ./tools.nix ./user-control.nix ./kill-switch.nix ./host.nix diff --git a/modules/proxy-suite/options/host.nix b/modules/proxy-suite/options/host.nix index 2b3f5e1..08a52cb 100644 --- a/modules/proxy-suite/options/host.nix +++ b/modules/proxy-suite/options/host.nix @@ -46,6 +46,8 @@ in # UDP ports the host's firewall opens, as "port" or "from-to". openUdpPorts = internalOption (types.listOf types.str) [ ]; resolvconfPackage = internalOption (types.nullOr types.package) null; + # The users the host's enabled time daemons send NTP as; null where the host cannot say. + timeSyncUsers = internalOption (types.nullOr (types.listOf types.str)) null; }; options.services.proxy-suite.internal = { @@ -64,6 +66,8 @@ in enable = internalOption types.bool false; pkexecWrapper = internalOption types.bool false; rules = internalOption types.lines ""; + # Action files by name (".policy"), for the polkit daemon to read. + actions = internalOption (types.attrsOf types.path) { }; }; nftables = internalOption types.bool false; # nftables tables by name, family inet (NixOS only): NAT the firewall option cannot express. diff --git a/modules/proxy-suite/options/inbounds.nix b/modules/proxy-suite/options/inbounds.nix index 27da540..a467f87 100644 --- a/modules/proxy-suite/options/inbounds.nix +++ b/modules/proxy-suite/options/inbounds.nix @@ -61,11 +61,26 @@ in Ports of this host's other services that clients reach through the tunnel on `serverAddress` and `serverAliases`, such as mail, beside the listeners' own. Direct like those: a connection to this host from itself skips its firewall, so list only - what the firewall already opens to the internet. TCP and UDP alike. + what the firewall already opens to the internet. TCP and UDP alike. Any other port on + any address of this host is refused where the inbounds dial "direct" themselves; the + addresses are read as the inbounds start, so restart them after one changes (DHCP). + Without `routing.serverSource` these connections come from this host's own address, + which its services may trust: a mail server that relays for its own host (Postfix's + default `mynetworks`) relays for every inbound user then. Set `serverSource`, or keep + such services from trusting this host's own addresses. ''; example = literalExpression "config.networking.firewall.allowedTCPPorts"; }; + accessLog = mkOption { + type = types.bool; + default = false; + description = '' + Log every connection, with the user, their address and the site, to the journal of + proxy-suite-inbounds: who went where, for anyone who can read the journal. On with + `proxy.autoProxy` whatever this says, which learns from those lines. + ''; + }; openFirewall = bool true "Open the firewall for every listener not on loopback."; shareLinks = bool true "Generate client share links for `proxy-ctl inbounds link`. Readable by root, and by `userControl.group` with the secrets scope."; @@ -111,7 +126,12 @@ in proxy = t.routingFields "that clients always reach through the local proxy, whatever the listener's `via`"; blockRu = bool true ''Block Russian destinations (geosite "category-ru", geoip "ru").''; - blockPrivate = bool true "Block private and loopback addresses, so clients cannot reach this host's LAN or local services."; + blockPrivate = bool true '' + Block private and loopback addresses, so clients cannot reach this host's LAN or local + services. Off, the LAN is open but this host is not. Either way, this host's own + addresses (loopback, and its public ones as its interfaces carry them at start) are + reachable only on the listener ports and `serverPorts`, whichever `via` a client takes. + ''; zapretDirect = bool true "Send zapret hostlist sites direct, so this host's zapret unblocks them. Only for the default `via`. With a direct listener or the XRay backend, only by IP: XRay matches names by what a client puts in its handshake, whatever address it connects to."; @@ -229,7 +249,10 @@ in default = [ ]; description = '' `dest` values a runtime listener's fallbacks may use, such as a decoy site. A - fallback to a `listener` must name another runtime listener. + fallback to a `listener` must name another runtime listener. A runtime listener's + `reality.dest` may be any public site on port 443; one on another port, on this host + or on a private network must be listed here. Its `hysteria.masquerade` must be a + public http(s) site, on port 80 or 443 unless its `host:port` is listed here. ''; example = [ "127.0.0.1:8080" ]; }; diff --git a/modules/proxy-suite/options/kill-switch.nix b/modules/proxy-suite/options/kill-switch.nix index 215a8d1..e467b68 100644 --- a/modules/proxy-suite/options/kill-switch.nix +++ b/modules/proxy-suite/options/kill-switch.nix @@ -1,11 +1,73 @@ -{ lib, ... }: +{ config, lib, ... }: +let + inherit (import ./lib.nix { inherit lib; }) addressOrCidrType; + hostTimeSyncUsers = config.services.proxy-suite.host.timeSyncUsers; +in { - options.services.proxy-suite.killSwitch.enable = lib.mkEnableOption "the kill switch" // { - description = '' - Block outgoing traffic that bypasses the active global tunnel (TUN, TProxy or a global - AmneziaWG profile), including while it restarts or after it fails. LAN, DHCP and NTP stay - open; `proxy.tproxy.lanInterfaces` devices keep the LAN but lose the internet. Only turning - the tunnel off, or `proxy-ctl killswitch off`, lifts it. - ''; + options.services.proxy-suite.killSwitch = { + enable = lib.mkEnableOption "the kill switch" // { + description = '' + Block outgoing traffic that bypasses the active global tunnel (TUN, TProxy or a global + AmneziaWG profile) from boot until the tunnel is up, while it restarts and after it + fails. LAN, DHCP and the time daemons' NTP stay open. Forwarded traffic TProxy does not + divert reaches the LAN only from `proxy.tproxy.lanInterfaces`. With TUN or a global + AmneziaWG profile configured, containers' and VMs' traffic is held to the LAN too while + neither that tunnel nor TProxy is up. Only turning the tunnel off with `proxy-ctl`, or + `proxy-ctl killswitch off`, lifts it, until the next boot or tunnel start. + ''; + }; + + directFallbacks = lib.mkOption { + type = lib.types.bool; + default = true; + description = '' + Whether, with the kill switch on, a subscription that cannot be fetched through the + tunnel is fetched once more directly, and WARP registers directly when the local proxy + cannot carry it. Either shows that server this host's own address. Off, both go through + the tunnel or not at all: a cold start with nothing cached then has no outbounds from + that subscription, and a WARP device that is itself the tunnel cannot register. + ''; + }; + + allowedSubnets = lib.mkOption { + type = lib.types.listOf addressOrCidrType; + default = config.services.proxy-suite.proxy.tproxy.localSubnets; + defaultText = lib.literalExpression "config.services.proxy-suite.proxy.tproxy.localSubnets"; + description = '' + Networks the kill switch leaves open besides the private and reserved ranges, such as + a routed IPv6 prefix on a VM bridge, whichever global mode is on. The default keeps + what TProxy leaves out reachable; set it to open a network without also taking it out + of TProxy. + ''; + example = [ + "192.168.0.0/16" + "2001:db8:1::/64" + ]; + }; + + timeSyncUsers = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = + if hostTimeSyncUsers != null then + hostTimeSyncUsers + else + [ + "systemd-timesync" + "chrony" + "_chrony" + "ntp" + "ntpsec" + ]; + defaultText = lib.literalMD '' + the users of the enabled timesyncd, chrony, ntp and openntpd on NixOS; elsewhere + `[ "systemd-timesync" "chrony" "_chrony" "ntp" "ntpsec" ]` + ''; + description = '' + Users that may send NTP (UDP port 123) past the kill switch. Users that do not exist + are skipped when it starts. A daemon sending from port 123 itself, as ntpd does, needs + no entry. + ''; + example = [ "chrony" ]; + }; }; } diff --git a/modules/proxy-suite/options/lib.nix b/modules/proxy-suite/options/lib.nix index 407e2d3..1df94ae 100644 --- a/modules/proxy-suite/options/lib.nix +++ b/modules/proxy-suite/options/lib.nix @@ -2,8 +2,31 @@ { lib }: let inherit (lib) mkOption types; + + octet = "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"; + ipv4 = "(${octet}\\.){3}${octet}"; + ipv4Prefix = "/(3[0-2]|[12]?[0-9])"; + # Loose on the groups (nft and ip reject a malformed one), strict on the characters. + ipv6 = "[0-9A-Fa-f]{0,4}(:[0-9A-Fa-f]{0,4}){2,7}(:${ipv4})?"; + ipv6Prefix = "/(12[0-8]|1[01][0-9]|[1-9]?[0-9])"; + # A readable name in docs and errors in place of the pattern. + matching = + description: pattern: + types.strMatching pattern + // { + inherit description; + }; in { + # Interface names, addresses and CIDRs go into nft rules and scripts as they are: catch + # typos early. An interface name is the kernel's (15 bytes at most), no leading "." or "-". + interfaceType = matching "network interface name" "[A-Za-z0-9_][A-Za-z0-9_.+-]{0,14}"; + ipv4CidrType = matching "IPv4 CIDR" "${ipv4}${ipv4Prefix}"; + ipv6CidrType = matching "IPv6 CIDR" "${ipv6}${ipv6Prefix}"; + addressOrCidrType = matching "IPv4 or IPv6 address or CIDR" "(${ipv4}(${ipv4Prefix})?|${ipv6}(${ipv6Prefix})?)"; + # A listen address: an IP or a host name. + hostType = matching "IP address or host name" "[A-Za-z0-9._:-]+"; + list = description: example: mkOption { diff --git a/modules/proxy-suite/options/per-app-routing.nix b/modules/proxy-suite/options/per-app-routing.nix index b8c71b6..35d2c7f 100644 --- a/modules/proxy-suite/options/per-app-routing.nix +++ b/modules/proxy-suite/options/per-app-routing.nix @@ -3,11 +3,16 @@ let inherit (lib) mkEnableOption mkOption types; t = import ./types.nix { inherit lib; }; - inherit (import ./lib.nix { inherit lib; }) int; + inherit (import ./lib.nix { inherit lib; }) + int + addressOrCidrType + interfaceType + ipv4CidrType + ; localSubnets = description: mkOption { - type = types.listOf types.str; + type = types.listOf addressOrCidrType; default = [ "192.168.0.0/16" ]; inherit description; example = [ @@ -64,15 +69,15 @@ in localSubnets = localSubnets "Subnets that skip the proxy (DNS still goes through it)."; interface = mkOption { - type = types.str; + type = interfaceType; default = "psperapptun0"; description = "Interface name."; }; address = mkOption { - type = types.str; + type = ipv4CidrType; default = "172.20.0.1/30"; - description = "Interface address (CIDR)."; + description = "Interface IPv4 address (CIDR)."; }; mtu = int 1400 "Interface MTU."; diff --git a/modules/proxy-suite/options/proxy-outbounds.nix b/modules/proxy-suite/options/proxy-outbounds.nix index 165b9be..85795e7 100644 --- a/modules/proxy-suite/options/proxy-outbounds.nix +++ b/modules/proxy-suite/options/proxy-outbounds.nix @@ -41,6 +41,35 @@ in ]; }; + runtimeSubscriptions = { + allowHttp = mkOption { + type = types.bool; + default = false; + description = '' + Let subscriptions added at runtime (`proxy-ctl proxy subs add`) be fetched over plain + http. Anyone on the way can then add entries of their own. + ''; + }; + allowInsecure = mkOption { + type = types.bool; + default = false; + description = '' + Keep entries of subscriptions added at runtime that turn certificate checks off, as + `subscriptions.*.allowInsecure` does for a declared one. Anyone on the way can then + stand in for those servers. + ''; + }; + allowPrivateServers = mkOption { + type = types.bool; + default = false; + description = '' + Keep entries of subscriptions added at runtime whose server is a private address, as + `subscriptions.*.allowPrivateServers` does for a declared one. Whoever can add a + subscription then picks servers on your network. + ''; + }; + }; + subscriptionUpdateInterval = mkOption { type = types.str; default = "1d"; diff --git a/modules/proxy-suite/options/proxy-routing.nix b/modules/proxy-suite/options/proxy-routing.nix index 5653a11..cfc16d6 100644 --- a/modules/proxy-suite/options/proxy-routing.nix +++ b/modules/proxy-suite/options/proxy-routing.nix @@ -72,8 +72,8 @@ in types.submodule { options = { url = mkOption { - type = types.strMatching "https?://.+"; - description = "URL of the sing-box rule set."; + type = types.strMatching "https://.+"; + description = "URL of the sing-box rule set (https only)."; example = "https://example.com/antifilter.srs"; }; format = mkOption { diff --git a/modules/proxy-suite/options/proxy-tproxy.nix b/modules/proxy-suite/options/proxy-tproxy.nix index 9bf61cc..8c336b0 100644 --- a/modules/proxy-suite/options/proxy-tproxy.nix +++ b/modules/proxy-suite/options/proxy-tproxy.nix @@ -2,6 +2,7 @@ let inherit (lib) mkEnableOption mkOption types; + inherit (import ./lib.nix { inherit lib; }) addressOrCidrType interfaceType; in { options.services.proxy-suite.proxy.tproxy = { @@ -32,7 +33,7 @@ in }; localSubnets = mkOption { - type = types.listOf types.str; + type = types.listOf addressOrCidrType; default = [ "192.168.0.0/16" ]; description = "Subnets that skip the proxy, such as your LAN and VM bridges (DNS still goes through it). IPv6 works too."; example = [ @@ -43,7 +44,7 @@ in }; lanInterfaces = mkOption { - type = types.listOf types.str; + type = types.listOf interfaceType; default = [ ]; description = '' LAN interfaces whose devices use this host as their gateway. Their TCP and UDP goes through the diff --git a/modules/proxy-suite/options/proxy-tun.nix b/modules/proxy-suite/options/proxy-tun.nix index 37dc81b..e35b0aa 100644 --- a/modules/proxy-suite/options/proxy-tun.nix +++ b/modules/proxy-suite/options/proxy-tun.nix @@ -2,21 +2,22 @@ let inherit (lib) mkEnableOption mkOption types; + inherit (import ./lib.nix { inherit lib; }) interfaceType ipv4CidrType; in { options.services.proxy-suite.proxy.tun = { enable = mkEnableOption "global TUN mode"; interface = mkOption { - type = types.str; + type = interfaceType; default = "singtun0"; description = "TUN interface name."; }; address = mkOption { - type = types.str; + type = ipv4CidrType; default = "172.19.0.1/30"; - description = "TUN interface address (CIDR)."; + description = "TUN interface IPv4 address (CIDR)."; }; mtu = mkOption { diff --git a/modules/proxy-suite/options/proxy.nix b/modules/proxy-suite/options/proxy.nix index 2b4aa47..8518ae7 100644 --- a/modules/proxy-suite/options/proxy.nix +++ b/modules/proxy-suite/options/proxy.nix @@ -13,6 +13,7 @@ let mkOption types ; + inherit (import ./lib.nix { inherit lib; }) hostType; in { options.services.proxy-suite.proxy = { @@ -51,15 +52,17 @@ in default = config.services.proxy-suite.host.enableIPv6; defaultText = literalExpression "config.networking.enableIPv6"; description = '' - Route IPv6 through TUN and TProxy too. When off, TProxy ignores IPv6 and the TUNs block - it, so apps fall back to IPv4. If the uplink has no IPv6, also set - `proxy.dns.strategy = "ipv4_only"`, or direct IPv6 connections hang instead of falling back. + Route IPv6 through TUN and TProxy too. When off, TProxy refuses IPv6 past the LAN and + on-link prefixes and the TUNs block it, so apps fall back to IPv4. If the uplink has no + IPv6, also set `proxy.dns.strategy = "ipv4_only"`, or direct IPv6 connections hang + instead of falling back. ''; }; listener = { address = mkOption { - type = types.str; + # Also a line of proxychains' config. + type = hostType; default = "127.0.0.1"; description = ''Address of the local SOCKS5/HTTP proxy. Use "0.0.0.0" only to expose it to the network.''; }; @@ -116,7 +119,11 @@ in probesPerRun = mkOption { type = types.ints.positive; default = 200; - description = "Maximum destinations probed per run. The rest wait for the next run, most-used first."; + description = '' + Maximum destinations probed per run: of those asked for with `proxy-ctl proxy auto + learn`, and again of those queued from traffic. The rest wait for the next run, the + queued ones most-used first. A run also ends after two hours, its probes kept. + ''; }; maxExits = mkOption { diff --git a/modules/proxy-suite/options/ssh-proxy.nix b/modules/proxy-suite/options/ssh-proxy.nix index 31932de..7e5bb9c 100644 --- a/modules/proxy-suite/options/ssh-proxy.nix +++ b/modules/proxy-suite/options/ssh-proxy.nix @@ -48,13 +48,13 @@ in type = types.listOf types.str; default = [ ]; description = '' - Accepted host keys, for sing-box. List every key `ssh-keyscan` prints, since the key type - is negotiated. + Accepted host keys, for sing-box, and for OpenSSH without `knownHostsFile`. List every + key `ssh-keyscan` prints, since the key type is negotiated. ''; example = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." ]; }; - hostKeyFile = path "Known-hosts file to read host keys from (sing-box). Takes priority over `hostKey`." "/root/.ssh/known_hosts"; + hostKeyFile = path "Known-hosts file to read host keys from (sing-box, and OpenSSH without `knownHostsFile`). Takes priority over `hostKey`." "/root/.ssh/known_hosts"; # The rest only apply to the OpenSSH unit (XRay, or asOutbound = false). knownHostsFile = path "Known-hosts file for OpenSSH." "/run/secrets/proxy-suite-ssh-known-hosts"; @@ -65,9 +65,13 @@ in "accept-new" "no" ]; - default = "accept-new"; - description = "OpenSSH host key policy."; - example = "yes"; + default = "yes"; + description = '' + OpenSSH host key policy. "yes" needs the server's keys: `knownHostsFile`, or else + `hostKeyFile` or `hostKey`. "accept-new" takes whatever key the first connection + meets, which anyone on the way can answer then. + ''; + example = "accept-new"; }; # The local SOCKS5 listener the OpenSSH unit opens. @@ -81,14 +85,22 @@ in port = mkOption { type = types.port; default = 1091; - description = "Port of the OpenSSH SOCKS5 listener."; + description = '' + Port of the OpenSSH SOCKS5 listener. It takes no login: where it is the XRay backend's + hop (`asOutbound`) on a host with root, only proxy-suite's daemons and root may + connect to it. A standalone tunnel stays open to every local user. + ''; }; }; serviceUser = mkOption { - type = token; + # A user name as nft and systemd take one. + type = types.nullOr (types.strMatching "[a-z_][a-z0-9_-]*[$]?"); default = "proxy-suite-daemon"; - description = "User that runs OpenSSH. The default is sandboxed; `null` runs it as root."; + description = '' + User that runs OpenSSH. The default is sandboxed; `null` runs it as root. Another user's + traffic gets past the kill switch, all of it: never a login user's. + ''; example = "proxy"; }; diff --git a/modules/proxy-suite/options/tools.nix b/modules/proxy-suite/options/tools.nix new file mode 100644 index 0000000..148c298 --- /dev/null +++ b/modules/proxy-suite/options/tools.nix @@ -0,0 +1,29 @@ +{ lib, ... }: + +let + inherit (lib) mkOption types; +in +{ + # Heavy helpers proxy-ctl can do without; nix-on-droid leaves them out by default. + options.services.proxy-suite.tools = { + lnav.enable = mkOption { + type = types.bool; + default = true; + defaultText = lib.literalMD "`true`, `false` on nix-on-droid"; + description = '' + Follow `proxy-ctl logs` in lnav. Without it they follow in less. + ''; + }; + + curlImpersonate.enable = mkOption { + type = types.bool; + default = true; + defaultText = lib.literalMD "`true`, `false` on nix-on-droid"; + description = '' + Probe with curl-impersonate (`proxy-ctl proxy auto probe`, and autoProxy), which + presents a browser's TLS fingerprint. Without it probes use plain curl, which some + bot protection refuses, so a working exit can be judged blocked. + ''; + }; + }; +} diff --git a/modules/proxy-suite/options/tor.nix b/modules/proxy-suite/options/tor.nix index 8ea9b28..ee4503f 100644 --- a/modules/proxy-suite/options/tor.nix +++ b/modules/proxy-suite/options/tor.nix @@ -73,12 +73,17 @@ in socksPort = mkOption { type = types.port; default = 18530; - description = "Loopback SOCKS port of Tor."; + description = '' + Loopback SOCKS port of Tor. Tor takes no login on it, so with `asOutbound` on a host with + root only proxy-suite's daemons and root may connect to it; other users reach Tor + through the proxy's own listener. + ''; }; bridges = { lines = mkOption { - type = types.listOf types.str; + # One torrc line each: a newline would add directives of its own. + type = types.listOf (types.strMatching "[^\n]*"); default = [ ]; description = '' Bridge lines from https://bridges.torproject.org, without the leading "Bridge". Setting diff --git a/modules/proxy-suite/options/types/inbounds.nix b/modules/proxy-suite/options/types/inbounds.nix index 191f7bd..c094df6 100644 --- a/modules/proxy-suite/options/types/inbounds.nix +++ b/modules/proxy-suite/options/types/inbounds.nix @@ -3,7 +3,7 @@ let inherit (lib) mkOption types; inherit (import ./amnezia-wg.nix { inherit lib; }) obfuscationType; - inherit (import ../lib.nix { inherit lib; }) nullStr; + inherit (import ../lib.nix { inherit lib; }) nullStr ipv6CidrType; # One inbound user, in `inbounds.users` under their name (shown in share links, subscriptions # and stats); listeners name the ones they accept. @@ -73,10 +73,14 @@ let ''; }; - subnet6 = nullStr '' - Tunnel IPv6 subnet (ULA). `null`: IPv4 only. With `mode = "lan"` it turns on IPv6 - forwarding, which stops this host from configuring itself from router advertisements. - '' "fd66:66::/64"; + subnet6 = + nullStr '' + Tunnel IPv6 subnet (ULA). `null`: IPv4 only. With `mode = "lan"` it turns on IPv6 + forwarding, which stops this host from configuring itself from router advertisements. + '' "fd66:66::/64" + // { + type = types.nullOr ipv6CidrType; + }; privateKeyFile = nullStr "File with the server private key, instead of a generated one." "/run/secrets/awg-server-key"; diff --git a/modules/proxy-suite/options/types/outbounds.nix b/modules/proxy-suite/options/types/outbounds.nix index 78ded80..660aba5 100644 --- a/modules/proxy-suite/options/types/outbounds.nix +++ b/modules/proxy-suite/options/types/outbounds.nix @@ -35,6 +35,29 @@ let url = nullStr "Subscription URL. Ends up in the Nix store; prefer `urlFile`." "https://example.com/sub/token123"; urlFile = nullStr "File with the subscription URL." "/run/secrets/proxy-subscription-url"; detour = detourOption "every entry of this subscription"; + allowPrivateServers = mkOption { + type = types.bool; + default = false; + description = '' + Keep entries whose server is a private address (10.0.0.0/8, 172.16.0.0/12, + 192.168.0.0/16, 100.64.0.0/10, fc00::/7), such as a subscription served on your own + network. Entries pointing at this host (loopback, "localhost", unspecified) or at a + link-local or multicast address are dropped either way: whoever serves the list picks + the servers, and the fastest wins. Only literal addresses (and "localhost") are + checked. For subscriptions added at runtime, see + `proxy.runtimeSubscriptions.allowPrivateServers`. + ''; + }; + allowInsecure = mkOption { + type = types.bool; + default = false; + description = '' + Keep entries that turn certificate checks off (`insecure=1`, for hysteria2 and + AnyTLS on sing-box), as for a provider with self-signed certificates. Anyone on the + way can then stand in for those servers. Dropped otherwise. For subscriptions added + at runtime, see `proxy.runtimeSubscriptions.allowInsecure`. + ''; + }; }; }; diff --git a/modules/proxy-suite/options/types/zapret.nix b/modules/proxy-suite/options/types/zapret.nix index 75bf131..dac7504 100644 --- a/modules/proxy-suite/options/types/zapret.nix +++ b/modules/proxy-suite/options/types/zapret.nix @@ -77,7 +77,19 @@ let }; nfqwsArgs = mkOption { - type = types.listOf types.str; + # They go into zapret's config inside double quotes, which its init script sources. + type = types.listOf ( + types.addCheck types.str ( + arg: + !builtins.any (c: lib.hasInfix c arg) [ + "\"" + "$" + "`" + "\\" + "\n" + ] + ) + ); default = [ ]; description = "Raw nfqws arguments; `--hostlist` and `--new` are added. Cannot be used with `configName`."; example = [ "--filter-tcp=443 --dpi-desync=fake,multisplit" ]; diff --git a/modules/proxy-suite/options/zapret.nix b/modules/proxy-suite/options/zapret.nix index 98eff06..6b89c2f 100644 --- a/modules/proxy-suite/options/zapret.nix +++ b/modules/proxy-suite/options/zapret.nix @@ -3,7 +3,7 @@ let inherit (lib) mkEnableOption mkOption types; t = import ./types.nix { inherit lib; }; - inherit (import ./lib.nix { inherit lib; }) list bool; + inherit (import ./lib.nix { inherit lib; }) list bool addressOrCidrType; in { options.services.proxy-suite.zapret = { @@ -44,7 +44,9 @@ in # Shared by both engines: a netfilter-level bypass, not an engine-specific concept. cidrExemption = { enable = mkEnableOption "skipping zapret for some subnets, such as NATed VMs it would break"; - cidrs = list "Subnets zapret skips." [ "192.168.123.0/24" ]; + cidrs = list "Subnets zapret skips." [ "192.168.123.0/24" ] // { + type = types.listOf addressOrCidrType; + }; }; zapret-discord-youtube = { diff --git a/modules/proxy-suite/options/zapret2.nix b/modules/proxy-suite/options/zapret2.nix index f478a95..72e06cb 100644 --- a/modules/proxy-suite/options/zapret2.nix +++ b/modules/proxy-suite/options/zapret2.nix @@ -38,7 +38,7 @@ in }; blobs = mkOption { - type = types.attrsOf types.str; + type = types.attrsOf (types.strMatching "[^[:space:]]+"); default = { }; description = "Extra fake payloads by name (blob=): a file in zapret2's files/fake, or an absolute path."; example = { @@ -47,14 +47,15 @@ in }; domains = mkOption { - type = types.listOf types.str; + # Each becomes one nfqws2 argument: whitespace would make more. + type = types.listOf (types.strMatching "[^[:space:]]+"); default = [ ]; description = "Domains always treated as blocked. At runtime: `proxy-ctl zapret auto add`."; example = [ "rutracker.org" ]; }; excludeDomains = mkOption { - type = types.listOf types.str; + type = types.listOf (types.strMatching "[^[:space:]]+"); default = [ ]; description = "Domains never touched or learned. At runtime: `proxy-ctl zapret auto exclude`."; example = [ "bank.example.com" ]; diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index f63f1c5..83e119c 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -80,7 +80,8 @@ let onionOutbound ; inherit (cfg) geodata; - inherit (derived) ruleSets; + inherit (derived) ruleSets proxyInboundsLoopback; + hopPorts = lib.optionals cfg.host.privileged derived.hopPorts; }; inherit (singBoxRules) geositeRuleSets @@ -101,7 +102,7 @@ let customRuleCategory onionOutbound ; - inherit (derived) selectionMode; + inherit (derived) selectionMode proxyInboundsLoopback; }; inherit (xrayRules) xrayRoutingRules xrayRouteModeRules; diff --git a/modules/proxy-suite/rules/proxy-inbounds.nix b/modules/proxy-suite/rules/proxy-inbounds.nix index 0a89002..ed357d6 100644 --- a/modules/proxy-suite/rules/proxy-inbounds.nix +++ b/modules/proxy-suite/rules/proxy-inbounds.nix @@ -9,7 +9,8 @@ proxyInboundsSelfSources, proxyInboundsRuntimeEnabled, proxyInboundsRuntimeVias, - proxyInboundRuntimePorts, + proxyInboundsHostPorts, + proxyInboundsLoopback, zapretDirectRules, }: @@ -34,17 +35,24 @@ let # A blocked listener stays blocked: neither serverAddress nor the proxy exceptions open it. exceptionInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via != "block") proxyInbounds); - # Only Tor reaches .onion: to the local proxy, whose own rule sends it there. First, so no - # IP rule before it has XRay look the name up, which would leak it to a resolver. - onionRule = lib.optional proxyInboundsRouteOnion (forException { - type = "field"; - ruleTag = "inbound-tor-onion"; - domain = [ "domain:onion" ]; - inboundTag = map (ib: ib.tag) ( - builtins.filter (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds - ); - outboundTag = "proxy"; - }); + # .onion goes to the local proxy, which hands it to Tor; first, so no IP rule looks it up. + # An address with an .onion SNI keeps its listener's via (mkSniffGuard). + onionListeners = builtins.filter ( + ib: ib.via != "block" && ib.listener.type != "amneziawg" + ) proxyInbounds; + onionRule = + lib.optionals (proxyInboundsRouteOnion && proxyInboundsResolveInSingBox) ( + mkSniffGuard "inbound-tor-onion-sniffed" [ "domain:onion" ] onionListeners runtimeOpenVias { } + ) + ++ lib.optional proxyInboundsRouteOnion (forException { + type = "field"; + ruleTag = "inbound-tor-onion"; + domain = [ "domain:onion" ]; + inboundTag = map (ib: ib.tag) ( + builtins.filter (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds + ); + outboundTag = "proxy"; + }); blockPrivateRule = lib.optional proxyInboundsCfg.routing.blockPrivate { type = "field"; @@ -70,30 +78,37 @@ let # Only the ports clients dial there, and the ones listed as public: the rest of this host # (wildcard services the firewall keeps from the internet) must not be reachable through it. - serverAddressPorts = lib.unique ( - map (ib: if ib.listener.sharePort != null then ib.listener.sharePort else ib.listener.port) ( - # AmneziaWG is UDP to the interface, never relayed through XRay. - builtins.filter (ib: ib.listener.type != "amneziawg") proxyInbounds - ) - ++ lib.optionals proxyInboundsCfg.subscriptions.enable [ - 80 - 443 - ] - ++ proxyInboundsCfg.serverPorts - ++ proxyInboundRuntimePorts - ); + # An allow toward "direct" only: hostFenceRules below refuse the rest there. + serverAddressPorts = proxyInboundsHostPorts; + + # XRay routes a UDP session by its first packet, so no exception leads to plain "direct" + # over UDP: IP rules go to outbounds whose finalRules allow only those addresses, name rules + # are held to TCP. + exceptionTarget = + field: ipOutbound: + if field == "ip" then + { outboundTag = ipOutbound; } + else + { + outboundTag = "direct"; + network = "tcp"; + }; # Names and IPs in rules of their own: XRay ANDs the fields of one rule. mkServerAddressRule = ruleTag: field: items: - lib.optional (items != [ ] && any exceptionInboundTags) (forException { - type = "field"; - inherit ruleTag; - ${field} = items; - inboundTag = exceptionInboundTags; - port = serverPortList; - outboundTag = "direct"; - }); + lib.optional (items != [ ] && any exceptionInboundTags) ( + forException ( + { + type = "field"; + inherit ruleTag; + ${field} = items; + inboundTag = exceptionInboundTags; + port = serverPortList; + } + // exceptionTarget field "direct-server" + ) + ); # Sniffing is routeOnly (proxy_inbound.py): a name rule also matches a connection to an IP # whose TLS SNI or HTTP Host carries that name, and "direct" then dials the IP, from this @@ -249,13 +264,17 @@ let mkZapretRule = ruleTag: field: items: - lib.optional (zapretDirectEnabled && items != [ ]) (forDefault { - type = "field"; - inherit ruleTag; - ${field} = items; - inboundTag = defaultInboundTags; - outboundTag = "direct"; - }); + lib.optional (zapretDirectEnabled && items != [ ]) ( + forDefault ( + { + type = "field"; + inherit ruleTag; + ${field} = items; + inboundTag = defaultInboundTags; + } + // exceptionTarget field "direct-zapret" + ) + ); zapretDomains = map (domain: "domain:${domain}") zapretDirectRules.domains; # Under IPOnDemand the guard would take every zapret name too: the domain rule stays off. @@ -314,9 +333,66 @@ let ip = [ "geoip:private" ]; } ]; + + # The "direct" outbound's fence around this host, whose own addresses it reaches past the + # firewall: only the ports above. The start script adds its interfaces' addresses. + hostAddresses = + proxyInboundsLoopback + ++ lib.filter (range: range != null) [ + proxyInboundsCfg.routing.serverSource.ipv4 + proxyInboundsCfg.routing.serverSource.ipv6 + ] + ++ serverIps; + hostFenceRules = + lib.optional (serverAddressPorts != [ ]) { + action = "allow"; + ip = hostAddresses; + port = serverPortList; + _hostAddresses = true; + } + ++ [ + { + action = "block"; + ip = hostAddresses; + _hostAddresses = true; + } + ]; in { - inherit xrayInboundRules selfFinalRules; + inherit xrayInboundRules selfFinalRules hostFenceRules; + # The names whose rules send a connection past its listener's via (this host, zapret's + # sites, .onion): matched only on the address the client asked for, never a sniffed name. + sniffDomainsExcluded = lib.unique ( + serverNameDomains + ++ lib.optionals zapretDirectEnabled zapretDomains + ++ lib.optional (onionListeners != [ ]) "domain:onion" + ); + # The outbounds the IP exceptions above lead to: each dials its own addresses alone. The + # start script puts "direct"'s fence around this host ahead of their rules. + exceptionOutbounds = + lib.optional (serverIps != [ ] && serverAddressPorts != [ ] && any exceptionInboundTags) { + protocol = "freedom"; + tag = "direct-server"; + settings.finalRules = [ + { + action = "allow"; + ip = serverIps; + port = serverPortList; + } + { action = "block"; } + ]; + } + ++ lib.optional (zapretDirectEnabled && zapretDirectRules.ips != [ ]) { + protocol = "freedom"; + tag = "direct-zapret"; + settings.finalRules = [ + { + action = "allow"; + ip = zapretDirectRules.ips; + } + { action = "block"; } + ]; + }; # Names of this host sent direct with no guard (IPOnDemand, and no IP aliases): a warning. unguardedServerNames = lib.optionals (!serverNameGuarded) serverNames; } diff --git a/modules/proxy-suite/rules/sing-box.nix b/modules/proxy-suite/rules/sing-box.nix index 48a4b27..5e05d73 100644 --- a/modules/proxy-suite/rules/sing-box.nix +++ b/modules/proxy-suite/rules/sing-box.nix @@ -9,6 +9,8 @@ onionOutbound, geodata, ruleSets, + proxyInboundsLoopback, + hopPorts, }: let @@ -85,6 +87,13 @@ let ++ lib.optional (onionOutbound != null) { domain_suffix = [ "onion" ]; outbound = onionOutbound; + } + # A client asking for 127.0.0.1: (mixed-in's local users) would have the daemon dial + # the loopback hops the nft guard keeps from them. + ++ lib.optional (hopPorts != [ ]) { + ip_cidr = proxyInboundsLoopback; + port = hopPorts; + action = "reject"; }; customRouteRules = map (rule: { @@ -135,13 +144,15 @@ let (mkRulesetRule "proxy" (map remoteTag r.proxy.ruleSets)) ]; + # Block ahead of the direct lists (category-ru's ad domains are in category-ads-all too); + # the user's own proxy lists still come first. singBoxRoutingRules = commonRules ++ lib.concatMap (item: item.entries) customRouteRules ++ proxyPrimaryRules + ++ blockRules ++ directRules ++ safetyDirectRules - ++ blockRules ++ proxyGeoRules; # DNS follows the routing: a name that goes through the proxy is looked up through it, so diff --git a/modules/proxy-suite/rules/xray.nix b/modules/proxy-suite/rules/xray.nix index c56eeb7..0f3179b 100644 --- a/modules/proxy-suite/rules/xray.nix +++ b/modules/proxy-suite/rules/xray.nix @@ -8,6 +8,7 @@ customRuleCategory, onionOutbound, selectionMode, + proxyInboundsLoopback, }: let @@ -117,19 +118,43 @@ let (xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips) ]; - # Kept by every route mode, like sing-box's common rules. - xrayCommonRules = lib.optional (onionOutbound != null) ( - mkXrayRule "tor-onion" { domain = [ "domain:onion" ]; } onionOutbound - ); + # Sniffing (and the TUN's fake DNS) puts a name in place of where a client connected: a + # TProxy LAN client's "Host: 127.0.0.1:2375", or a container's lvh.me through the TUN, must + # not reach this host's loopback. Names resolved only at the dial are the direct + # outbound's finalRules' (config-templates/xray.nix). No "::ffff:127.0.0.0/104": XRay + # refuses its whole config over it. + xrayTransparentInbounds = [ + "tproxy-in" + "tproxy-in6" + "tun-in" + ]; + xrayLoopbackGuardRules = [ + (mkXrayRule "guard-loopback-ip" { + inboundTag = xrayTransparentInbounds; + ip = proxyInboundsLoopback; + } "block") + (mkXrayRule "guard-loopback-domain" { + inboundTag = xrayTransparentInbounds; + domain = [ "domain:localhost" ]; + } "block") + ]; + # Kept by every route mode, like sing-box's common rules. + xrayCommonRules = + xrayLoopbackGuardRules + ++ lib.optional (onionOutbound != null) ( + mkXrayRule "tor-onion" { domain = [ "domain:onion" ]; } onionOutbound + ); + + # Block ahead of the direct lists, as sing-box has it (rules/sing-box.nix). xrayRoutingRules = xrayCommonRules ++ lib.concatMap (item: item.entries) xrayCustomRouteRules ++ xrayProxyPrimaryRules + ++ xrayBlockRules ++ xrayDirectRules ++ xraySafetyDirectRules - ++ xrayProxyGeoRules - ++ xrayBlockRules; + ++ xrayProxyGeoRules; xrayRouteModeRules = { common = xrayCommonRules; diff --git a/modules/proxy-suite/rulesets-fetch.template.sh b/modules/proxy-suite/rulesets-fetch.template.sh index 4078982..f99ca77 100644 --- a/modules/proxy-suite/rulesets-fetch.template.sh +++ b/modules/proxy-suite/rulesets-fetch.template.sh @@ -12,7 +12,8 @@ failed=0 # DNS rules read. fetch() { local name=$1 url=$2 path=$3 dns=$4 format=$5 detour=$6 tmp dnsTmp - local args=(--fail --silent --show-error --location --max-time 120 --max-filesize 64M) + # --proto-redir: a redirect to http would let the path pick the rules. + local args=(--fail --silent --show-error --location --proto-redir =https --max-time 120 --max-filesize 64M) [ "$detour" = proxy ] && args+=("${proxy[@]}") tmp=$(@coreutils@/bin/mktemp "$path.XXXXXX") || { failed=1; return; } dnsTmp=$(@coreutils@/bin/mktemp "$dns.XXXXXX") || { rm -f "$tmp"; failed=1; return; } diff --git a/modules/proxy-suite/rulesets.nix b/modules/proxy-suite/rulesets.nix index fc4b250..d6847e6 100644 --- a/modules/proxy-suite/rulesets.nix +++ b/modules/proxy-suite/rulesets.nix @@ -83,13 +83,19 @@ in "proxy-suite-socks.service" ]; wants = [ "network-online.target" ]; - serviceConfig = unprivilegedServiceConfig [ ] // { - Type = "oneshot"; - ExecStart = fetchScript; - StateDirectory = "proxy-suite/rulesets"; - StateDirectoryMode = "0755"; - LoadCredential = lib.optional withProxyAuth "proxy-password:${passwordSource}"; - }; + serviceConfig = + unprivilegedServiceConfig [ ] + # Through the proxy curl looks nothing up itself (socks5h). + // lib.optionalAttrs (lib.any (rs: rs.detour == "direct") ruleSets) ( + derived.constants.killSwitchOwnLookups pkgs + ) + // { + Type = "oneshot"; + ExecStart = fetchScript; + StateDirectory = "proxy-suite/rulesets"; + StateDirectoryMode = "0755"; + LoadCredential = lib.optional withProxyAuth "proxy-password:${passwordSource}"; + }; }; timers.proxy-suite-rulesets = { diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 01da92a..f39a389 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -300,6 +300,17 @@ let (!derived.sshProxyNativeOutbound || cfg.sshProxy.hostKey != [ ] || cfg.sshProxy.hostKeyFile != null) "proxy-suite: sshProxy.hostKey or sshProxy.hostKeyFile is required when sshProxy.asOutbound = true with a SingBox or hybrid backend, because SingBox verifies host keys by value and an empty list accepts any key. Point hostKeyFile at a known-hosts file, or list every key from `ssh-keyscan -p ` in hostKey -- the host key algorithm is negotiated, so a single pinned key fails the handshake when the server picks another algorithm." ) + # OpenSSH's own: with "yes" and no key known, it would refuse every connection. + (mkAssertion + ( + !(cfg.sshProxy.enable && derived.sshProxyUnitEnabled) + || cfg.sshProxy.strictHostKeyChecking != "yes" + || cfg.sshProxy.knownHostsFile != null + || cfg.sshProxy.hostKeyFile != null + || cfg.sshProxy.hostKey != [ ] + ) + "proxy-suite: sshProxy needs the server's host keys (knownHostsFile, hostKeyFile or hostKey, from `ssh-keyscan -p `), or strictHostKeyChecking = \"accept-new\" to trust whatever key the first connection meets" + ) (mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ]) "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}" ) @@ -589,6 +600,17 @@ let (requireEnabled proxyInboundsEnabled (proxyInbounds != [ ] || derived.proxyInboundsRuntimeEnabled) "proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners, or inbounds.runtime.enable" ) + # Each range is sized for any sane config, not for every one: a second listener on a + # port fails its unit, and whatever routes to it goes nowhere. + (uniqueValues true reservedLoopbackPorts + "proxy-suite: two of proxy-suite's own loopback listeners share a port (${ + lib.concatMapStringsSep ", " toString ( + lib.unique ( + builtins.filter (port: lib.count (p: p == port) reservedLoopbackPorts > 1) reservedLoopbackPorts + ) + ) + }): too many AmneziaWG outbounds, AmneziaWG listeners or whitelistBypass joiners for their ranges" + ) # Runtime listeners bind only there: clear of what is bound here already. (mkAssertion ( @@ -1042,6 +1064,31 @@ let ) "proxy-suite: AmneziaWG inbounds listeners route with table ${toString derived.constants.awgInboundRouteTable}, which proxy.tproxy.routeTable or a perAppRouting routeTable also uses" ) + # The tables proxy-suite numbers itself, which an option must not name too: each start + # flushes and refills its own. + ( + let + c = derived.constants; + slots = base: n: lib.genList (i: base + i) n; + internal = + map (ob: ob.routeTable) derived.awgInterfaceOutbounds + ++ lib.optionals derived.awgRuntimeIfaceOutbounds ( + slots c.awgRuntimeIfaceTableBase c.awgRuntimeIfaceSlots + ) + ++ lib.optionals derived.perAppPinTproxy (slots c.perAppPinTproxyTableBase derived.perAppPinSlots) + ++ lib.optionals derived.perAppPinTun (slots c.perAppPinTunTableBase derived.perAppPinSlots) + ++ lib.optionals derived.perAppViaProfiles (slots c.awgAppTableBase c.awgAppSlots); + named = + lib.optional globalTproxy.enable globalTproxy.routeTable + ++ lib.optional perAppRoutingTun.enable perAppRoutingTun.routeTable + ++ lib.optional perAppRoutingTproxy.enable perAppRoutingTproxy.routeTable; + taken = builtins.filter (t: builtins.elem t internal) named; + in + mkAssertion (taken == [ ]) + "proxy-suite: route table ${ + lib.concatMapStringsSep ", " toString taken + } (proxy.tproxy.routeTable or a perAppRouting routeTable) is one proxy-suite uses itself: AmneziaWG interface outbounds take ${toString c.awgOutboundRouteTableBase} up, runtime ones ${toString c.awgRuntimeIfaceTableBase} up, pin slots ${toString c.perAppPinTproxyTableBase} and ${toString c.perAppPinTunTableBase} up, apps through AmneziaWG profiles ${toString c.awgAppTableBase} up" + ) ] ++ lib.concatMap ( ib: @@ -1240,6 +1287,16 @@ let ) derived.torOnionInbounds; whitelistBypassCfg = cfg.whitelistBypass; whitelistBypassAssertions = [ + # They become unit names, outbound tags and file names, spliced into the units' scripts. + (mkAssertion + ( + !whitelistBypassCfg.enable + || lib.all (name: builtins.match "[A-Za-z0-9][A-Za-z0-9._-]*" name != null) ( + builtins.attrNames whitelistBypassCfg.joiners ++ builtins.attrNames whitelistBypassCfg.creators + ) + ) + "proxy-suite: whitelistBypass.joiners and .creators names must be letters, digits, '.', '_' and '-', starting with a letter or digit" + ) (requireEnabled ( derived.whitelistBypassJoiners != [ ] ) proxyEnabled "proxy-suite: whitelistBypass.joiners requires proxy.enable = true") @@ -1319,8 +1376,15 @@ let "proxy-suite: tor.socksPort ${toString torCfg.socksPort} collides with another proxy-suite listener" ) ]; + # zapret2.blobs' names go into nfqws2's argv as --blob=:@. + blobNameAssertions = map ( + name: + mkAssertion (builtins.match "[A-Za-z0-9._-]+" name != null) + "proxy-suite: zapret.zapret2.blobs name '${name}' must be letters, digits, dot, dash and underscore" + ) (builtins.attrNames cfg.zapret.zapret2.blobs); in rootlessAssertions +++ blobNameAssertions ++ featureAssertions ++ torAssertions ++ whitelistBypassAssertions diff --git a/modules/proxy-suite/service/builders.nix b/modules/proxy-suite/service/builders.nix index eb3a8ae..a42690f 100644 --- a/modules/proxy-suite/service/builders.nix +++ b/modules/proxy-suite/service/builders.nix @@ -68,6 +68,10 @@ rec { ExecStart = execStart; Restart = "on-failure"; RestartSec = 5; + # Backing off to two minutes: a unit that cannot come up would refetch what it lacks + # every 5 s for good. + RestartSteps = 5; + RestartMaxDelaySec = 120; RuntimeDirectory = runtimeDirectory; } // lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; } @@ -128,11 +132,13 @@ rec { execStart, execStop, }: - mkOneshotService { + # Requires=: holds the shared backend up (StopWhenUnneeded=) and restarts this with it, + # its crash included. Restarted by a switch, not stopped and started: a stop drops the hold. + lib.recursiveUpdate (mkOneshotService { inherit description execStart execStop; requires = [ "${backendService}.service" ]; after = [ "${backendService}.service" ]; - }; + }) { serviceConfig."X-StopIfChanged" = false; }; mkAnchorService = sliceName: description: @@ -201,6 +207,19 @@ rec { ${nft} delete table ${family} ${table} 2>/dev/null || true ''; + # A table's rules file swapped in whole, in one transaction: for a reload after the + # firewall flushed the ruleset, where a delete-then-load would leave a gap. + mkNftReplaceTable = + { + nft, + family, + table, + file, + }: + '' + { printf '%s\n' "table ${family} ${table}" "delete table ${family} ${table}"; cat ${file}; } | ${nft} -f - + ''; + mkIpRuleDeleteByFwmark = { ip, @@ -275,11 +294,15 @@ rec { ; }} ${mkIpLocalDefaultRouteDelete { inherit ip family table; }} + ${ip} ${family} route del unreachable default table ${toString table} 2>/dev/null || true '') [ "-4" "-6" - ]; + ] + + '' + while ${ip} -6 rule del fwmark ${toString fwmark} table main suppress_prefixlength 0 2>/dev/null; do :; done + ''; mkTproxyRoutingUp = { @@ -291,7 +314,17 @@ rec { lib.concatMapStrings (family: '' ${ip} ${family} route replace local default dev lo table ${toString table} ${ip} ${family} rule add fwmark ${toString fwmark} table ${toString table} - '') ([ "-4" ] ++ lib.optional ipv6 "-6"); + '') ([ "-4" ] ++ lib.optional ipv6 "-6") + # Without proxy.ipv6, marked IPv6 would leave directly: unreachable instead, so apps fall + # back to IPv4. Not where the kernel has no IPv6 at all. On-link IPv6 still goes by main + # (suppress_prefixlength 0: any route but its default); added last, it is looked at first. + + lib.optionalString (!ipv6) '' + if [ -e /proc/net/if_inet6 ]; then + ${ip} -6 route replace unreachable default table ${toString table} + ${ip} -6 rule add fwmark ${toString fwmark} table ${toString table} + ${ip} -6 rule add fwmark ${toString fwmark} table main suppress_prefixlength 0 + fi + ''; mkIpLinkDelete = { diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index b2dce23..f87f808 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -113,6 +113,10 @@ let ip nft ; + # NixOS's firewall loads the tables in constants.persistedNftDir itself (hosts/nixos.nix). + firewallIncludesTables = cfg.host.privileged && cfg.host.kind == "nixos"; + # Fetches subscriptions through the tunnel (subscriptions.nix): no daemon, never exempt. + subscriptionFetchUser = "proxy-suite-fetch"; # Filled in below; lazily, so the sub-modules can read each other's results. inherit scripts perAppRouting; }; diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 29d1265..ac84cf2 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -60,6 +60,9 @@ in proxychainsConfigFile amneziaWgProfileNamesFile ; + withSystemd = constants.serviceManager != "supervisor"; + withLnav = cfg.tools.lnav.enable; + withCurlImpersonate = cfg.tools.curlImpersonate.enable; env = { CLASH_API = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}"; SELECTION = selectionMode; @@ -134,7 +137,6 @@ in INBOUNDS_ENABLED = flag proxyInboundsEnabled; INBOUNDS_LINKS_FILE = proxyInboundsLinksFile; INBOUNDS_STATS_FILE = constants.inboundStatsFile; - INBOUNDS_XRAY = proxyInboundsXray; INBOUNDS_API = "unix://${constants.inboundStatsApiSocket}"; INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile; INBOUNDS_SUB_BASE_URL = @@ -153,19 +155,28 @@ in OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile; RUNTIME_OUTBOUNDS_DIR = constants.runtimeOutboundsDir; RUNTIME_SUBS_DIR = constants.runtimeSubscriptionsDir; + RUNTIME_SUBS_ALLOW_HTTP = flag proxyCfg.runtimeSubscriptions.allowHttp; USER_CONTROL_GROUP = userControlCfg.group; # {group: [scopes]}: what proxy-suite-clash-api lets each group's members ask. USER_CONTROL_GROUPS = builtins.toJSON ctx.clashBrokerGroups; LOCAL_PROXY_URL = "http://${localProxy.hostPart}:${toString proxyCfg.listener.port}"; AUTOPROXY_ENABLED = flag proxyCfg.autoProxy.enable; AUTOPROXY_STATE_DIR = constants.autoProxyStateDir; + AUTOPROXY_SPOOL_DIR = constants.autoProxySpoolDir; TOR_CONTROL_SOCKET = constants.torControlSocket; - SING_BOX = "${singBoxCfg.package}/bin/sing-box"; STATE_DIR = constants.stateDir; RUNTIME_DIR = constants.runtimeDir; SERVICE_MANAGER = constants.serviceManager; PRIVILEGED = flag constants.privileged; } + # Only the engines this host runs, so the other stays out of the closure; unset, + # proxy_ctl.py looks on PATH and skips what it cannot run. + // lib.optionalAttrs ctx.singBoxEnabled { + SING_BOX = "${singBoxCfg.package}/bin/sing-box"; + } + // lib.optionalAttrs proxyInboundsEnabled { + INBOUNDS_XRAY = proxyInboundsXray; + } // lib.optionalAttrs ctx.clashBrokerEnabled { CLASH_BROKER = constants.clashBrokerSocket; } diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index b37cb6b..d50d373 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -102,6 +102,10 @@ let ++ lib.optional cfg.whitelistBypass.enable { path = "${constants.stateDir}/whitelist-bypass"; scope = "whitelistBypass"; + } + ++ lib.optional cfg.proxy.autoProxy.enable { + path = constants.autoProxySpoolDir; + scope = "autoProxy"; }; serviceUnits = import ./units.nix { @@ -122,7 +126,12 @@ let import ../autoproxy.nix { inherit lib pkgs cfg; inherit (control) proxyCtl; - inherit (constants) autoProxyStateDir runtimeDir journalctl; + inherit (constants) + autoProxyStateDir + autoProxySpoolDir + runtimeDir + journalctl + ; inherit userControlAllows; } ); @@ -140,8 +149,17 @@ let # health/ takes hints from watchdogs; groups-state.json is for the front ends. RuntimeDirectory = "proxy-suite-outbound-groups"; RuntimeDirectoryMode = "0755"; + } + // lib.optionalAttrs cfg.host.privileged { + # health/ is the watchdogs' (root's and the service user's) to write to, not every + # local user's. Made here, with the capabilities the watcher lacks. + ExecStartPre = "+${pkgs.coreutils}/bin/install -d -m 1730 -o root -g ${constants.serviceUser} ${constants.runtimeDir}/proxy-suite-outbound-groups/health"; + } + // { NoNewPrivileges = true; PrivateTmp = true; + # Root without capabilities still owns the disks' device nodes. + PrivateDevices = true; ProtectSystem = "strict"; ProtectHome = true; ProtectClock = true; @@ -176,6 +194,8 @@ let CapabilityBoundingSet = [ "" ]; NoNewPrivileges = true; PrivateTmp = true; + # Root without capabilities still owns the disks' device nodes. + PrivateDevices = true; ProtectSystem = "strict"; ProtectHome = true; ProtectClock = true; @@ -242,8 +262,10 @@ lib.mkMerge [ services.proxy-suite.internal = { # The GUI's pkexec needs its setuid wrapper. polkit.pkexecWrapper = lib.mkIf (cfg.enable && cfg.gui.enable) true; - # See constants.serviceUser. - systemUsers = [ constants.serviceUser ]; + # See constants.serviceUser; and the subscription fetcher's (subscriptions.nix). + systemUsers = + constants.ownTrafficUsers + ++ lib.optional (constants.privileged && proxyEnabled) context.ctx.subscriptionFetchUser; packages = [ control.proxyCtl @@ -289,13 +311,17 @@ lib.mkMerge [ # carry a mark whose table has no route back. Only those: the LAN is not trusted. (lib.mkIf (tproxyLanSysctl != { }) ( let - rules = lib.concatMapStrings (interface: '' - iifname "${interface}" meta mark ${toString globalTproxy.fwmark} accept - '') globalTproxy.lanInterfaces; + rules = + extra: + lib.concatMapStrings (interface: '' + iifname "${interface}" meta mark ${toString globalTproxy.fwmark}${extra} accept + '') globalTproxy.lanInterfaces; in { - extraInputRules = rules; - extraReversePathFilterRules = rules; + # Into the backend's transparent socket alone: while it restarts, the mark would + # otherwise let a gateway client into any of this host's own listeners. + extraInputRules = rules " socket transparent 1"; + extraReversePathFilterRules = rules ""; } )) ]; @@ -306,18 +332,12 @@ lib.mkMerge [ ); polkit.enable = lib.mkIf (cfg.enable && (userControlEnabled || cfg.gui.enable)) true; - # The GUI's "Retry as Root" and root toggle run proxy-ctl through pkexec: one - # admin password then covers the next few minutes, as sudo's does in the TUI. + # The GUI's "Retry as Root" runs proxy-ctl through pkexec (polkit.nix), by the path + # proxy_model.elevated uses. + polkit.actions = lib.mkIf (cfg.enable && cfg.gui.enable) { + "${polkit.proxyCtlActionId}.policy" = polkit.mkProxyCtlAction "${control.proxyCtl}/bin/proxy-ctl"; + }; polkit.rules = lib.mkMerge [ - (lib.mkIf (cfg.enable && cfg.gui.enable) '' - polkit.addRule(function(action, subject) { - if (action.id === "org.freedesktop.policykit.exec" && - action.lookup("program") === "${control.proxyCtl}/bin/proxy-ctl") { - return polkit.Result.AUTH_ADMIN_KEEP; - } - return null; - }); - '') (lib.mkIf (cfg.enable && userControlEnabled) '' polkit.addRule(function(action, subject) { if (!(${polkit.userControlPolkitMember})) { @@ -356,6 +376,18 @@ lib.mkMerge [ "${constants.runtimeInboundsDir}/listeners" ] )) + # inbound_runtime.py's lock, outside the spool the members write to; it opens it + # read-only and never makes it, so it must be here first. + (lib.mkIf (cfg.enable && derived.proxyInboundsRuntimeEnabled && constants.privileged) ( + [ + "f ${constants.runtimeInboundsLock} 0640 root ${ + if userControlAllows "inbounds" then userControlCfg.group else "root" + } -" + ] + ++ map (g: "a+ ${constants.runtimeInboundsLock} - - - - g:${g}:r") ( + derived.userControlExtraGroupsFor "inbounds" + ) + )) # Per-app profiles added at runtime: read by everyone who runs apps, written with the # perApp scope. (lib.mkIf (cfg.enable && cfg.perAppRouting.enable) [ @@ -436,6 +468,33 @@ lib.mkMerge [ "proxy-suite: no outbounds or subscriptions are declared; the proxy will not start" + " until one is added with `proxy-ctl proxy outbounds add`" ) + # On Android every app reaches loopback: one that finds the proxy there learns its exit, + # or tells whoever asks that this phone runs one. + ++ lib.optional (cfg.host.kind == "nix-on-droid" && proxyEnabled && !localProxyAuthEnabled) ( + "proxy-suite: proxy.listener takes no login, and on Android every app can use it;" + + " set proxy.listener.auth" + ) + # Tor's SOCKS port and OpenSSH's -D take no login: without the nftables guard + # (constants.daemonMetadataGuard), every local user reaches those exits. + ++ + lib.optional + ( + !constants.privileged + && ( + derived.torOutboundEnabled || (derived.sshProxyOutboundEnabled && !derived.sshProxyNativeOutbound) + ) + ) + ( + "proxy-suite: without root, nothing keeps other local users (on Android, other apps) off" + + " the loopback SOCKS ports of ${ + lib.concatStringsSep " and " ( + lib.optional derived.torOutboundEnabled "Tor (tor.socksPort)" + ++ lib.optional ( + derived.sshProxyOutboundEnabled && !derived.sshProxyNativeOutbound + ) "the OpenSSH tunnel (sshProxy.listener.port)" + ) + }: neither takes a login. sing-box dials SSH natively, with no listener" + ) ++ lib.optional ( @@ -452,15 +511,30 @@ lib.mkMerge [ + " anyone who reaches the port uses your outbounds; set listener.auth, or keep it off the" + " firewall's allowed ports" ) - # The prober and proxy-ctl's outbound test dial these without credentials. + # OpenSSH's -D takes no login at all. ++ lib.optional - (proxyEnabled && localProxyAuthEnabled && proxyCfg.autoProxy.enable && !pureXrayEnabled) ( - "proxy-suite: proxy.listener.auth does not cover autoProxy's loopback listeners" - + " (ports ${toString proxyCfg.autoProxy.probeBasePort}-${ - toString (proxyCfg.autoProxy.probeBasePort + proxyCfg.autoProxy.maxExits - 1) - } and ${toString constants.outboundTestPort}): every local user reaches your exits through them" + cfg.sshProxy.enable + && !( + lib.hasPrefix "127." cfg.sshProxy.listener.address + || cfg.sshProxy.listener.address == "::1" + || cfg.sshProxy.listener.address == "localhost" + ) + ) + ( + "proxy-suite: sshProxy.listener.address is ${cfg.sshProxy.listener.address}: its SOCKS port takes" + + " no login, so anyone who reaches it uses the SSH server; keep it on loopback, or off the" + + " firewall's allowed ports" + ) + ++ + lib.optional + ( + cfg.warp.enable && cfg.warp.generatorUrl != null && !lib.hasPrefix "https://" cfg.warp.generatorUrl + ) + ( + "proxy-suite: warp.generatorUrl is not https://: anyone on the way can hand back a profile" + + " of their own, and the WARP traffic goes to them" ) # rules/proxy-inbounds.nix guards the names of this host only where XRay leaves names # unresolved, or where IP aliases catch a name that resolves here first. diff --git a/modules/proxy-suite/service/per-app-routing.nix b/modules/proxy-suite/service/per-app-routing.nix index 7e72f13..63d5ffe 100644 --- a/modules/proxy-suite/service/per-app-routing.nix +++ b/modules/proxy-suite/service/per-app-routing.nix @@ -34,6 +34,7 @@ let findBin headBin ; + inherit (ctx.constants) systemctl; } // slices ); diff --git a/modules/proxy-suite/service/per-app-routing/backend-scripts.nix b/modules/proxy-suite/service/per-app-routing/backend-scripts.nix index 616798e..056d15d 100644 --- a/modules/proxy-suite/service/per-app-routing/backend-scripts.nix +++ b/modules/proxy-suite/service/per-app-routing/backend-scripts.nix @@ -73,7 +73,6 @@ let family = "-6"; table = perAppRoutingTun.routeTable; }} - ${nft} -f ${perAppTunChainFile} ${perAppTunWaitForInterface} # The backend may not have brought the link up yet, and routes via a down link fail # with "Device for nexthop is not up". @@ -84,7 +83,8 @@ let ${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable} # No uplink src, as in xrayTunUpScript: it goes stale when the uplink address changes. ${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} - ${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true + # Cleared above, so it goes in; if it did not, marked apps would leave by the main table. + ${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} ${ if ipv6 then '' @@ -100,6 +100,8 @@ let '' } ${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true + # The marking last, once its routes are in (as tproxyUpScript). + ${nft} -f ${perAppTunChainFile} ''; perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app" '' @@ -140,6 +142,27 @@ let ${builders.flushResolvedCaches} ''; + # After a firewall reload that flushed the ruleset: the marking alone (the routes stay). + # The users' rules go back in with their own units' reload, ordered after this one. + perAppTunReloadScript = pkgs.writeShellScript "proxy-suite-per-app" '' + set -euo pipefail + ${builders.mkNftReplaceTable { + inherit nft; + family = "inet"; + table = "proxy_suite_per_app_tun"; + file = perAppTunChainFile; + }} + ''; + perAppTproxyReloadScript = pkgs.writeShellScript "proxy-suite-per-app" '' + set -euo pipefail + ${builders.mkNftReplaceTable { + inherit nft; + family = "inet"; + table = "proxy_suite_per_app_tproxy"; + file = perAppTproxyRulesFile; + }} + ''; + perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app" '' set -euo pipefail @@ -154,13 +177,14 @@ let table = perAppRoutingTproxy.routeTable; }} - ${nft} -f ${perAppTproxyRulesFile} + # The route first, then the marking (as tproxyUpScript). ${builders.mkTproxyRoutingUp { inherit ip; inherit ipv6; fwmark = perAppRoutingTproxy.fwmark; table = perAppRoutingTproxy.routeTable; }} + ${nft} -f ${perAppTproxyRulesFile} ''; perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app" '' @@ -181,8 +205,10 @@ in { inherit perAppTunUpScript + perAppTunReloadScript perAppTunDownScript perAppTproxyUpScript + perAppTproxyReloadScript perAppTproxyDownScript ; } 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 92fa62c..f875fc3 100644 --- a/modules/proxy-suite/service/per-app-routing/user-rules.nix +++ b/modules/proxy-suite/service/per-app-routing/user-rules.nix @@ -13,9 +13,83 @@ grepBin, findBin, headBin, + systemctl, }: let + # The hold: what a per-app slice sends unmarked is turned away, in a table no backend + # touches, so a backend restart or crash holds the apps rather than letting them out + # directly. It goes with the user's unit, not its restart, and mirrors the route's exceptions. + holdTable = "proxy_suite_per_app_hold"; + # nftables.nix's RESERVED_IP and RESERVED_IP6, which the TUN and TProxy chains leave alone. + reserved4 = [ + "10.0.0.0/8" + "100.64.0.0/10" + "127.0.0.0/8" + "169.254.0.0/16" + "172.16.0.0/12" + "192.0.0.0/24" + "224.0.0.0/4" + "240.0.0.0/4" + "255.255.255.255/32" + ]; + reserved6 = [ + "::/128" + "::1/128" + "::ffff:0:0/96" + "fc00::/7" + "fe80::/10" + "ff00::/8" + ]; + nftSet = items: "{ ${lib.concatStringsSep ", " items} }"; + # As shell words in double quotes, printed one per line: a mark of "$mark" is the shell's. + # Every route marks lookups wherever the resolver is, loopback's too. `allow`: what goes + # unmarked, in either family. + mkHoldBodies = + { + # The marks the route's packets carry, as shell text (a number, or "$mark"). + marks, + allow, + }: + let + # Not merely "no mark": since Linux 5.17 CAP_NET_RAW sets one (ping -m), so a held app + # could mark its way out. A kernel AmneziaWG interface's own encapsulated packets keep + # the app's socket with the interface's FwMark: the via route lists that mark too. + unmarked = "meta mark != { ${lib.concatStringsSep ", " marks} }"; + reject = "reject with icmpx admin-prohibited"; + allow4 = builtins.filter (cidr: !lib.hasInfix ":" cidr) allow; + allow6 = builtins.filter (lib.hasInfix ":") allow; + bodies = [ + "${unmarked} meta l4proto { tcp, udp } th dport 53 ${reject}" + "${unmarked} ct direction != reply ip daddr != ${nftSet allow4} ${reject}" + "${unmarked} ct direction != reply ip6 daddr != ${nftSet allow6} ${reject}" + ]; + in + "printf '%s\\n' ${lib.concatMapStringsSep " " (body: "\"${body}\"") bodies}"; + tunHold = + mark: + mkHoldBodies { + marks = [ mark ]; + allow = reserved4 ++ reserved6 ++ perAppRoutingTun.localSubnets; + }; + tproxyHold = + mark: + mkHoldBodies { + marks = [ mark ]; + allow = reserved4 ++ reserved6 ++ perAppRoutingTproxy.localSubnets; + }; + # Deletes the rules of one comment from a chain, if the table is there. + dropRulesByComment = table: chain: comment: '' + handles=$(${nft} -a list chain ${table} ${chain} 2>/dev/null \ + | ${grepBin} -F "comment \"${comment}\"" \ + | ${awk} '{ print $NF }' || true) + if [ -n "$handles" ]; then + while IFS= read -r handle; do + [ -n "$handle" ] || continue + ${nft} delete rule ${table} ${chain} handle "$handle" || true + done <<< "$handles" + fi + ''; # `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. @@ -30,6 +104,8 @@ let sliceLabel, markRule, prelude ? "", + # Shell text printing the hold's rule bodies (mkHoldBodies); null: no hold. + hold ? null, }: pkgs.writeShellScript "proxy-suite-per-app" '' set -euo pipefail @@ -58,6 +134,22 @@ let fi cgroup_path=''${cgroup_dir#/sys/fs/cgroup/} cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }') + ${lib.optionalString (hold != null) '' + # The hold first: from here on, nothing of the app leaves unmarked. + hold_comment="$rule_comment_prefix-hold" + ${dropRulesByComment "inet ${holdTable}" "output" "$hold_comment"} + { + printf '%s\n' "add table inet ${holdTable}" \ + "add chain inet ${holdTable} output { type filter hook output priority filter; policy accept; }" + # In a subshell: `hold` may be a case statement over several lines. + ( + ${hold} + ) | while IFS= read -r body; do + printf 'add rule inet ${holdTable} output socket cgroupv2 level %s "%s" %s comment "%s"\n' \ + "$cgroup_level" "$cgroup_path" "$body" "$hold_comment" + done + } | ${nft} -f - + ''} handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \ | ${grepBin} -F "comment \"$rule_comment_prefix-mark\"" \ @@ -81,12 +173,24 @@ let nftTable, nftChain, prelude ? "", + # Whether the start put a hold in (mkUserRuleStart). + hold ? false, + # The unit this runs in, as shell text. + unitName ? ''"proxy-suite-${name}-user@$uid.service"'', }: pkgs.writeShellScript "proxy-suite-per-app" '' set -euo pipefail ${prelude} uid="$1" rule_comment_prefix="proxy-suite-${name}-user-$uid" + ${lib.optionalString hold '' + # Its restart (the backend's restart or crash, through Requires=, or a switch) keeps the + # hold, a job of that type until the stop half is done: the app waits for its marking. + if ! ${systemctl} list-jobs --no-legend ${unitName} \ + | ${awk} '$3 == "restart" { found = 1 } END { exit !found }'; then + ${dropRulesByComment "inet ${holdTable}" "output" "$rule_comment_prefix-hold"} + fi + ''} handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \ | ${grepBin} -F "comment \"$rule_comment_prefix-mark\"" \ | ${awk} '{ print $NF }' || true) @@ -107,28 +211,32 @@ let sliceName = perAppTunSliceName; sliceLabel = "app TUN"; markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}"; + hold = tunHold (toString perAppRoutingTun.fwmark); }; perAppTunUserRuleStop = mkUserRuleStop { name = "per-app-tun"; nftFamily = "inet"; nftTable = "proxy_suite_per_app_tun"; nftChain = "app_mark"; + hold = true; }; perAppTproxyUserRuleStart = mkUserRuleStart { name = "per-app-tproxy"; nftFamily = "inet"; nftTable = "proxy_suite_per_app_tproxy"; - nftChain = "output"; + nftChain = "app_mark"; sliceName = perAppTproxySliceName; sliceLabel = "app TProxy"; markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}"; + hold = tproxyHold (toString perAppRoutingTproxy.fwmark); }; perAppTproxyUserRuleStop = mkUserRuleStop { name = "per-app-tproxy"; nftFamily = "inet"; nftTable = "proxy_suite_per_app_tproxy"; - nftChain = "output"; + nftChain = "app_mark"; + hold = true; }; perAppZapretUserRuleStart = mkUserRuleStart { @@ -148,7 +256,13 @@ let }; in { - inherit mkUserRuleStart mkUserRuleStop; + inherit + mkUserRuleStart + mkUserRuleStop + mkHoldBodies + tunHold + tproxyHold + ; 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 index 3cfe0fa..9ad097e 100644 --- a/modules/proxy-suite/service/per-app-routing/via.nix +++ b/modules/proxy-suite/service/per-app-routing/via.nix @@ -27,6 +27,7 @@ let ip nft jq + awk ; inherit (constants) awgPerAppRulePriority @@ -91,7 +92,7 @@ let 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 + if [[ ! $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] || (( 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 @@ -112,9 +113,16 @@ let } 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 + # One added at runtime: the slot its interface runs in, as proxy-suite-awg-if@ keeps it; + # else the spool's, which is group-writable (O_NOFOLLOW), and names the slot it gets + # next, not the one a tag removed and added again still runs in. + slot_file="/run/proxy-suite-awg-if-$tag/slot" + if [[ -s $slot_file && ! -L $slot_file ]]; then + slot=$(${pkgs.coreutils}/bin/head -n 1 "$slot_file") + else + slot=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$tag.iface" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true) + fi + if [[ $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] && (( 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), @@ -217,6 +225,12 @@ let type nat hook postrouting priority srcnat; policy accept; oifname "$interface" meta mark $mark masquerade } + # The app's packets out of any other interface: the ip rules are gone (networkd + # drops rules it did not make), and the main table took them to the uplink. + chain misrouted { + type filter hook postrouting priority filter; policy accept; + meta mark $mark oifname != { "lo", "$interface" } drop + } } EOF @@ -237,9 +251,15 @@ let exec ${python3} ${proxySuiteScriptsDir}/per_app_dns.py --port "$dns_port" --mark "$mark" "''${servers[@]}" ''; + # A failure keeps the marking and the unreachable rule, so the apps are turned away rather + # than sent out directly until the restart; viaUp clears it. A stop takes it all down. viaDown = pkgs.writeShellScript "proxy-suite-per-app" '' set -uo pipefail ${resolveInstance} + if [[ ''${SERVICE_RESULT:-success} != success ]]; then + echo "proxy-suite: per-app via $1 failed ($SERVICE_RESULT): its apps are held until it is back" >&2 + exit 0 + fi ${nft} delete table inet "$nft_table" 2>/dev/null || true ${rulesDown} ''; @@ -279,7 +299,33 @@ let slice_name="proxy-suite-per-app-via-$key.slice" set -- "''${instance%%-*}" ''; - viaUserStart = userRules.mkUserRuleStart { + # The hold (user-rules.nix), by what the key runs via: an AmneziaWG interface takes the + # private ranges too (as viaUp's chain does), a pin slot what its route's backend takes. + viaHold = '' + case "$key" in + awg-* | app-*) + ${userRules.mkHoldBodies { + marks = [ + "$mark" + (toString cfg.proxy.tproxy.proxyMark) + ]; + allow = [ + "127.0.0.0/8" + "169.254.0.0/16" + "224.0.0.0/4" + "255.255.255.255/32" + "::1/128" + "fe80::/10" + "ff00::/8" + ] + ++ perAppRoutingCfg.via.localSubnets; + }} + ;; + tproxy-*) ${userRules.tproxyHold "$mark"} ;; + tun-*) ${userRules.tunHold "$mark"} ;; + esac + ''; + viaUserRule = userRules.mkUserRuleStart { name = "per-app-via-$key"; nftFamily = "inet"; nftTable = "$nft_table"; @@ -288,6 +334,7 @@ let sliceLabel = "app via"; markRule = "meta mark set $mark ct mark set $mark"; prelude = userPrelude; + hold = viaHold; }; viaUserStop = userRules.mkUserRuleStop { name = "per-app-via-$key"; @@ -295,7 +342,88 @@ let nftTable = "$nft_table"; nftChain = "$nft_chain"; prelude = userPrelude; + hold = true; + unitName = ''"proxy-suite-per-app-via-user@$instance.service"''; }; + + # $1, a user unit's instance -, to $key and $via_unit, the unit whose table + # the key's user rules go in. + viaUserKey = '' + 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[1]} + case "$key" in + awg-* | app-*) via_unit="proxy-suite-per-app-via@$key.service" ;; + *) via_unit="proxy-suite-per-app-via-''${key%%-*}@''${key#*-}.service" ;; + esac + ''; + # Held while a user's rule goes in, and while the last user's unit takes the via unit + # down: no rule lands in a table on its way out, to leave its app unmarked. + viaUsersLock = '' + ${pkgs.coreutils}/bin/mkdir -p ${pinDir} + exec 8>>"${pinDir}/users-$key.lock" + ${flock} 8 + ''; + viaUserStart = pkgs.writeShellScript "proxy-suite-per-app" '' + set -euo pipefail + ${viaUserKey} + ${viaUsersLock} + # proxy-ctl starts it first; one on its way down takes the table with it. + if [[ $(${constants.systemctl} show --property=ActiveState --value "$via_unit") != active ]]; then + echo "proxy-suite: $via_unit is not up" >&2 + exit 1 + fi + ${viaUserRule} "$1" + ''; + # ExecStopPost of a user's unit: with no other user's left, the via unit goes, and the + # global profile it ran through. perApp members may only start those (polkit.nix): + # stopping one under another user's apps would send them out unmarked. + viaRetire = pkgs.writeShellScript "proxy-suite-per-app" '' + set -euo pipefail + ${viaUserKey} + # Its own restart (a job of that type until the stop half is done) comes straight back. + if ${constants.systemctl} list-jobs --no-legend "proxy-suite-per-app-via-user@$1.service" \ + | ${awk} '$3 == "restart" { found = 1 } END { exit !found }'; then + exit 0 + fi + ${viaUsersLock} + others=$(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \ + "proxy-suite-per-app-via-user@*-$key.service" \ + | ${awk} -v self="proxy-suite-per-app-via-user@$1.service" '$1 != self') + [[ -z $others ]] || exit 0 + was=$(${constants.systemctl} show --property=ActiveState --value "$via_unit" || true) + ${constants.systemctl} stop "$via_unit" + # A failed one kept its rules to hold its apps (viaDown), and a stop runs nothing more for + # it: with no app left, they go here. + if [[ $was == failed && ( $key == awg-* || $key == app-* ) ]]; then + SERVICE_RESULT=success ${viaDown} "$key" || true + ${constants.systemctl} reset-failed "$via_unit" 2>/dev/null || true + fi + ${lib.optionalString perAppViaProfiles '' + # After the via unit: its stop reads the profile's slot. + if [[ $key == app-* ]]; then + set -- "''${key#app-}" + ${decodeTag} + ${constants.systemctl} stop "proxy-suite-awg-app@$tag.service" + fi + ''} + ''; + # ExecStartPost of the via units, $1 the key. Their table starts empty, also on a restart + # (Restart=, or that of the backend a pin is part of), under users' units that stay + # active: their rules go back in here, or their apps would go out unmarked. + viaReapply = pkgs.writeShellScript "proxy-suite-per-app" '' + set -uo pipefail + ${constants.systemctl} list-units --plain --no-legend --state=active \ + "proxy-suite-per-app-via-user@*-''${1:-}.service" \ + | while read -r unit _; do + instance=''${unit#proxy-suite-per-app-via-user@} + ${viaUserRule} "''${instance%.service}" \ + || echo "proxy-suite: the rule of $unit did not go back in" >&2 + done + ''; # 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"; @@ -308,7 +436,7 @@ let tableBase = constants.perAppPinTproxyTableBase; nftFiles = perAppPinTproxyRulesFiles; # Where the user rule units add their cgroup rules, as for the per-app TProxy's own. - nftChain = "output"; + nftChain = "app_mark"; clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}"; secretFile = "${constants.runtimeDir}/proxy-suite-socks/clash-secret"; backend = "proxy-suite-socks.service"; @@ -458,6 +586,26 @@ let set -euo pipefail ${decodeTag} ${pinSlot route true} + if [[ -z $slot ]]; then + # Every slot taken: one that nothing has run through for a minute (no user's marking + # unit for it), as a perApp member could leave behind by starting the unit alone, is + # taken back. The minute spares one proxy-ctl has just started for its app. + for (( n = 0; n < ${toString perAppPinSlots}; n++ )); do + slot_file="${pinDir}/${route}-$n" + [[ -f $slot_file ]] || continue + other=$(< "$slot_file") + [[ $other =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || continue + (( $(${pkgs.coreutils}/bin/date +%s) - $(${pkgs.coreutils}/bin/stat -c %Y "$slot_file") >= 60 )) || continue + other_hex=$(printf '%s' "$other" | ${pkgs.coreutils}/bin/od -An -tx1 | ${pkgs.coreutils}/bin/tr -d ' \n') + if [[ -z $(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \ + "proxy-suite-per-app-via-user@*-${route}-$other_hex.service") ]]; then + echo "proxy-suite: taking back ${route} pin slot $n from '$other': nothing runs through it" >&2 + ${constants.systemctl} stop "proxy-suite-per-app-via-${route}@$other_hex.service" || true + break + fi + done + ${pinSlot route true} + fi if [[ -z $slot ]]; then echo "proxy-suite: all ${toString perAppPinSlots} ${route} pin slots are taken (perAppRouting.via.pinSlots)" >&2 exit 1 @@ -472,8 +620,10 @@ let trap release ERR files=(${lib.concatMapStringsSep " " toString r.nftFiles}) ${nft} delete table inet "$nft_table" 2>/dev/null || true - ${nft} -f "''${files[$slot]}" + # The route first, then the marking: a packet marked before its route is in would + # leave by the main table, and the kill switch lets the mark through. ${r.routingUp} + ${nft} -f "''${files[$slot]}" # A backend that restarts restarts this too (PartOf), which switches it again. select_pin "$tag" 60 ''; @@ -505,8 +655,11 @@ in viaUp viaDns viaDown + viaUserRule viaUserStart viaUserStop + viaRetire + viaReapply pinRoutes pinUp pinDown diff --git a/modules/proxy-suite/service/polkit-rules.template.js b/modules/proxy-suite/service/polkit-rules.template.js index 1b80efb..c02d37e 100644 --- a/modules/proxy-suite/service/polkit-rules.template.js +++ b/modules/proxy-suite/service/polkit-rules.template.js @@ -3,6 +3,8 @@ if (typeof unit !== "string" || @verbs@.indexOf(verb) === -1) { return null; } var known = @units@.indexOf(unit) !== -1; +// One of the subject's own per-app marking units, rather than one every user shares. +var own = false; var templates = @templates@; for (var i = 0; !known && i < templates.length; i++) { var template = templates[i]; @@ -25,6 +27,7 @@ for (var i = 0; !known && i < templates.length; i++) { if (owner !== uid) { return null; } + own = true; } known = true; } @@ -40,6 +43,9 @@ for (var prefix in scopeByUnitPrefix) { break; } } +if (scope === "perApp" && !own && @sharedVerbs@.indexOf(verb) === -1) { + return null; +} // Any of the subject's groups that holds the scope. var groupScopes = @groupScopes@; for (var group in groupScopes) { diff --git a/modules/proxy-suite/service/polkit.nix b/modules/proxy-suite/service/polkit.nix index 9e6e1c4..bfc81f6 100644 --- a/modules/proxy-suite/service/polkit.nix +++ b/modules/proxy-suite/service/polkit.nix @@ -1,5 +1,5 @@ # Polkit rule body granting userControl group members passwordless control over the -# units of their scopes. +# units of their scopes; and the GUI's pkexec action for proxy-ctl. # # Only units this module declares, by their full names: systemd asks the same # manage-units question with the same unit name for a transient unit @@ -30,6 +30,10 @@ let # 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"; + # Their watchdogs, which pull them in (Wants=, BindsTo=): the same scope, or "services" + # would start what it does not hold. + "proxy-suite-awg-app-watchdog@" = "perApp"; + "proxy-suite-awg-if-watchdog@" = "outbounds"; "proxy-suite-awg-runtime-sync." = "outbounds"; "proxy-suite-autoproxy-learn." = "autoProxy"; "proxy-suite-zapret2-cutoff." = "zapret"; @@ -50,10 +54,18 @@ let "reload-or-try-restart" "reset-failed" ]; + # perApp units every user's apps share: start only, as a stop or restart would send the + # other users' apps out unmarked. They go once idle on their own. + sharedVerbs = [ + "start" + "reset-failed" + ]; + proxyCtlActionId = "io.github.FUFSoB.ProxySuite.proxy-ctl"; in { userControlPolkitRules = fillTemplate ./polkit-rules.template.js { verbs = builtins.toJSON verbs; + sharedVerbs = builtins.toJSON sharedVerbs; units = builtins.toJSON units; templates = builtins.toJSON templates; coreutils = pkgs.coreutils; @@ -64,4 +76,36 @@ in userControlPolkitMember = lib.concatMapStringsSep " || " ( group: "subject.isInGroup(${builtins.toJSON group})" ) (builtins.attrNames userControlGroupScopes); + + inherit proxyCtlActionId; + # pkexec's action for proxy-ctl, by its path after realpath. The password every time: a + # kept grant covers the whole session, and proxy-ctl as root runs commands (`apps run`). + mkProxyCtlAction = + program: + pkgs.writeTextFile { + name = "proxy-suite-polkit-action"; + # polkitd skips a file it cannot parse, and pkexec then falls back to its generic action. + checkPhase = '' + ${pkgs.libxml2.bin}/bin/xmllint --noout --nonet \ + --dtdvalid ${pkgs.polkit.out}/share/polkit-1/policyconfig-1.dtd "$target" + ''; + text = '' + + + + proxy-suite + + Run proxy-ctl as root + Authentication is required to change proxy-suite as root + + auth_admin + auth_admin + auth_admin + + ${program} + + + ''; + }; } diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index 1e0792c..9bc2517 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -31,6 +31,10 @@ let builders constants ; + # A value in a shell comment, on that one line: a newline in a tag (types.str) would end + # the comment and run the rest as root. + oneLine = value: builtins.replaceStrings [ "\n" "\r" ] [ " " " " ] (toString value); + runtimeDir = "${constants.runtimeDir}/proxy-suite-inbounds"; linksFile = "${runtimeDir}/links.json"; subscriptionsFile = "${runtimeDir}/subscriptions.json"; @@ -126,7 +130,7 @@ let in if urlSource == null then '' - # via outbound: ${ob.tag} (static xray json) + # via outbound: ${oneLine ob.tag} (static xray json) OB_JSON=$(cat ${ pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON (ob.xrayJson // { inherit (ob) tag; })) }) @@ -135,7 +139,7 @@ let '' else '' - # via outbound: ${ob.tag} + # via outbound: ${oneLine ob.tag} URL=$(cat ${lib.escapeShellArg urlSource}) OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \ --backend xray --tag ${lib.escapeShellArg ob.tag}) @@ -165,9 +169,12 @@ let printf '%s' "$body" > "$SUB_DIR.new/$token" done chmod -R u=rwX,g=rX,o= "$SUB_DIR.new" + # Traverse-only for the group: the web server opens a token by name but can never + # list them all (autoindex, a stray directory listing). + chmod 0710 "$SUB_DIR.new" ${constants.ifPrivileged '' ${pkgs.coreutils}/bin/chgrp -R ${lib.escapeShellArg subsCfg.group} "$SUB_DIR.new" || - echo "proxy-suite: group ${subsCfg.group} cannot be given the subscriptions; they stay root-only" >&2''} + echo "proxy-suite: group "${lib.escapeShellArg subsCfg.group}" cannot be given the subscriptions; they stay root-only" >&2''} rm -rf "$SUB_DIR" mv "$SUB_DIR.new" "$SUB_DIR" ${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}" @@ -194,11 +201,19 @@ let INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED") + # Every address this host has now, for the direct outbound's fence (rules/proxy-inbounds.nix): + # one it gains later is fenced from the next start. Where netlink is closed (Android), the + # fence keeps what the configuration knows. + if ! HOST_ADDRESSES=$(${ip} -j addr show | ${jq} -c '[.[].addr_info[]?.local | strings] | unique'); then + echo "proxy-suite: cannot list this host's addresses; direct reaches any port of those not configured" >&2 + HOST_ADDRESSES='[]' + fi + OUTBOUNDS_JSON='[]' ${viaOutboundsBlock} ${lib.optionalString needsLocalProxyAuth '' - LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" + LOCAL_PROXY_PASSWORD="$(cat ${lib.escapeShellArg localProxyAuthPasswordSource})" ''} # With inbounds.runtime, the routing rules are build-inbound.py's: the template's with the @@ -216,8 +231,19 @@ let } \ --argjson runtime ${if proxyInboundsRuntimeEnabled then "true" else "false"} \ --slurpfile rendered <(printf '%s' "$RENDERED") \ + --argjson host_addresses "$HOST_ADDRESSES" \ '.inbounds += $ibs[0] + | (.outbounds[] | select(.tag == "direct") | .settings.finalRules[] | select(._hostAddresses)) + |= (.ip += ($host_addresses - .ip) | del(._hostAddresses)) | .outbounds = $obs[0] + .outbounds + # A via outbound that is freedom too (xrayJson, say, for its fragment settings) + # dials from this host as "direct" does: the same fence, ahead of its own rules; + # all of it but the closing allow of "direct", which would end them. + | ([.outbounds[] | select(.tag == "direct") | .settings.finalRules // []] | first // []) as $fence + | (.outbounds[] | select(.protocol == "freedom" and .tag != "direct" + and ((.tag // "") | startswith("direct-self") | not))) + |= (.settings = ((.settings // {}) + | .finalRules = (($fence | map(select(. != {action: "allow"}))) + (.finalRules // [])))) | if $runtime then .routing.rules = $rendered[0].rules | .outbounds += $rendered[0].selfOutbounds @@ -262,7 +288,8 @@ let else '' ${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"''} - chmod 640 "$RUNTIME_DIR/config.json.tmp" + # Without root the group is the user's own primary one, which may be shared. + chmod ${if constants.privileged then "640" else "600"} "$RUNTIME_DIR/config.json.tmp" '' } ${constants.grantFileAcl pkgs ''"$RUNTIME_DIR/config.json.tmp"'' @@ -271,26 +298,17 @@ let } mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json" - # The stats API's socket takes this setgid directory's group: XRay cannot chown it. + # The stats API's socket: the daemon's and root's alone. Whoever reaches it can reset the + # counters, wiping per-user traffic before the collector adds it up; the stats scope + # reads the collector's file instead. API_DIR=$(dirname ${lib.escapeShellArg constants.inboundStatsApiSocket}) rm -rf "$API_DIR" ${ if !constants.privileged then ''mkdir -m 0700 "$API_DIR"'' - else if userControlAllows "stats" then - '' - install -d -m 2750 -o ${constants.serviceUser} -g ${lib.escapeShellArg userControlCfg.group} "$API_DIR" || - install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"'' else - ''install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"'' + ''install -d -m 0700 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"'' } - # userControl.groups with the stats scope: into the directory, and onto the socket XRay - # makes in it as its own group is (a default entry; the socket's mode caps it). - ${lib.optionalString (constants.privileged && userControlExtraGroupsFor "stats" != [ ]) '' - ${pkgs.acl}/bin/setfacl -m ${ - lib.concatMapStringsSep "," (g: "g:${g}:rx,d:g:${g}:rwx") (userControlExtraGroupsFor "stats") - } -- "$API_DIR" - ''} ${writeLinksBlock} ${writeSubscriptionsBlock} @@ -300,7 +318,8 @@ let ''; # Adds XRay's counters to the daily totals, read and reset in one call, and notes who - # is online. Run by a timer, and by the inbounds' ExecStop, so a restart loses nothing. + # is online: .online, for `proxy-ctl inbounds online` without the API. Run by a timer, + # and by the inbounds' ExecStop, so a restart loses nothing. collectInboundStats = pkgs.writeShellScript "proxy-suite-inbounds" '' set -euo pipefail file=${lib.escapeShellArg constants.inboundStatsFile} @@ -326,18 +345,22 @@ let } [ -s "$file" ] || echo '{}' > "$file" tmp=$(${pkgs.coreutils}/bin/mktemp "$file.XXXXXX") - ${jq} --argjson q "$reading" --argjson online "$online" --argjson awg "$awg" \ + # Slurped, not --argjson: one argument holds at most 128 KiB, which a few hundred users' + # counters outgrow, and the reading above already reset them. + ${jq} --slurpfile q_ <(printf '%s' "$reading") --slurpfile online_ <(printf '%s' "$online") \ + --slurpfile awg_ <(printf '%s' "$awg") \ --arg day "$(${pkgs.coreutils}/bin/date +%F)" \ --argjson now "$(${pkgs.coreutils}/bin/date +%s)" \ - -f ${ + "\$q_[0] as \$q | \$online_[0] as \$online | \$awg_[0] as \$awg | $(< ${ builtins.path { name = "proxy-suite-inbounds"; path = ../inbound-stats-add.jq; } - } "$file" > "$tmp" + }) + | .online = (\$online.users // [])" "$file" > "$tmp" ${lib.optionalString (userControlAllows "stats") '' ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" || - echo "proxy-suite: group ${userControlCfg.group} cannot read the stats; they stay root-only" >&2 + echo "proxy-suite: group "${lib.escapeShellArg userControlCfg.group}" cannot read the stats; they stay root-only" >&2 ''} chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp" ${constants.grantFileAcl pkgs ''"$tmp"'' (userControlExtraGroupsFor "stats") "r"} diff --git a/modules/proxy-suite/service/routing-scripts.nix b/modules/proxy-suite/service/routing-scripts.nix index 3cbcda8..772ccff 100644 --- a/modules/proxy-suite/service/routing-scripts.nix +++ b/modules/proxy-suite/service/routing-scripts.nix @@ -15,6 +15,7 @@ let tproxyLanSysctl perAppRoutingTun proxyCfg + cfg ; inherit (proxyCfg) ipv6; inherit (constants) @@ -47,6 +48,23 @@ let "-6" ]; + # A table, as NixOS's firewall includes it (constants.persistedNftDir): written aside and + # renamed, never half there. `lines`: its rules, as shell words printed one per line. + persistedNftDir = ctx.constants.persistedNftDir; + persistTable = + table: lines: + lib.optionalString ctx.firewallIncludesTables '' + ${pkgs.coreutils}/bin/install -d -m 0700 ${persistedNftDir} + ( + umask 077 + printf '%s\n' "add table inet ${table}" "delete table inet ${table}" ${lines} \ + > ${persistedNftDir}/${table}.nft.tmp + ) && mv -f ${persistedNftDir}/${table}.nft.tmp ${persistedNftDir}/${table}.nft + ''; + # Before the table goes: a firewall reload in between would bring it back. + unpersistTable = + table: lib.optionalString ctx.firewallIncludesTables "rm -f ${persistedNftDir}/${table}.nft"; + # Replies to connections from outside (sshd, a game server, anything listening) take # proxyMark, so the fwmark rule sends them back out the way they came instead of into # the TUN, where nothing expects them. Locally started connections stay "original". @@ -72,18 +90,30 @@ let in { # One nft transaction swaps the old table for the new: traffic never sees neither. Also the - # unit's reload, which a switch runs instead of a restart (units.nix). + # unit's reload, which a switch runs instead of a restart (units.nix). The time daemons' + # users are looked up here rather than named in the rules: a missing one would fail them all. killSwitchUpScript = pkgs.writeShellScript "proxy-suite-routing" '' set -euo pipefail - ${nft} -f - <<'EOF' + uids=() + for user in ${lib.escapeShellArgs cfg.killSwitch.timeSyncUsers}; do + uid=$(${pkgs.coreutils}/bin/id -u -- "$user" 2>/dev/null) && uids+=("$uid") + done + time_sync= + if (( ''${#uids[@]} )); then + time_sync="add element inet proxy_suite_killswitch time_sync_uids { $(IFS=,; echo "''${uids[*]}") }" + fi + ${nft} -f - </dev/null || true + '' + } ${lib.optionalString perAppRoutingTun.enable '' - ${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} - ${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} + for family in "''${families[@]}"; do + ${ip} "$family" rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} + done ''} - service_uid=$(${pkgs.coreutils}/bin/id -u ${constants.serviceUser}) - ${ip} -4 rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main - ${ip} -6 rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main - for family in -4 -6; do + for service_user in ${lib.escapeShellArgs constants.ownTrafficUsers}; do + service_uid=$(${pkgs.coreutils}/bin/id -u "$service_user") + for family in "''${families[@]}"; do + ${ip} "$family" rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main + done + done + for family in "''${families[@]}"; do ${ip} "$family" rule add pref ${toString xrayTunMarkBypassRulePriority} fwmark ${toString globalTproxy.proxyMark} lookup main ${ip} "$family" rule add pref ${toString xrayTunDnsRulePriority} ipproto udp dport 53 table ${toString tunAutoRouteTableIndex} ${ip} "$family" rule add pref ${toString xrayTunDnsRulePriority} ipproto tcp dport 53 table ${toString tunAutoRouteTableIndex} ${ip} "$family" rule add pref ${toString xrayTunMainRulePriority} lookup main suppress_prefixlength 0 done - ${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex} - ${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex} + for family in "''${families[@]}"; do + ${ip} "$family" rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex} + done + ''; + + # The reply marking, after a firewall reload that flushed the ruleset: without it, replies + # to connections from outside (sshd among them) are routed into the TUN until it restarts. + xrayTunReloadScript = pkgs.writeShellScript "proxy-suite-routing" '' + set -euo pipefail + ${builders.mkNftReplaceTable { + inherit nft; + family = "inet"; + table = xrayTunReplyTable; + file = xrayTunReplyRules; + }} ''; tproxyUpScript = pkgs.writeShellScript "proxy-suite-routing" '' @@ -164,24 +228,50 @@ in table = globalTproxy.routeTable; }} - ${nft} -f ${nftablesRulesFile} - # Set on NixOS already; system-manager hosts only get them here. + # Set on NixOS already; system-manager hosts only get them here. Left on at the stop: + # by then something else (Docker, libvirt) may rely on forwarding too. ${lib.concatStrings ( lib.mapAttrsToList (name: value: '' ${pkgs.procps}/bin/sysctl -q -w ${name}=${toString value} '') tproxyLanSysctl )} + # The route first, then the marking: a packet marked before its rule exists would leave + # by the main table, and the kill switch lets the mark through. ${builders.mkTproxyRoutingUp { inherit ip; inherit ipv6; fwmark = globalTproxy.fwmark; table = globalTproxy.routeTable; }} + ${nft} -f ${nftablesRulesFile} + ${persistTable "singbox" "'include \"${nftablesRulesFile}\"'"} + ''; + + # After a firewall reload that flushed the ruleset (NixOS's flushRuleset, a distribution's + # `flush ruleset` config): the marking alone, swapped in whole in one transaction. The + # policy routing is no nftables state, and stays. + tproxyReloadScript = pkgs.writeShellScript "proxy-suite-routing" '' + set -euo pipefail + ${builders.mkNftReplaceTable { + inherit nft; + family = "inet"; + table = "singbox"; + file = nftablesRulesFile; + }} + ''; + + # The daemon guard (constants.daemonMetadataGuard) as loaded: a static table, so its + # listing loads again as it is. + persistDaemonGuardScript = pkgs.writeShellScript "proxy-suite-routing" '' + set -euo pipefail + rules=$(${nft} -s list table inet proxy_suite_daemon_guard) || exit 0 + ${persistTable "proxy_suite_daemon_guard" ''"$rules"''} ''; tproxyDownScript = pkgs.writeShellScript "proxy-suite-routing" '' set +e + ${unpersistTable "singbox"} ${builders.mkNftDeleteTable { inherit nft; family = "inet"; @@ -216,6 +306,7 @@ in table = tunAutoRouteTableIndex; }} ${deleteXrayTunRules} + ${unpersistTable xrayTunReplyTable} ${deleteXrayTunReplyTable} ${builders.mkIpRouteFlushTable { inherit ip; diff --git a/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq b/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq index 524c42b..6c5100b 100644 --- a/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq +++ b/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq @@ -1,10 +1,16 @@ -# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved. +# inbounds.routing.blockPrivate (or, without it, this host's loopback), enforced here because +# the listener passes names unresolved. # Just before the first direct rule (or last, for a direct final), so names that the # proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local # mixed-in clients lose names that resolve private. Rules for other inbounds do not count: # autoProxy's direct probe pin would put the guard first, resolving every name, .onion too. +# This host's own addresses too, its public one among them, on every port but those its +# clients may reach there (inbounds.serverPorts and the like): dialed from here, a service the +# firewall keeps from the internet would answer (the start script lists them). | [{inbound: ["mixed-in"], action: "resolve"@resolveStrategy@}, - {inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard + {inbound: ["mixed-in"]@rejectMatch@, action: "reject"}] + + (($ARGS.named.host_addresses // []) as $own + | if $own == [] or @hostPortsAllOpen@ then [] else [{inbound: ["mixed-in"], ip_cidr: $own@hostPortMatch@, action: "reject"}] end) as $guard | (.route.rules | map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null) | index(true)) as $first_direct 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 195fa41..42004d1 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 @@ -4,7 +4,11 @@ def sing_box_preserved_rules: and (((.inbound? // []) | index("xray-dns-in")) != null))]; # 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 +# Slurped (lists of one), not arguments: they grow with the outbounds and rules. +$route_rules[0] as $route_rules | $probe_inbounds[0] as $probe_inbounds +| $probe_pin_rules[0] as $probe_pin_rules | $autoproxy_rule_sets[0] as $autoproxy_rule_sets +| $autoproxy_rules[0] as $autoproxy_rules +| ([.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}] @@ -30,6 +34,13 @@ def is_pin: ((.outbound? // "") | type) == "string" and ((.outbound? // "") | st else . end | .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets) | .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules) + # What autoProxy sends through an exit is looked up through the proxy too, as every other + # proxied name is (proxy.dns.remote): not by the local resolver, in the clear, for a + # destination learned blocked. Its own rule-sets alone, which hold names only. + | .dns.rules = ((.dns.rules // []) + [$autoproxy_rules[] + | select((.outbound? // "direct") != "direct" + and ((.rule_set? // []) | all(startswith("autoproxy-"))) and ((.rule_set? // []) | length > 0)) + | {rule_set, server: "remote"}]) # 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)] diff --git a/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq b/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq index e01ecb3..0d508f0 100644 --- a/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq +++ b/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq @@ -13,7 +13,8 @@ def xray_rewrite_proxy_rule($single_tag): end; def xray_preserved_rules: [.routing.rules[] - | select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote")]; + | select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote" + or . == "inbounds-private-guard" or . == "inbounds-host-guard")]; def xray_final_rule($tag; $single_tag): if $tag == "proxy" and "@selectionMode@" == "urltest" then {type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag) @@ -42,7 +43,9 @@ def xray_pin_server_names: else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local") | . + {domains: ($names | map("full:" + .)), skipFallback: true}] end; -.outbounds = ($obs[0] + .outbounds) +# Slurped (a list of one), not an argument: it grows with the rules. +$route_rules[0] as $route_rules +| .outbounds = ($obs[0] + .outbounds) | if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end | if $auth_enabled then (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password" @@ -65,11 +68,25 @@ def xray_pin_server_names: # too: name the rest instead. Disabling is a runtime decision, so always. # ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop"; # rename one of them if that matters. - | if $ARGS.named.xray_selectable == null then . else - ($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates + # Slurped (a list of one), not an argument: every tag of a large subscription. + | ($ARGS.named.xray_selectable // [null])[0] as $selectable + | if $selectable == null then . else + ($selectable | map("proxy-suite-ob-" + .)) as $candidates | if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end | if .observatory then .observatory.subjectSelector = $candidates else . end end + # This host's own addresses, on every port but those its inbounds' clients may reach there, + # just after the inbounds' guard: dialed from here, its public one would reach a service + # the firewall keeps from the internet (the start script lists them). + | ($ARGS.named.host_addresses // []) as $own + | (.routing.rules | map((.ruleTag? // "") == "inbounds-private-guard") | index(true)) as $at + | if $own == [] or $at == null or "@hostClosedPorts@" == "" then . else + .routing.rules |= [.[] | select((.ruleTag? // "") != "inbounds-host-guard")] + | .routing.rules = .routing.rules[:$at + 1] + + [{type: "field", ruleTag: "inbounds-host-guard", inboundTag: ["mixed-in"], ip: $own, + port: "@hostClosedPorts@", outboundTag: "block"}] + + .routing.rules[$at + 1:] + end | if $xray_single_proxy_tag == "" then . else 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 62b519a..4ffb72e 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -4,17 +4,31 @@ selectionMode, proxyInboundsGuardPrivate, proxyInboundsGuardStrategy ? null, + # inbounds.routing.blockPrivate: the guard rejects the private ranges, else loopback alone. + proxyInboundsBlockPrivate ? true, + proxyInboundsLoopback ? [ ], + # The ports of this host's own addresses its inbounds' clients may not reach, as ranges. + proxyInboundsHostClosedPorts ? [ ], userDnsRules ? [ ], # proxy.dns.remote as a sing-box server, for the AmneziaWG interfaces added at runtime; null # when there are none. awgRuntimeDnsServer ? null, + # proxy.listener on an address other machines reach (0.0.0.0, a LAN address). + listenerExposed ? false, }: let fillTemplate = import ../../lib/fill-template.nix; + # XRay's port list: "80,1000-2000". + closedPorts = map ( + r: if r.from == r.to then toString r.from else "${toString r.from}-${toString r.to}" + ) proxyInboundsHostClosedPorts; in if pureXrayEnabled then - (fillTemplate ./backend-filter-xray.template.jq { inherit selectionMode; }) + (fillTemplate ./backend-filter-xray.template.jq { + inherit selectionMode; + hostClosedPorts = lib.concatStringsSep "," closedPorts; + }) else (fillTemplate ./backend-filter-sing-box.template.jq { userDnsRuleCount = toString (builtins.length userDnsRules); @@ -33,8 +47,45 @@ else + (if .routing_mark then {routing_mark} else {} end) ] '' + # A listener others reach, without the inbounds' guard: a LAN client could CONNECT to + # 127.0.0.1 (or a name resolving there), which the private-ranges rule sends direct, dialed + # from here: this host's loopback-only services. This host's own clients may still, and + # their names stay unresolved for the proxy. + + lib.optionalString (listenerExposed && !proxyInboundsGuardPrivate) '' + | {source_ip_cidr: ["127.0.0.0/8", "::1/128"], invert: true} as $remote + | [{type: "logical", mode: "and", rules: [{inbound: ["mixed-in"]}, $remote], + action: "resolve", server: "local"}, + {type: "logical", mode: "and", + rules: [{inbound: ["mixed-in"], ip_cidr: ${builtins.toJSON proxyInboundsLoopback}}, $remote], + action: "reject"}] as $guard + | (.route.rules + | map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null) + | index(true)) as $first_direct + | if $first_direct != null then + .route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:] + elif (.route.final // "direct") == "direct" then + .route.rules += $guard + else . end + '' + # No sniffing on mixed-in, where the inbounds' clients arrive: an SNI the rules send direct + # would take their connection direct to any address. Their names still route as names. + + lib.optionalString proxyInboundsGuardPrivate '' + | (.route.rules[]? | select(.action? == "sniff" and (has("inbound") | not))) + |= . + {inbound: ["mixed-in"], invert: true} + '' + lib.optionalString proxyInboundsGuardPrivate ( fillTemplate ./backend-filter-private-guard.template.jq { + rejectMatch = + if proxyInboundsBlockPrivate then + ", ip_is_private: true" + else + ", ip_cidr: ${builtins.toJSON proxyInboundsLoopback}"; + # sing-box's port_range is always from:to. + hostPortMatch = ", port_range: ${ + builtins.toJSON (map (r: "${toString r.from}:${toString r.to}") proxyInboundsHostClosedPorts) + }"; + # Then there is nothing to reject: no rule, as an empty port_range would match any port. + hostPortsAllOpen = lib.boolToString (proxyInboundsHostClosedPorts == [ ]); resolveStrategy = lib.optionalString ( proxyInboundsGuardStrategy != null ) ", strategy: \"${proxyInboundsGuardStrategy}\""; diff --git a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.template.sh b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.template.sh index d9c7c0e..1eeed92 100644 --- a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.template.sh +++ b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.template.sh @@ -55,7 +55,9 @@ _proxy_suite_write_xray_sidecar_config() { if [ "$(@jq@ 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then return 0 fi - @jq@ -n \ + # umask: the file holds every XRay outbound's credentials until the start script's + # chmod, in a runtime directory others can list. + (umask 077 && @jq@ -n \ --arg loglevel "$XRAY_LOGLEVEL" \ --argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \ --argjson port "$XRAY_SIDECAR_PORT" \ @@ -92,5 +94,5 @@ _proxy_suite_write_xray_sidecar_config() { domainStrategy: "AsIs", rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}]) } - }' > "$RUNTIME_DIR/xray-sidecar.json" + }' > "$RUNTIME_DIR/xray-sidecar.json") } diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index e97d0d2..23d9383 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -27,9 +27,17 @@ mkSubscriptionBlock, mkSubscriptionLoadHelperBlock, runtimeSubscriptionsBlock, + laterTags ? [ ], + # The backends, to check a runtime JSON outbound with before it joins the config. + singBoxBin ? null, + xrayBin ? null, }: let + # A value in a shell comment, on that one line: a newline in a tag (types.str) would end + # the comment and run the rest as root. + oneLine = value: builtins.replaceStrings [ "\n" "\r" ] [ " " " " ] (toString value); + sshProxyTag = "ssh-proxy"; torOutboundEnabled = torCfg != null && torCfg.enable && torCfg.asOutbound; groupsJq = builtins.path { @@ -41,12 +49,13 @@ let # The keys of an outbound that point the backend at a local file or program, comma-joined; # a sing-box tor outbound as "type: tor". proxy_url_parsers.local_file_keys and proxy-ctl's - # _local_file_keys apply the same rule. + # _local_file_keys apply the same rule. A non-ASCII key counts as well: Go's JSON + # decoding matches field names under Unicode case folding ("maſterKeyLog" is masterKeyLog). localFileKeysJq = '' [(if .type == "tor" then "type: tor" else empty end), (.. | objects | keys[] | ascii_downcase - | select(endswith("file") or (endswith("path") and . != "path") or endswith("directory") - or IN("masterkeylog", "torrc", "extra_args")))] + | select((explode | any(. > 127)) or endswith("file") or (endswith("path") and . != "path") + or endswith("directory") or IN("masterkeylog", "torrc", "extra_args")))] | unique | join(", ") ''; @@ -91,16 +100,24 @@ let case "$pref" in xray) ob=$(_proxy_suite_parse_xray_url "$tag" "$url") || return 1 + _proxy_suite_check_url_outbound xray "$ob" "$tag" "$source" || return 1 _proxy_suite_add_xray_sidecar_ob "$ob" "$tag" ;; sing-box) ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url") || return 1 + _proxy_suite_check_url_outbound sing-box "$ob" "$tag" "$source" || return 1 _proxy_suite_add_sing_box_ob "$ob" ;; *) - if ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url" 2>"$RUNTIME_DIR/sing-box-parser.err"); then + # Created 0600 first: the parser's error can quote the link's id or password, + # and the runtime directory is world-listable. + (umask 077 && : > "$RUNTIME_DIR/sing-box-parser.err") + # One sing-box parses but refuses still gets XRay's turn. + if ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url" 2>"$RUNTIME_DIR/sing-box-parser.err") && + _proxy_suite_check_url_outbound sing-box "$ob" "$tag" "$source" 2>/dev/null; then _proxy_suite_add_sing_box_ob "$ob" elif ob=$(_proxy_suite_parse_xray_url "$tag" "$url"); then + _proxy_suite_check_url_outbound xray "$ob" "$tag" "$source" || return 1 _proxy_suite_add_xray_sidecar_ob "$ob" "$tag" else echo "proxy-suite: outbound '$tag' cannot be parsed by SingBox or XRay" >&2 @@ -115,6 +132,9 @@ let else '' ob=$(_proxy_suite_parse_url "$tag" "$url") || return 1 + _proxy_suite_check_url_outbound ${ + if pureXrayEnabled then "xray" else "sing-box" + } "$ob" "$tag" "$source" || return 1 OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON") ''; # Raw JSON gets the tag and the routing mark a Nix-declared one gets (rawOutboundJson). @@ -166,14 +186,17 @@ let "" | *[!0-9]*) return 1 ;; esac [ "$2" -ge 1 ] && [ "$2" -le 65535 ] || return 1 - ob=$(${jq} -nc --arg t "$1" --argjson p "$2" ${ - lib.escapeShellArg ( - if pureXrayEnabled then - ''{protocol: "socks", tag: $t, settings: {address: "127.0.0.1", port: $p}}'' - else - ''{type: "socks", tag: $t, server: "127.0.0.1", server_port: $p}'' - ) - }) || return 1 + # The tunnel's listener takes the hop login (constants.ensureHopLogin). + ${constants.ensureHopLogin pkgs} + ob=$(${jq} -nc --arg t "$1" --argjson p "$2" --arg u ${constants.hopUser} \ + --rawfile pw ${lib.escapeShellArg constants.hopLoginFile} ${ + lib.escapeShellArg ( + if pureXrayEnabled then + ''{protocol: "socks", tag: $t, settings: {address: "127.0.0.1", port: $p, user: $u, pass: ($pw | rtrimstr("\n"))}}'' + else + ''{type: "socks", tag: $t, server: "127.0.0.1", server_port: $p, username: $u, password: ($pw | rtrimstr("\n"))}'' + ) + }) || return 1 ${ if hybridEnabled then ''_proxy_suite_add_sing_box_ob "$ob"'' @@ -219,19 +242,25 @@ let # written before links existed: those entries share as JSON until the next update). _proxy_suite_record_subscription_share() { SUBSCRIPTION_URLS_JSON=$(${jq} --arg t "$1" --rawfile u <(_proxy_suite_read_source "$2") '.[$t] = ($u | rtrimstr("\n"))' <<< "$SUBSCRIPTION_URLS_JSON") + # Only the entries merged (_proxy_suite_record_outbound_source ran first): one left + # out for a taken tag would otherwise put its link on that tag's outbound. if [ -s "$3" ]; then - OUTBOUND_URLS_JSON=$(${jq} --slurpfile l "$3" '. + $l[0]' <<< "$OUTBOUND_URLS_JSON") || true + OUTBOUND_URLS_JSON=$(${jq} --slurpfile l "$3" --arg s "sub:$1" \ + --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \ + '. + ($l[0] | with_entries(select($sources[0][.key] == $s)))' <<< "$OUTBOUND_URLS_JSON") || true fi } # $1 source label, $2 array length before the add, $3 after. Subscriptions # append an unknown number of outbounds, so they label them by range. + # Here and below, whatever grows with the outbounds goes to jq through a file, not + # --argjson: a big subscription outgrows the kernel's 128 KiB limit on one argument. _proxy_suite_record_outbound_source() { [ "$3" -gt "$2" ] || return 0 OUTBOUND_SOURCES_JSON=$(${jq} \ - --argjson sources "$OUTBOUND_SOURCES_JSON" --arg s "$1" \ + --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") --arg s "$1" \ --argjson b "$2" --argjson a "$3" \ - 'reduce .[$b:$a][].tag as $t ($sources; .[$t] = $s)' <<< "$OUTBOUNDS_JSON") + 'reduce .[$b:$a][].tag as $t ($sources[0]; .[$t] = $s)' <<< "$OUTBOUNDS_JSON") } ${ @@ -256,6 +285,15 @@ let } '' } + # $1 kind, $2 the outbound parsed from a URL, $3 tag, $4 source label: a runtime one + # through the backend's own check, as for runtime JSON. + _proxy_suite_check_url_outbound() { + [ "$4" = runtime ] || return 0 + _proxy_suite_check_json_outbound "$1" "$2" && return 0 + echo "proxy-suite: runtime outbound '$3' is not one the backend takes" >&2 + return 1 + } + # $1 tag, $2 URL, $3 source label, $4 backend preference (auto|sing-box|xray). # Returns non-zero when the URL cannot be parsed; the caller decides whether # that is fatal. @@ -266,6 +304,28 @@ let OUTBOUND_URLS_JSON=$(${jq} --arg t "$tag" --rawfile u <(printf '%s' "$url") '.[$t] = $u' <<< "$OUTBOUND_URLS_JSON") } + # $1 kind, $2 the outbound: whether its backend takes it, as one it refuses would fail + # the whole start. Alone (its references dropped), as the service user, from stdin. + _proxy_suite_check_json_outbound() { + local kind="$1" ob="$2" as=() + [ "$(${pkgs.coreutils}/bin/id -u)" = 0 ] && as=(${constants.runAsServiceUser pkgs [ ]}) + case "$kind" in + ${lib.optionalString (singBoxBin != null) '' + sing-box) + ${jq} -c '{outbounds: [del(.detour, .domain_resolver) | select(.type != "selector" and .type != "urltest")]}' <<< "$ob" \ + | "''${as[@]}" ${singBoxBin} check -c /dev/stdin >/dev/null 2>&1 + ;; + ''} + ${lib.optionalString (xrayBin != null) '' + xray) + ${jq} -c '{outbounds: [del(.proxySettings) | del(.streamSettings.sockopt.dialerProxy)]}' <<< "$ob" \ + | "''${as[@]}" ${xrayBin} run -test -format json -c stdin: >/dev/null 2>&1 + ;; + ''} + *) return 0 ;; + esac + } + # $1 tag, $2 file holding one sing-box or XRay outbound, $3 source label. _proxy_suite_add_json_outbound() { local tag="$1" source="$3" ob kind unsafe @@ -282,6 +342,10 @@ let fi fi kind=$(${jq} -r 'if has("protocol") then "xray" elif has("type") then "sing-box" else "" end' <<< "$ob") + if [ "$source" = runtime ] && ! _proxy_suite_check_json_outbound "$kind" "$ob"; then + echo "proxy-suite: runtime outbound '$tag' is not one the backend takes (a field misspelt, or one it no longer has)" >&2 + return 1 + fi ${jsonAddBlock} _proxy_suite_record_tag_source "$tag" "$source" } @@ -297,8 +361,16 @@ let [ -f "$f" ] && [ ! -L "$f" ] || continue tag="''${f##*/}" tag="''${tag%.*}" + # A tab or newline in a name would split the line into entries of its own. + if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then + echo "proxy-suite: warning: ignoring a runtime outbound whose name is not a valid tag" >&2 + continue + fi case "$tag" in - proxy | direct | block${lib.optionalString torOutboundEnabled " | tor"}) + # proxy-suite-*: the test selector and the pin selectors the start script adds; + # priority.json is the priority overrides, not an outbound. + proxy | direct | block | priority | proxy-suite-*${lib.optionalString torOutboundEnabled " | tor"}) + [ "$f" = "${runtimeOutboundsDir}/priority.json" ] && continue echo "proxy-suite: warning: ignoring runtime outbound '$tag': reserved name" >&2 continue ;; @@ -316,7 +388,7 @@ let jsonFile = pkgs.writeText "proxy-suite-core" outboundJson; in '' - # outbound: ${tag} (static ${backend} json) + # outbound: ${oneLine tag} (static ${backend} json) OB_JSON=$(cat "${jsonFile}") OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON") _proxy_suite_record_tag_source ${lib.escapeShellArg tag} static @@ -326,8 +398,8 @@ let urlSource = if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-core" ob.url; in '' - # outbound: ${tag} - _proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static || exit 1 + # outbound: ${oneLine tag} + _proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat ${lib.escapeShellArg urlSource})" static || exit 1 ''; singBoxRawOutboundJson = @@ -347,7 +419,7 @@ let jsonFile = pkgs.writeText "proxy-suite-core" outboundJson; in '' - # outbound: ${tag} (hybrid XRay json sidecar) + # outbound: ${oneLine tag} (hybrid XRay json sidecar) OB_JSON=$(cat "${jsonFile}") _proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag} _proxy_suite_record_tag_source ${lib.escapeShellArg tag} static @@ -358,7 +430,7 @@ let jsonFile = pkgs.writeText "proxy-suite-core" outboundJson; in '' - # outbound: ${tag} (hybrid SingBox json) + # outbound: ${oneLine tag} (hybrid SingBox json) OB_JSON=$(cat "${jsonFile}") _proxy_suite_add_sing_box_ob "$OB_JSON" _proxy_suite_record_tag_source ${lib.escapeShellArg tag} static @@ -368,8 +440,8 @@ let urlSource = if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-core" ob.url; in '' - # outbound: ${tag} (hybrid ${ob.backend}) - _proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static ${ob.backend} || exit 1 + # outbound: ${oneLine tag} (hybrid ${ob.backend}) + _proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat ${lib.escapeShellArg urlSource})" static ${ob.backend} || exit 1 ''; mkSshProxyOutboundBlock = @@ -420,7 +492,7 @@ let -f ${lib.escapeShellArg sshProxyCfg.hostKeyFile} \ | ${jq} -R -s '[splits("\n")] | map(select(length > 0 and (startswith("#") | not))) | map(sub("^\\S+\\s+"; ""))') if [ "$(${jq} 'length' <<< "$SSH_HOST_KEYS")" -eq 0 ]; then - echo "proxy-suite: no host keys for ${knownHostsTarget} in ${sshProxyCfg.hostKeyFile}" >&2 + echo "proxy-suite: no host keys for "${lib.escapeShellArg knownHostsTarget}" in "${lib.escapeShellArg sshProxyCfg.hostKeyFile} >&2 exit 1 fi OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON") @@ -433,7 +505,9 @@ let # sing-box opens the key as ${constants.serviceUser}, which cannot read a key in a # home directory: it gets a copy only root and its group can read. SSH_IDENTITY="$RUNTIME_DIR/ssh-identity" - install -m 0640 ${constants.ifPrivileged "-g ${constants.serviceUser} "}${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY" + install -m ${ + if constants.privileged then "0640" else "0600" + } ${constants.ifPrivileged "-g ${constants.serviceUser} "}${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY" OB_JSON=$(${jq} --arg key "$SSH_IDENTITY" '.private_key_path = $key' <<< "$OB_JSON") ''} ${hostKeyFileBlock} @@ -448,7 +522,7 @@ let # Outbounds whose JSON is known at build time: every backend takes it as is. mkFixedOutboundBlock = comment: source: outbound: '' - # outbound: ${outbound.tag} (${comment}) + # outbound: ${oneLine outbound.tag} (${comment}) OB_JSON=${lib.escapeShellArg (builtins.toJSON outbound)} ${ if hybridEnabled then @@ -459,28 +533,52 @@ let _proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source} ''; + # As mkFixedOutboundBlock, with the hop login added at start: it is drawn per boot, and + # the password reaches jq from its file, never argv. + mkHopOutboundBlock = comment: source: outbound: '' + # outbound: ${oneLine outbound.tag} (${comment}) + ${constants.ensureHopLogin pkgs} + OB_JSON=$(${jq} -c --arg u ${constants.hopUser} --rawfile pw ${lib.escapeShellArg constants.hopLoginFile} ${ + lib.escapeShellArg ( + if pureXrayEnabled then + ''.settings += {user: $u, pass: ($pw | rtrimstr("\n"))}'' + else + ''. + {username: $u, password: ($pw | rtrimstr("\n"))}'' + ) + } <<< ${lib.escapeShellArg (builtins.toJSON outbound)}) + ${ + if hybridEnabled then + ''_proxy_suite_add_sing_box_ob "$OB_JSON"'' + else + ''OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")'' + } + _proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source} + ''; + # WARP and "singBox" or "userspace" AmneziaWG profiles run in a tunnel unit, which restarts them when the # handshake stops being answered. Every backend reaches it as a loopback SOCKS hop. + # Every hop but Tor's takes the hop login (constants.ensureHopLogin); Tor has none to take. mkTunnelOutboundBlock = unit: source: tag: port: - mkFixedOutboundBlock "SOCKS hop to ${unit}" source ( - if pureXrayEnabled then - { - protocol = "socks"; - inherit tag; - settings = { - address = "127.0.0.1"; - inherit port; - }; - } - else - { - type = "socks"; - inherit tag; - server = "127.0.0.1"; - server_port = port; - } - ); + (if source == "tor" then mkFixedOutboundBlock else mkHopOutboundBlock) "SOCKS hop to ${unit}" source + ( + if pureXrayEnabled then + { + protocol = "socks"; + inherit tag; + settings = { + address = "127.0.0.1"; + inherit port; + }; + } + else + { + type = "socks"; + inherit tag; + server = "127.0.0.1"; + server_port = port; + } + ); # An "interface" AmneziaWG profile: the outbound binds to the interface, which has no routes. # sing-box resolves its destinations through it too; XRay resolves as usual. @@ -532,11 +630,31 @@ let mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock; + # Tags a runtime outbound may not take: the outbounds added after it, the groups (declared + # and runtime), and the backend template's own. Those already in (declared, subscriptions, + # an earlier runtime one under another extension) are checked as it comes. + runtimeTakenTags = laterTags ++ lib.optional pureXrayEnabled "dns-out"; runtimeOutboundsBlock = '' # outbounds added at runtime, and the hop each one chains through (.detour) RUNTIME_DETOURS_JSON='{}' + RUNTIME_TAKEN_JSON=$( + for f in "${runtimeOutboundsDir}"/*.group; do + [ -e "$f" ] || continue + f="''${f##*/}" + printf '%s\n' "''${f%.group}" + done | ${jq} -R . | ${jq} -cs --argjson fixed ${lib.escapeShellArg (builtins.toJSON runtimeTakenTags)} '. + $fixed' + ) while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do [ -n "$RUNTIME_OB_TAG" ] || continue + # A duplicate tag fails the backend's start, every outbound with it: this one goes. + if { + printf '%s\n' "''${OUTBOUNDS_JSON:-[]}" + ${lib.optionalString hybridEnabled ''printf '%s\n' "''${XRAY_OUTBOUNDS_JSON:-[]}"''} + } | ${jq} -e -s --arg t "$RUNTIME_OB_TAG" --argjson taken "$RUNTIME_TAKEN_JSON" \ + '(add | [.[].tag]) + $taken | index([$t]) != null' >/dev/null 2>&1; then + echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG': the tag is taken" >&2 + continue + fi 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. @@ -581,24 +699,25 @@ let # unchained; whatever chained through it is checked again. detourBlock = '' # outbound chaining - DETOURS_JSON=$(${jq} -c --argjson runtime "$RUNTIME_DETOURS_JSON" '.outbounds = $runtime + .outbounds' \ + DETOURS_JSON=$(${jq} -c --slurpfile runtime <(printf '%s' "$RUNTIME_DETOURS_JSON") '.outbounds = $runtime[0] + .outbounds' \ <<< ${lib.escapeShellArg (builtins.toJSON detours)}) while [ "$DETOURS_JSON" != '{"outbounds":{},"subscriptions":{}}' ]; do + # The filter reads $sources as the object itself, so the program unwraps the slurped one. DETOUR_RESULT=$(${jq} -c --slurpfile xob <(printf '%s' "${ if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]" }") '{outbounds: ., xray: $xob[0]}' <<< "$OUTBOUNDS_JSON" \ - | ${jq} -c -f ${ + | ${jq} -c -f <(printf '%s' '$sources[0] as $sources | '; cat ${ builtins.path { name = "proxy-suite-outbound-detours"; path = ../../outbound-detours.jq; } - } \ + }) \ --argjson d "$DETOURS_JSON" \ - --argjson sources "$OUTBOUND_SOURCES_JSON" \ + --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \ --arg kind ${detourKind}) - DETOUR_DROP=$(${jq} -c --argjson sources "$OUTBOUND_SOURCES_JSON" \ - '[.errors[] | select($sources[.tag] == "runtime")] | unique_by(.tag)' <<< "$DETOUR_RESULT") - if ${jq} -e --argjson sources "$OUTBOUND_SOURCES_JSON" 'any(.errors[]; $sources[.tag] != "runtime")' <<< "$DETOUR_RESULT" >/dev/null; then + DETOUR_DROP=$(${jq} -c --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \ + '[.errors[] | select($sources[0][.tag] == "runtime")] | unique_by(.tag)' <<< "$DETOUR_RESULT") + if ${jq} -e --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") 'any(.errors[]; $sources[0][.tag] != "runtime")' <<< "$DETOUR_RESULT" >/dev/null; then ${jq} -r '.errors[] | "proxy-suite: " + .message' <<< "$DETOUR_RESULT" >&2 exit 1 fi @@ -638,7 +757,7 @@ let DISABLED_TAGS_JSON=$(${jq} -c --arg t "''${DISABLED_TAG%.disabled}" '. + [$t]' <<< "$DISABLED_TAGS_JSON") done fi - DISABLED_TAGS_JSON=$(${jq} -c --argjson tags "$OUTBOUND_TAGS_JSON" 'map(select(. as $t | $tags | index([$t]))) | unique' <<< "$DISABLED_TAGS_JSON") + DISABLED_TAGS_JSON=$(${jq} -c --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") 'map(select(. as $t | $tags[0] | index([$t]))) | unique' <<< "$DISABLED_TAGS_JSON") ''; # proxy.groups and those `proxy-ctl proxy groups add` left as .group next to the runtime @@ -671,7 +790,7 @@ let # As proxy-ctl names them; the spool is group-writable, and a group tagged "proxy" # would shadow the real selector. case "$GROUP_NAME" in - proxy | direct | block${lib.optionalString torOutboundEnabled " | tor"} | [!A-Za-z0-9]* | *[!A-Za-z0-9._-]*) + proxy | direct | block | proxy-suite-*${lib.optionalString torOutboundEnabled " | tor"} | [!A-Za-z0-9]* | *[!A-Za-z0-9._-]*) echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': reserved or invalid name" >&2 continue ;; @@ -713,12 +832,13 @@ let while IFS= read -r GROUP_NAME; do echo "proxy-suite: warning: ignoring group '$GROUP_NAME': an outbound has that tag" >&2 GROUPS_CONFIG_JSON=$(${jq} -c --arg g "$GROUP_NAME" 'del(.[$g])' <<< "$GROUPS_CONFIG_JSON") - done < <(${jq} -r --argjson tags "$OUTBOUND_TAGS_JSON" 'keys[] | select(. as $g | $tags | index([$g]))' <<< "$GROUPS_CONFIG_JSON") + done < <(${jq} -r --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") 'keys[] | select(. as $g | $tags[0] | index([$g]))' <<< "$GROUPS_CONFIG_JSON") # A runtime group inside itself is left out, like any runtime outbound that cannot be # built; only a loop among declared groups fails the start. while :; do - GROUPS_RESULT=$(${jq} -nc --argjson tags "$OUTBOUND_TAGS_JSON" --argjson sources "''${OUTBOUND_SOURCES_JSON:-{\}}" \ - '{tags: $tags, sources: $sources}' \ + GROUPS_RESULT=$(${jq} -nc --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") \ + --slurpfile sources <(printf '%s' "''${OUTBOUND_SOURCES_JSON:-{\}}") \ + '{tags: $tags[0], sources: $sources[0]}' \ | ${jq} -c -f ${groupsJq} \ --argjson groups "$GROUPS_CONFIG_JSON" \ --argjson priority "$PRIORITY_JSON" \ @@ -741,7 +861,7 @@ let GROUP_TAGS_JSON=$(${jq} -c '.groups | keys_unsorted' <<< "$GROUPS_RESULT") GROUPS_INFO_JSON=$(${jq} -c '.groups' <<< "$GROUPS_RESULT") TOP_TAGS_JSON=$(${jq} -c '.top' <<< "$GROUPS_RESULT") - OUTBOUNDS_JSON=$(${jq} -c --argjson g "$(${jq} -c '.outbounds' <<< "$GROUPS_RESULT")" '. + $g' <<< "$OUTBOUNDS_JSON") + OUTBOUNDS_JSON=$(${jq} -c --slurpfile g <(${jq} -c '.outbounds' <<< "$GROUPS_RESULT") '. + $g[0]' <<< "$OUTBOUNDS_JSON") ''; pinBlock = '' @@ -778,19 +898,21 @@ let # chains through, what selection leaves alone, and what was disabled. inventoryBlock = '' ${jq} -n \ - --argjson tags "$OUTBOUND_TAGS_JSON" \ - --argjson sources "$OUTBOUND_SOURCES_JSON" \ + --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") \ + --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \ --arg pinned "$PINNED_OUTBOUND" \ --arg selection ${lib.escapeShellArg selectionMode} \ --slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \ --slurpfile xobs <(printf '%s' "${if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"}") \ - --argjson selectable "$SELECTABLE_TAGS_JSON" \ + --slurpfile selectable <(printf '%s' "$SELECTABLE_TAGS_JSON") \ --argjson disabled "$DISABLED_TAGS_JSON" \ - --argjson groups "$GROUPS_INFO_JSON" \ - --argjson top "$TOP_TAGS_JSON" \ + --slurpfile groups <(printf '%s' "$GROUPS_INFO_JSON") \ + --slurpfile top <(printf '%s' "$TOP_TAGS_JSON") \ --argjson priority "$PRIORITY_JSON" \ --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \ - '{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection, + '$tags[0] as $tags | $sources[0] as $sources | $selectable[0] as $selectable + | $groups[0] as $groups | $top[0] as $top + | {tags: $tags, sources: $sources, pinned: $pinned, selection: $selection, detours: ([($xobs[0] + $obs[0])[] | (.detour // .streamSettings.sockopt.dialerProxy?) as $h | select($h != null) | {key: .tag, value: $h}] | from_entries), excluded: ($top - $selectable), disabled: $disabled, @@ -864,17 +986,17 @@ let if [ -z "$PINNED_OUTBOUND" ] && [ "''${GROUPS_WATCHED:-true}" != true ]; then # No Clash API here for the watcher to drive: sing-box's own urltest instead. WRAPPER=$(${jq} -n \ - --argjson tags "$SELECTABLE_TAGS_JSON" \ + --slurpfile tags <(printf '%s' "$SELECTABLE_TAGS_JSON") \ --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \ --argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \ - '{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:"30s",tolerance:$tolerance}') + '{type:"urltest",tag:"proxy",outbounds:$tags[0],url:$url,interval:"30s",tolerance:$tolerance}') else WRAPPER=$(${jq} -n \ - --argjson tags "$TAGS" \ + --slurpfile tags <(printf '%s' "$TAGS") \ --arg default "$DEFAULT_TAG" \ - '{type:"selector",tag:"proxy",outbounds:$tags,default:$default,interrupt_exist_connections:true}') + '{type:"selector",tag:"proxy",outbounds:$tags[0],default:$default,interrupt_exist_connections:true}') fi - OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") + OUTBOUNDS_JSON=$(${jq} --slurpfile w <(printf '%s' "$WRAPPER") '$w + .' <<< "$OUTBOUNDS_JSON") '' else if selectionMode == "selector" then '' @@ -884,10 +1006,10 @@ let DEFAULT_TAG=$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON") fi WRAPPER=$(${jq} -n \ - --argjson tags "$TAGS" \ + --slurpfile tags <(printf '%s' "$TAGS") \ --arg default "$DEFAULT_TAG" \ - '{type:"selector",tag:"proxy",outbounds:$tags,default:$default}') - OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") + '{type:"selector",tag:"proxy",outbounds:$tags[0],default:$default}') + OUTBOUNDS_JSON=$(${jq} --slurpfile w <(printf '%s' "$WRAPPER") '$w + .' <<< "$OUTBOUNDS_JSON") '' else '' @@ -896,18 +1018,18 @@ let # A pin beats latency ranking: the same outbounds, behind a selector # the Clash API can also switch live. WRAPPER=$(${jq} -n \ - --argjson tags "$TAGS" \ + --slurpfile tags <(printf '%s' "$TAGS") \ --arg default "$PINNED_OUTBOUND" \ - '{type:"selector",tag:"proxy",outbounds:$tags,default:$default}') + '{type:"selector",tag:"proxy",outbounds:$tags[0],default:$default}') else WRAPPER=$(${jq} -n \ - --argjson tags "$SELECTABLE_TAGS_JSON" \ + --slurpfile tags <(printf '%s' "$SELECTABLE_TAGS_JSON") \ --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \ --arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \ --argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \ - '{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}') + '{type:"urltest",tag:"proxy",outbounds:$tags[0],url:$url,interval:$interval,tolerance:$tolerance}') fi - OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") + OUTBOUNDS_JSON=$(${jq} --slurpfile w <(printf '%s' "$WRAPPER") '$w + .' <<< "$OUTBOUNDS_JSON") ''; # Real exits for autoProxy, taken after the wrapper may have renamed one to # "proxy". diff --git a/modules/proxy-suite/service/script-blocks/subscription-cache-helpers.template.sh b/modules/proxy-suite/service/script-blocks/subscription-cache-helpers.template.sh index 29befdc..8a9cde4 100644 --- a/modules/proxy-suite/service/script-blocks/subscription-cache-helpers.template.sh +++ b/modules/proxy-suite/service/script-blocks/subscription-cache-helpers.template.sh @@ -2,6 +2,11 @@ SUB_CACHE_DIR="@cacheDir@" RUNTIME_SUBS_DIR="@runtimeSubscriptionsDir@" +# The caches hold every server's credentials and original link: root and, with the +# "secrets" scope, the userControl groups only, as for the share file. +mkdir -p "$SUB_CACHE_DIR" +@cacheDirAccess@ + _proxy_suite_valid_subscription_cache() { [ -s "$1" ] && @jq@ -e @validCacheFilter@ "$1" >/dev/null 2>&1 } @@ -34,34 +39,72 @@ _proxy_suite_drop_invalid_subscription_cache() { fi } -# $1 tag, $2 file holding the subscription URL. Writes the cache atomically, -# and next to it .links: each entry's original URI, for proxy-ctl to share. +# $1 "direct" to fetch as the service user, past the kill switch and outside the tunnel; +# otherwise as an unprivileged user the tunnel and the kill switch take as they take root. +# Root opens the output files either way (the links on fd 3). +_proxy_suite_run_fetcher() { + local how="$1" tag="$2" src="$3" cache_tmp="$4" links_tmp="$5" as=(@tunnelFetch@) + shift 5 + [ "$how" = direct ] && as=(@directFetch@) + printf '%s' "$(_proxy_suite_read_source "$src")" \ + | PYTHONPATH="@pythonPath@" "${as[@]}" @python3@ @fetchSubscriptionPy@ \ + @backendArg@ --tag-prefix "$tag" --links-fd 3 "$@" > "$cache_tmp" 3> "$links_tmp" +} + +# A temporary file of its own next to $1: the start scripts share the directory and fetch at +# once. Readable as the caches always were; the directory's mode keeps others out. +_proxy_suite_cache_tmp() { + local tmp + tmp=$(mktemp "$1.XXXXXX") || return 1 + chmod 0644 "$tmp" + printf '%s' "$tmp" +} + +# $1 tag, $2 file holding the subscription URL, then the fetcher's flags. Writes the cache +# atomically, and .links for proxy-ctl to share. Through the tunnel; directly past the +# kill switch only with no cache, which has no proxy to fetch through. _proxy_suite_fetch_subscription() { - local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links" - mkdir -p "$SUB_CACHE_DIR" - if printf '%s' "$(_proxy_suite_read_source "$src")" \ - | PYTHONPATH="@pythonPath@" @python3@ @fetchSubscriptionPy@ \ - @backendArg@ --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then - if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then - mv "$links.tmp" "$links" + local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links" cache_tmp links_tmp + # What a fetch killed midway (a stop's timeout) left behind. + @findutils@/bin/find "$SUB_CACHE_DIR" -maxdepth 1 -type f \( -name "$tag.json.??????" -o -name "$tag.links.??????" \) \ + -mmin +10 -delete 2>/dev/null || true + cache_tmp=$(_proxy_suite_cache_tmp "$cache") || return 1 + links_tmp=$(_proxy_suite_cache_tmp "$links") || { rm -f "$cache_tmp"; return 1; } + if _proxy_suite_run_fetcher tunnel "$tag" "$src" "$cache_tmp" "$links_tmp" "${@:3}" || + { @killSwitch@ && ! _proxy_suite_valid_subscription_cache "$cache" && + echo "proxy-suite: subscription '$tag' not fetched through the tunnel and not cached; fetching it directly, past the kill switch" >&2 && + _proxy_suite_run_fetcher direct "$tag" "$src" "$cache_tmp" "$links_tmp" "${@:3}"; }; then + if _proxy_suite_commit_subscription_cache "$cache_tmp" "$cache" "$tag"; then + mv "$links_tmp" "$links" return 0 fi - rm -f "$links.tmp" + rm -f "$links_tmp" return 1 fi - rm -f "$cache.tmp" "$links.tmp" + rm -f "$cache_tmp" "$links_tmp" echo "proxy-suite: failed to update subscription '$tag'" >&2 return 1 } -# Every runtime subscription, as "\t" lines. +# Every runtime subscription, as "\t" lines. Checked again here, as the spool +# is group-writable: a declared subscription's name would take over its cache. _proxy_suite_runtime_subscriptions() { - local f tag + local f tag declared [ -d "$RUNTIME_SUBS_DIR" ] || return 0 for f in "$RUNTIME_SUBS_DIR"/*.url; do [ -f "$f" ] && [ ! -L "$f" ] || continue tag="${f##*/}" tag="${tag%.url}" + if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ || $tag == proxy-suite-* ]]; then + echo "proxy-suite: warning: ignoring a runtime subscription whose name is not a valid tag" >&2 + continue + fi + for declared in @declaredTags@; do + if [ "$tag" = "$declared" ]; then + echo "proxy-suite: warning: ignoring runtime subscription '$tag': a declared one has that name" >&2 + continue 2 + fi + done printf '%s\t%s\n' "$tag" "$f" done } diff --git a/modules/proxy-suite/service/script-blocks/subscriptions.nix b/modules/proxy-suite/service/script-blocks/subscriptions.nix index 311509b..7ae791c 100644 --- a/modules/proxy-suite/service/script-blocks/subscriptions.nix +++ b/modules/proxy-suite/service/script-blocks/subscriptions.nix @@ -21,9 +21,17 @@ let fetchSubscriptionPy routingMarkJq ; - inherit (constants) stateDir runtimeSubscriptionsDir; + inherit (constants) stateDir runtimeSubscriptionsDir runtimeOutboundsDir; + # Outbounds and groups the start script adds after the subscriptions, which a subscription + # entry must not take the tag of. + laterTagsJson = builtins.toJSON (ctx.effectiveOutboundTags ++ ctx.groupTags); subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend; - subscriptionBackendArg = "--backend ${subscriptionBackend}"; + # Each entry also through its backend's own config check: one it refuses would fail the + # whole start, every other outbound with it. + subscriptionBackendArg = + "--backend ${subscriptionBackend}" + + lib.optionalString (subscriptionBackend != "xray") " --check-sing-box ${ctx.singBox}" + + lib.optionalString (subscriptionBackend != "sing-box") " --check-xray ${ctx.xray}"; subscriptionCacheDir = "${stateDir}/subscriptions/${backend}"; mkSubscriptionUrlSource = @@ -35,16 +43,53 @@ let readSourceFunction = constants.readSourceFunction pkgs; cacheDir = subscriptionCacheDir; inherit runtimeSubscriptionsDir jq; + declaredTags = lib.escapeShellArgs (map (sub: sub.tag) proxyCfg.subscriptions); validCacheFilter = lib.escapeShellArg ( if hybridEnabled then ''type == "object" and (.singBox | type == "array") and (.xray | type == "array")'' else ''type == "array"'' ); - diffutils = pkgs.diffutils; + inherit (pkgs) diffutils findutils; + # The directory alone, not what is in it (constants.grantDirAcl): the caches are 0644, and + # a recursive pass would trip over another start script's temporary file. + cacheDirAccess = + let + secrets = ctx.userControlAllows "secrets"; + extraGroups = ctx.userControlExtraGroupsFor "secrets"; + in + lib.optionalString secrets '' + ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg ctx.userControlCfg.group} "$SUB_CACHE_DIR" + '' + + '' + chmod ${if secrets then "0750" else "0700"} "$SUB_CACHE_DIR" + '' + + constants.ifPrivileged ( + if extraGroups == [ ] then + ''${pkgs.acl}/bin/setfacl -b -- "$SUB_CACHE_DIR"'' + else + ''${pkgs.acl}/bin/setfacl --set ${ + lib.concatStringsSep "," ( + [ + "u::rwx" + "g::${if secrets then "r-x" else "---"}" + "o::---" + ] + ++ map (g: "g:${g}:r-x") extraGroups + ) + } -- "$SUB_CACHE_DIR"'' + ); pythonPath = parserScriptsPythonPath; inherit python3 fetchSubscriptionPy; backendArg = subscriptionBackendArg; + killSwitch = lib.boolToString ctx.killSwitchDirectFallbacks; + # Its own user, not exempt from the tunnel or the kill switch: the HTTP client and the + # parser of what any subscription server sends do not run as root. + tunnelFetch = constants.ifPrivileged "${pkgs.util-linux}/bin/setpriv --reuid=${ctx.subscriptionFetchUser} --regid=${ctx.subscriptionFetchUser} --clear-groups --inh-caps=-all --ambient-caps=-all --bounding-set=-all --no-new-privs --"; + # Past the kill switch as the service user, resolving names itself (constants.ownLookups). + directFetch = lib.optionalString ctx.killSwitchDirectFallbacks "${pkgs.util-linux}/bin/unshare --mount ${constants.ownLookups pkgs} ${ + constants.runAsServiceUser pkgs [ ] + }"; }; # Merging a cache into OUTBOUNDS_JSON needs the routing mark, which differs per @@ -62,25 +107,54 @@ let mergeBlock = if hybridEnabled then '' - SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$cache") + SUB_SING_BOX_JSON=$(_proxy_suite_free_tags "$tag" < <(${jq} -c '.singBox' "$cache")) ${markBlock}OUTBOUNDS_JSON=$(${jq} --slurpfile sub <(printf '%s' "$SUB_SING_BOX_JSON") '. + $sub[0]' <<< "$OUTBOUNDS_JSON") - _proxy_suite_add_xray_sidecar_obs "$(${jq} -c '.xray' "$cache")" + _proxy_suite_add_xray_sidecar_obs "$(_proxy_suite_free_tags "$tag" < <(${jq} -c '.xray' "$cache"))" '' else '' - SUB_JSON=$(cat "$cache") + SUB_JSON=$(_proxy_suite_free_tags "$tag" < "$cache") ${markBlock}OUTBOUNDS_JSON=$(${jq} --slurpfile sub <(printf '%s' "$SUB_JSON") '. + $sub[0]' <<< "$OUTBOUNDS_JSON") ''; in '' - # $1 tag, $2 file holding the subscription URL. Fetches on a cold cache and - # merges whatever is cached; a subscription that cannot be fetched is a + # stdin: a subscription's outbounds; prints those whose tag is free. A taken one (by any + # other outbound, a group or the suite's own) would fail the backend's start. + _proxy_suite_free_tags() { + local entries taken f name + entries=$(cat) + taken=$( + { + ${jq} -r 'map(.tag) | .[]' <<< "$OUTBOUNDS_JSON" + if [ -d ${lib.escapeShellArg runtimeOutboundsDir} ]; then + for f in ${lib.escapeShellArg runtimeOutboundsDir}/*.url ${lib.escapeShellArg runtimeOutboundsDir}/*.json \ + ${lib.escapeShellArg runtimeOutboundsDir}/*.awg ${lib.escapeShellArg runtimeOutboundsDir}/*.group; do + [ -e "$f" ] || continue + name="''${f##*/}" + printf '%s\n' "''${name%.*}" + done + fi + } | ${jq} -R . | ${jq} -cs --argjson fixed ${lib.escapeShellArg laterTagsJson} '. + $fixed + ["proxy", "direct", "block"] | unique' + ) + ${jq} -r --arg sub "$1" --slurpfile taken <(printf '%s' "$taken") ' + $taken[0] as $taken + | .[] | .tag | select(. as $t | ($taken | index([$t])) != null or startswith("proxy-suite-")) + | "proxy-suite: warning: subscription \($sub) entry \(.) left out: the tag is taken" + ' <<< "$entries" >&2 + ${jq} -c --slurpfile taken <(printf '%s' "$taken") ' + $taken[0] as $taken + | map(select(.tag as $t | ($taken | index([$t])) == null and ($t | startswith("proxy-suite-") | not))) + ' <<< "$entries" + } + + # $1 tag, $2 file holding the subscription URL, then the fetcher's flags. Fetches on a + # cold cache and merges whatever is cached; a subscription that cannot be fetched is a # warning, never a failed start. _proxy_suite_load_subscription() { local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" before after _proxy_suite_drop_invalid_subscription_cache "$cache" "$tag" if [ ! -f "$cache" ]; then - _proxy_suite_fetch_subscription "$tag" "$src" \ + _proxy_suite_fetch_subscription "$tag" "$src" "''${@:3}" \ || echo "proxy-suite: warning: could not fetch subscription '$tag'" >&2 fi [ -f "$cache" ] || return 0 @@ -92,21 +166,31 @@ let } ''; + # A subscription's fetcher flags. Runtime ones take proxy.runtimeSubscriptions', https only + # unless allowHttp: over http anyone on the way could add entries. + mkSubscriptionFetchArgs = + sub: + lib.optionalString sub.allowPrivateServers " --allow-private-servers" + + lib.optionalString sub.allowInsecure " --allow-insecure"; + runtimeCfg = proxyCfg.runtimeSubscriptions; + runtimeFetchArgs = + mkSubscriptionFetchArgs runtimeCfg + lib.optionalString (!runtimeCfg.allowHttp) " --https-only"; + mkSubscriptionBlock = sub: _routingMark: '' # subscription: ${sub.tag} - _proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)} + _proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}${mkSubscriptionFetchArgs sub} ''; runtimeSubscriptionsBlock = '' # subscriptions added at runtime while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do [ -n "$RUNTIME_SUB_TAG" ] || continue - _proxy_suite_load_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC" + _proxy_suite_load_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"${runtimeFetchArgs} done < <(_proxy_suite_runtime_subscriptions) ''; mkSubscriptionFetchBlock = sub: '' - if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}; then + if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}${mkSubscriptionFetchArgs sub}; then echo "Updated subscription: ${sub.tag}" else FAILED=1 @@ -116,7 +200,7 @@ let runtimeSubscriptionsFetchBlock = '' while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do [ -n "$RUNTIME_SUB_TAG" ] || continue - if _proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"; then + if _proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"${runtimeFetchArgs}; then echo "Updated subscription: $RUNTIME_SUB_TAG" else FAILED=1 diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 4d01259..817e16e 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -148,6 +148,11 @@ let mkSubscriptionLoadHelperBlock runtimeSubscriptionsBlock ; + # What the start script adds after the runtime outbounds: one of theirs named like these + # would fail the backend's start, every outbound with it. + laterTags = sctx.effectiveOutboundTags ++ sctx.groupTags; + singBoxBin = if pureXrayEnabled then null else sctx.singBox; + xrayBin = if xrayEnabled then sctx.xray else null; }; inherit (outboundScripts) mkOutboundScript; @@ -161,6 +166,13 @@ let proxyInboundsGuardPrivate proxyInboundsGuardStrategy ; + proxyInboundsBlockPrivate = proxyInboundsCfg.routing.blockPrivate; + inherit (ctx) proxyInboundsLoopback proxyInboundsHostClosedPorts; + listenerExposed = + let + address = proxyCfg.listener.address; + in + !(lib.hasPrefix "127." address || address == "::1" || address == "localhost"); userDnsRules = proxyCfg.dns.singBox.rules; awgRuntimeDnsServer = if ctx.awgRuntimeIfaceOutbounds then diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index adbadb7..76f1650 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -38,6 +38,7 @@ let ; inherit (constants) autoProxyStateDir + autoProxySpoolDir outboundTestPort xrayDnsBridgePorts xraySidecarPorts @@ -47,22 +48,20 @@ let inherit pkgs; inherit (constants) serviceUser ifPrivileged; }; + autoProxyMigrate = import ../autoproxy-migrate.nix { inherit pkgs; }; + # Who reads the probe listeners' login (`proxy outbounds test`, `proxy auto probe`). + # Local proxy auth with userControl off keeps its group as before. + probeLoginMainGroup = + (!userControlCfg.enable && localProxyAuthEnabled) + || userControlAllows "outbounds" + || userControlAllows "autoProxy"; + probeLoginExtraGroups = lib.unique ( + ctx.userControlExtraGroupsFor "outbounds" ++ ctx.userControlExtraGroupsFor "autoProxy" + ); runBackend = constants.runAsServiceUser pkgs constants.backendCaps; userControlGroup = lib.escapeShellArg userControlCfg.group; chgrp = "${pkgs.coreutils}/bin/chgrp"; - routeModeBlacklistTail = - if pureXrayEnabled then - '' - + .proxyGeo - + .block - '' - else - '' - + .block - + .proxyGeo - ''; - # Every route mode is the same four assignments over one jq program on the rule buckets. routeModeArms = [ { @@ -73,9 +72,10 @@ let .common + (.custom | map(.entries) | add // []) + .proxyPrimary + + .block + .direct + .safetyDirect - ${routeModeBlacklistTail} + + .proxyGeo ''; } { @@ -86,9 +86,10 @@ let .common + (.custom | map(.entries) | add // []) + .proxyPrimary + + .block + .direct + .safetyDirect - ${routeModeBlacklistTail} + + .proxyGeo ''; } { @@ -101,8 +102,9 @@ let .common + (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // []) + .proxyPrimary + + .block + .safetyDirect - ${routeModeBlacklistTail} + + .proxyGeo ''; } { @@ -113,8 +115,8 @@ let rules = '' .common + (.custom | map(select(.category == "block") | .entries) | add // []) - + .safetyDirect + .block + + .safetyDirect ''; } ]; @@ -153,6 +155,16 @@ let ''; writeProxychainsConfigBlock = '' + # proxychains reads its config by words: a password with whitespace in it would come out + # as another field, or another line. None then, and proxy-ctl says why. + case "''${LOCAL_PROXY_PASSWORD:-}" in + *[[:space:]]*) + echo "proxy-suite: listener.auth's password has whitespace, which proxychains cannot take; no proxychains config" >&2 + rm -f "${runtimeProxychainsConfig}" + ;; + *) + # Private from the start: the chmod below would leave a moment where anyone reads it. + (umask 077 && : > "${runtimeProxychainsConfig}") { printf '%s\n' 'strict_chain' ${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"} @@ -167,12 +179,15 @@ let "$LOCAL_PROXY_PASSWORD" } > "${runtimeProxychainsConfig}" ${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"''} - chmod 640 "${runtimeProxychainsConfig}" + # Without root the group is the user's own primary one, which may be shared. + chmod ${if constants.privileged then "640" else "600"} "${runtimeProxychainsConfig}" # It holds the proxy's password: userControl.groups that run apps through proxychains. ${constants.grantFileAcl pkgs ''"${runtimeProxychainsConfig}"'' (ctx.userControlExtraGroupsFor "perApp") "r" } + ;; + esac ''; mkStartScript = @@ -209,7 +224,7 @@ let ${hybridRuntimeHelpersBlock routingMark xraySidecarPort xrayDnsBridgePort} ${subscriptionCacheHelpersBlock} ${lib.optionalString enableLocalProxyAuth '' - LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" + LOCAL_PROXY_PASSWORD="$(cat ${lib.escapeShellArg localProxyAuthPasswordSource})" # The umask stays in the subshell: left set, it also narrowed everything # written below, and autoProxy's state.json is group-readable by design. ( @@ -238,9 +253,9 @@ let AUTOPROXY_RULES_JSON='[]' ${lib.optionalString enableAutoProxy '' AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir} - # 0751: sing-box, running as ${constants.serviceUser}, reaches the rules/ inside; - # 0771 with userControl's autoProxy scope, whose group queues learn requests there. - install -d -m ${if ctx.userControlAnyAllows "autoProxy" then "0771" else "0751"} "$AUTOPROXY_DIR" + # Root's alone, 0751: sing-box, running as ${constants.serviceUser}, reaches the + # rules/ inside. An install from before the spool is made so first. + ${autoProxyMigrate} "$AUTOPROXY_DIR" ${lib.escapeShellArg autoProxySpoolDir} [ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json" # direct is always exit 0; state is keyed by tag, so shifting indices are @@ -249,9 +264,9 @@ let PROBE_EXITS_JSON=$(${jq} -c \ --argjson max ${toString proxyCfg.autoProxy.maxExits} \ --argjson base ${toString proxyCfg.autoProxy.probeBasePort} \ - --argjson disabled "''${DISABLED_TAGS_JSON:-[]}" \ + --slurpfile disabled <(printf '%s' "''${DISABLED_TAGS_JSON:-[]}") \ --arg dir "$AUTOPROXY_DIR" ' - (["direct"] + map(select(. != "direct" and (. as $t | $disabled | index([$t]) | not))))[0:$max] + (["direct"] + map(select(. != "direct" and (. as $t | $disabled[0] | index([$t]) | not))))[0:$max] | to_entries | map({i: .key, tag: .value, port: ($base + .key), rule_set: ("autoproxy-" + (.key | tostring)), @@ -264,8 +279,19 @@ let PROBE_INBOUNDS_JSON=$(${jq} -c 'map({type: "mixed", tag: ("probe-in-" + (.i | tostring)), listen: "127.0.0.1", listen_port: .port})' <<< "$PROBE_EXITS_JSON") - PROBE_PIN_RULES_JSON=$(${jq} -c 'map({inbound: ["probe-in-" + (.i | tostring)], - outbound: .tag})' <<< "$PROBE_EXITS_JSON") + # The hosts probed are ones the inbounds' clients dialed: the direct probe gets their + # fence (inbounds.routing.blockPrivate), resolving as a direct dial would. + PROBE_PIN_RULES_JSON=$(${jq} -c --argjson fence ${ + lib.escapeShellArg ( + builtins.toJSON ( + if ctx.proxyInboundsCfg.routing.blockPrivate then + { ip_is_private = true; } + else + { ip_cidr = ctx.proxyInboundsLoopback; } + ) + ) + } '[{inbound: ["probe-in-0"], action: "resolve", server: "local"}, ({inbound: ["probe-in-0"], action: "reject"} + $fence)] + + map({inbound: ["probe-in-" + (.i | tostring)], outbound: .tag})' <<< "$PROBE_EXITS_JSON") AUTOPROXY_RULE_SETS_JSON=$(${jq} -c 'map({type: "local", format: "source", tag: .rule_set, path: .path})' <<< "$PROBE_EXITS_JSON") # all-bypass means everything direct; learned exits must not override it. @@ -280,7 +306,7 @@ let # hybrid XRay outbound is a sing-box socks hop whose real server is the sidecar's. # A loopback hop (the WARP tunnel, XRay's SSH listener) has no server worth timing. ENDPOINTS_TMP="$RUNTIME_DIR/outbound-endpoints.json.tmp" - ${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") ' + (umask 077 && ${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") ' $sidecar[0] as $sidecar | def endpoint: if .server then {server, port: .server_port} @@ -301,7 +327,7 @@ let | ($real[.tag] // .) | select(endpoint != null and (endpoint.server | test("^(127\\.|::1$|localhost$)") | not)) | {key: $tag, value: (endpoint + {network: (if udp then "udp" else "tcp" end)})}] | from_entries - ' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP" + ' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP") # Where each proxy server is: not credentials, but not for every local user either. ${ if userControlCfg.enable || localProxyAuthEnabled then @@ -336,16 +362,18 @@ let ${lib.optionalString (!pureXrayEnabled) '' # Delay and download: a loopback listener pinned to a selector over every real # exit, switched one outbound at a time through the Clash API. - OUTBOUNDS_JSON=$(${jq} -c --argjson tags "$EXIT_TAGS_JSON" \ - '. + [{type: "selector", tag: "proxy-suite-test", outbounds: $tags}]' <<< "$OUTBOUNDS_JSON") + # Slurped, not --argjson: one argument holds at most 128 KiB, less than the tags + # of a large subscription. + OUTBOUNDS_JSON=$(${jq} -c --slurpfile tags <(printf '%s' "$EXIT_TAGS_JSON") \ + '. + [{type: "selector", tag: "proxy-suite-test", outbounds: $tags[0]}]' <<< "$OUTBOUNDS_JSON") PROBE_INBOUNDS_JSON=$(${jq} -c '. + [{type: "mixed", tag: "proxy-suite-test-in", listen: "127.0.0.1", listen_port: ${toString outboundTestPort}}]' <<< "$PROBE_INBOUNDS_JSON") PROBE_PIN_RULES_JSON=$(${jq} -c \ '. + [{inbound: ["proxy-suite-test-in"], outbound: "proxy-suite-test"}]' <<< "$PROBE_PIN_RULES_JSON") - ${jq} -n --argjson tags "$EXIT_TAGS_JSON" \ + ${jq} -n --slurpfile tags <(printf '%s' "$EXIT_TAGS_JSON") \ --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} ' {port: ${toString outboundTestPort}, selector: "proxy-suite-test", url: $url, - outbounds: ($tags | map({key: ., value: .}) | from_entries)} + outbounds: ($tags[0] | map({key: ., value: .}) | from_entries)} ' > "$RUNTIME_DIR/outbound-test.json" # Tags and a loopback port only. chmod 644 "$RUNTIME_DIR/outbound-test.json" @@ -402,14 +430,25 @@ let esac ''} + # Every address this host has now, for the inbounds' guard (backend-filter-private-guard): + # dialed from here, a client would reach any port of them past the firewall. + HOST_ADDRESSES_JSON='[]' + ${lib.optionalString (ctx.proxyInboundsEnabled && ctx.proxyInboundsNeedLocalProxy) '' + if ! HOST_ADDRESSES_JSON=$(${pkgs.iproute2}/bin/ip -j addr show | ${jq} -c \ + '[.[].addr_info[]?.local | strings | if test(":") then . + "/128" else . + "/32" end] | unique'); then + echo "proxy-suite: cannot list this host's addresses; the inbounds' clients reach any port of them" >&2 + HOST_ADDRESSES_JSON='[]' + fi + ''} + # umask: the file holds credentials until the chmod below; the process # substitutions keep them out of the argv every local user can read. (umask 077 && ${jq} \ --slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \ - --argjson probe_inbounds "$PROBE_INBOUNDS_JSON" \ - --argjson probe_pin_rules "$PROBE_PIN_RULES_JSON" \ - --argjson autoproxy_rule_sets "$AUTOPROXY_RULE_SETS_JSON" \ - --argjson autoproxy_rules "$AUTOPROXY_RULES_JSON" \ + --slurpfile probe_inbounds <(printf '%s' "$PROBE_INBOUNDS_JSON") \ + --slurpfile probe_pin_rules <(printf '%s' "$PROBE_PIN_RULES_JSON") \ + --slurpfile autoproxy_rule_sets <(printf '%s' "$AUTOPROXY_RULE_SETS_JSON") \ + --slurpfile autoproxy_rules <(printf '%s' "$AUTOPROXY_RULES_JSON") \ --argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \ --arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \ ${ @@ -419,24 +458,54 @@ let "--arg password ''" } \ --argjson route_enabled "$ROUTE_MODE_ACTIVE" \ - --argjson route_rules "$ROUTE_RULES_JSON" \ + --slurpfile route_rules <(printf '%s' "$ROUTE_RULES_JSON") \ --arg route_final "$ROUTE_FINAL" \ --arg dns_final "$DNS_FINAL" \ --argjson clear_dns_rules "$CLEAR_DNS_RULES" \ --arg xray_loglevel "$XRAY_LOGLEVEL" \ --arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \ - --argjson xray_selectable "$SELECTABLE_TAGS_JSON" \ + --slurpfile xray_selectable <(printf '%s' "$SELECTABLE_TAGS_JSON") \ --argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \ + --argjson host_addresses "$HOST_ADDRESSES_JSON" \ -f "$BACKEND_JQ_FILTER" \ "${configFile}" > "$RUNTIME_DIR/config.json") ${lib.optionalString excludeServiceUserFromTun '' # proxy-suite's own daemons (the inbound XRay, replies to its clients included) # stay out of the TUN; the uid is only known on this host. - SERVICE_UID=$(${pkgs.coreutils}/bin/id -u ${constants.serviceUser}) - (umask 077 && ${jq} --argjson uid "$SERVICE_UID" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = [$uid]' \ + SERVICE_UIDS=$(for service_user in ${lib.escapeShellArgs constants.ownTrafficUsers}; do + ${pkgs.coreutils}/bin/id -u "$service_user" + done | ${jq} -cs .) + (umask 077 && ${jq} --argjson uids "$SERVICE_UIDS" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = $uids' \ "$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next") mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json" ''} + ${lib.optionalString (!pureXrayEnabled) '' + # The probe and test listeners reach any exit past the routing rules and the kill + # switch: a login per start, into jq through its environment (argv is public). + if ${jq} -e '[.inbounds[]? | (.tag // "") | select(startswith("probe-in-") or . == "proxy-suite-test-in")] | length > 0' \ + "$RUNTIME_DIR/config.json" >/dev/null; then + PROBE_PASSWORD=$(${pkgs.coreutils}/bin/od -An -tx1 -N16 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n') + (umask 077 && PROBE_PASSWORD="$PROBE_PASSWORD" ${jq} '(.inbounds[]? | select((.tag // "") | startswith("probe-in-") or . == "proxy-suite-test-in")) + += {users: [{username: "probe", password: $ENV.PROBE_PASSWORD}]}' \ + "$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next") + mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json" + (umask 077 && printf 'probe:%s\n' "$PROBE_PASSWORD" > "$RUNTIME_DIR/probe-login.tmp") + unset PROBE_PASSWORD + ${ + # Only to the groups that test outbounds or probe for autoProxy: to any other the + # login is a way out direct, past the routing rules and the kill switch. + if probeLoginMainGroup then + '' + ${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$RUNTIME_DIR/probe-login.tmp"''} + chmod ${if constants.privileged then "640" else "600"} "$RUNTIME_DIR/probe-login.tmp" + '' + else + ''chmod 600 "$RUNTIME_DIR/probe-login.tmp"'' + } + ${constants.grantFileAcl pkgs ''"$RUNTIME_DIR/probe-login.tmp"'' probeLoginExtraGroups "r"} + mv "$RUNTIME_DIR/probe-login.tmp" "$RUNTIME_DIR/probe-login" + fi + ''} # The Clash API lists every connection and switches outbounds. Loopback alone lets # every local user at it, and every web page too (sing-box allows any origin): a # secret per start. @@ -472,7 +541,9 @@ let else '' ${constants.ifPrivileged ''${chgrp} ${constants.serviceUser} "$backend_config"''} - chmod 640 "$backend_config" + # Without root the group is the user's own primary one, which may be shared + # (users): the owner alone then. + chmod ${if constants.privileged then "640" else "600"} "$backend_config" '' } ${constants.grantFileAcl pkgs ''"$backend_config"'' (ctx.userControlExtraGroupsFor "secrets") "r"} diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index 0503942..c030166 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -12,7 +12,6 @@ let globalTun globalTproxy killSwitchEnabled - awgGlobalProfiles perAppRoutingTun perAppRoutingTproxy perAppZapretEnabled @@ -41,7 +40,9 @@ let inherit (routingScripts) xrayTunUpScript + xrayTunReloadScript tproxyUpScript + tproxyReloadScript tproxyDownScript killSwitchUpScript killSwitchDownScript @@ -74,6 +75,135 @@ let perAppViaAwg = perAppViaInterfaceOutbounds != [ ] || perAppViaRuntime || ctx.perAppViaProfiles; # Or any outbound, through a pin slot: either way, the apps' slices and their marking. perAppViaEnabled = perAppViaAwg || perAppRouting.pinUp != { }; + # A per-app backend every user's apps share. perApp members may only start it (polkit.nix): + # it goes once the last user's marking unit that requires it stops, or the last pin of it. + perAppSharedBackend = + unit: restartOnSwitch (lib.recursiveUpdate unit { unitConfig.StopWhenUnneeded = true; }); + # A switch restarts it rather than stopping it across activation: a shorter gap, and a + # restart keeps the per-app holds (user-rules.nix). [Service] is where the switch reads it. + restartOnSwitch = unit: lib.recursiveUpdate unit { serviceConfig."X-StopIfChanged" = false; }; + # Rules a firewall reload can flush, put back by `reload` (a start of the firewall: by + # proxy-suite-firewall-reapply). After=, or the firewall's flush could come after it. + reloadAfterFirewall = + reload: unit: + lib.recursiveUpdate unit { + after = (unit.after or [ ]) ++ [ "nftables.service" ]; + serviceConfig.ExecReload = reload; + unitConfig.ReloadPropagatedFrom = [ "nftables.service" ]; + }; + # NixOS's firewall loads the static tables itself (constants.persistedNftDir); the per-app + # ones hold cgroup matches, which fail the firewall's whole load once the cgroup is gone. + firewallIncludes = ctx.firewallIncludesTables; + reloadAfterFirewallUnlessIncluded = + reload: if firewallIncludes then lib.id else reloadAfterFirewall reload; + # What proxy-suite-firewall-reapply reloads, as systemctl patterns. + firewallReapplyUnits = + lib.optionals (!firewallIncludes) ( + lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service" + ++ lib.optional (proxyEnabled || proxyInboundsEnabled) "proxy-suite-daemon-guard.service" + ++ lib.optional (proxyEnabled && globalTproxy.enable) "${serviceNames.tproxy}.service" + # Only XRay's TUN has a reload; sing-box's would be restarted. + ++ lib.optional (proxyEnabled && globalTun.enable && pureXrayEnabled) "${serviceNames.tun}.service" + ) + ++ lib.optionals (proxyEnabled && perAppRoutingTun.enable) [ + "${serviceNames.perAppTun}.service" + "${serviceNames.perAppTun}-user@*.service" + ] + ++ lib.optionals (proxyEnabled && perAppRoutingTproxy.enable) [ + "${serviceNames.perAppTproxy}.service" + "${serviceNames.perAppTproxy}-user@*.service" + ] + ++ lib.optional perAppViaAwg "proxy-suite-per-app-via@*.service" + ++ map (route: "proxy-suite-per-app-via-${route}@*.service") ( + builtins.attrNames perAppRouting.pinUp + ); + # A per-app route's DNS forwarder (nftables.nix's dns_redirect), up while the route or one + # of its pin slots is: a listener for the route's own mark, and one for each slot's. + perAppDnsUnit = route: "proxy-suite-per-app-${route}-dns.service"; + mkPerAppDnsForwarder = + { + route, + mark, + basePort, + pinMarkBase, + pins, + bind ? [ ], + }: + let + listeners = [ + "${toString basePort}:${toString mark}" + ] + ++ lib.genList (slot: "${toString (basePort + 1 + slot)}:${toString (pinMarkBase + slot)}") ( + if pins then ctx.perAppPinSlots else 0 + ); + in + restartOnSwitch (mkRestartingService { + description = "proxy-suite per-app ${route} DNS forwarder"; + execStart = lib.concatStringsSep " " ( + [ + ctx.python3 + "${ctx.proxySuiteScriptsDir}/per_app_dns.py" + ] + ++ map (l: "--listen ${l}") listeners + ++ map (a: "--bind ${a}") bind + ++ [ ctx.constants.perAppDnsUpstream ] + ); + runtimeDirectory = "proxy-suite-per-app-${route}-dns"; + extraServiceConfig = { + # Ready once it listens, so the route's apps' first lookup finds it. + Type = "notify"; + NotifyAccess = "main"; + RestartSec = 2; + DynamicUser = true; + # SO_MARK on its sockets, and nothing else. + AmbientCapabilities = [ "CAP_NET_ADMIN" ]; + CapabilityBoundingSet = [ "CAP_NET_ADMIN" ]; + NoNewPrivileges = true; + ProtectSystem = "strict"; + ProtectHome = true; + PrivateTmp = true; + PrivateDevices = true; + ProtectClock = true; + ProtectHostname = true; + ProtectKernelLogs = true; + ProtectKernelModules = true; + ProtectKernelTunables = true; + ProtectControlGroups = true; + RestrictNamespaces = true; + RestrictRealtime = true; + LockPersonality = true; + MemoryDenyWriteExecute = true; + SystemCallArchitectures = "native"; + RestrictAddressFamilies = [ + "AF_UNIX" + "AF_INET" + "AF_INET6" + ]; + SystemCallFilter = [ "@system-service" ]; + # The apps' queries on loopback, sent on to the upstream the backend answers for. + IPAddressAllow = [ + "localhost" + ctx.constants.perAppDnsUpstream + ]; + IPAddressDeny = "any"; + }; + }) + // { + unitConfig.StopWhenUnneeded = true; + }; + # The global TUN and TProxy carry every app already: the per-app TProxy backend, its pin + # slots and per-app zapret refuse to start under them, and go when one starts + # (constants.refuseUnderGlobal). + globalModeUnits = [ + "${serviceNames.tproxy}.service" + "${serviceNames.tun}.service" + ]; + perAppUnderGlobalModes = [ + "${serviceNames.perAppTproxy}.service" + "proxy-suite-per-app-via-tproxy@*.service" + "proxy-suite-per-app-via-tun@*.service" + "${serviceNames.perAppZapret}.service" + ]; # 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 @@ -99,7 +229,9 @@ let { enable = proxyEnabled; name = serviceNames.socks; - value = mkRestartingService { + # No PropagatesStopTo= TProxy: it stops TProxy on a restart too, which should hold the + # traffic meanwhile. `proxy off` stops TProxy itself. + value = restartOnSwitch (mkRestartingService { description = "${backendDescription} proxy client (SOCKS + TProxy-ready)"; # Only XRay goes through the OpenSSH unit's listener. after = [ @@ -114,11 +246,18 @@ let ++ lib.optional torOutboundEnabled "proxy-suite-tor.service" ++ map (j: "proxy-suite-wb-joiner-${j.tag}.service") whitelistBypassJoiners; wantedBy = [ "multi-user.target" ]; + # The hop login drawn as root, ahead of the start script, which ProtectSystem keeps + # from writing /run (constants.ensureHopLogin). + execStartPre = lib.filter (x: x != null) [ + (ctx.constants.daemonMetadataGuard ctx.pkgs) + "+${ctx.constants.ensureHopLogin ctx.pkgs}" + ]; execStart = scripts.startSocks; runtimeDirectory = serviceNames.socks; stateDirectory = "proxy-suite"; - extraServiceConfig = xrayAssetEnv // spoolReaderSandbox [ ]; - }; + # The hybrid sidecar's config has no geo rules: only XRay as the backend reads them. + extraServiceConfig = lib.optionalAttrs pureXrayEnabled xrayAssetEnv // spoolReaderSandbox [ ]; + }); } { enable = proxyInboundsEnabled; @@ -139,6 +278,7 @@ let ++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service" ++ lib.optional torOnionEnabled "proxy-suite-tor.service"; wantedBy = [ "multi-user.target" ]; + execStartPre = ctx.constants.daemonMetadataGuard ctx.pkgs; execStart = scripts.startInbounds; # inbounds.routing.serverSource's dummy interface. execStopPost = scripts.stopInboundsInterface; @@ -146,9 +286,24 @@ let # The collector's file. stateDirectory = "proxy-suite"; # While XRay still runs: what it counted since the last timer run. - extraServiceConfig = xrayAssetEnv // { - ExecStop = scripts.collectInboundStats; - }; + extraServiceConfig = + xrayAssetEnv + // { + ExecStop = scripts.collectInboundStats; + } + # Nothing it runs is setuid (setpriv drops to the service user by itself), and no + # other unit shares its temporary files. + // lib.optionalAttrs ctx.constants.privileged { + NoNewPrivileges = true; + PrivateTmp = true; + # Root parses the group-writable inbounds.d: it writes nowhere but its runtime + # and state directories, which systemd leaves writable. + ProtectSystem = "strict"; + ProtectKernelTunables = true; + ProtectControlGroups = true; + # The stats API's directory is the daemon's alone now, no setgid one to make. + RestrictSUIDSGID = true; + }; }; } { @@ -158,7 +313,11 @@ let description = "Apply proxy-suite inbound users and listeners added at runtime"; execStart = scripts.reloadInbounds; stateDirectory = "proxy-suite"; - extraServiceConfig.RemainAfterExit = false; + # Root, over the spool userControl's group writes. + extraServiceConfig = { + RemainAfterExit = false; + } + // spoolReaderSandbox [ ]; }; } { @@ -173,20 +332,22 @@ let extraServiceConfig.RemainAfterExit = false; }; } - # Pulled in by every global tunnel and left up when it stops or crashes: only - # proxy-ctl's off verbs take it down. After them, so a first start still fetches - # subscriptions and resolves endpoints directly. + # Up from boot, before any network, and pulled in by every global tunnel; only proxy-ctl's + # off verbs take it down. What the tunnels fetch to come up goes as a user it lets past. { enable = killSwitchEnabled; name = serviceNames.killSwitch; value = mkOneshotService { description = "proxy-suite kill switch - reject traffic outside the global tunnel"; + # After the firewall: its start flushes the whole ruleset on some hosts. after = [ - "${serviceNames.socks}.service" - "${serviceNames.tun}.service" - ] - ++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles); + "sysinit.target" + "nftables.service" + "firewall.service" + ]; + wants = [ "network-pre.target" ]; + wantedBy = [ "multi-user.target" ]; execStart = killSwitchUpScript; execStop = killSwitchDownScript; extraServiceConfig.ExecReload = killSwitchUpScript; @@ -195,100 +356,210 @@ let # new rules from a switch are swapped in by a reload instead, in one transaction. // { reloadIfChanged = true; + before = [ "network-pre.target" ]; + unitConfig = { + # Not stopped at shutdown either, unlike the units it guards. + DefaultDependencies = false; + } + # Put back after a firewall reload that flushed the ruleset (see reloadAfterFirewall). + // lib.optionalAttrs (!firewallIncludes) { + ReloadPropagatedFrom = [ "nftables.service" ]; + }; + }; + } + # A start or restart of the firewall, which flushes the ruleset on some hosts, reloads + # what reloadAfterFirewall covers; a reload does nothing to a unit that is not up. + { + enable = ctx.constants.privileged && firewallReapplyUnits != [ ]; + name = "proxy-suite-firewall-reapply"; + value = mkOneshotService { + description = "proxy-suite - put its nftables tables back after the firewall starts"; + after = [ "nftables.service" ]; + wantedBy = [ "nftables.service" ]; + # --no-block: the units it reloads are ordered after nftables, whose start this is + # part of. + execStart = "-${ctx.constants.systemctl} try-reload-or-restart --no-block ${lib.concatStringsSep " " firewallReapplyUnits}"; + # Inactive once done, so the firewall's next start runs it again. + extraServiceConfig.RemainAfterExit = false; + }; + } + # The daemon guard (constants.daemonMetadataGuard) on its own as well, so that a firewall + # that flushed the ruleset gets it back, not only the next start of the units that load it. + { + enable = ctx.constants.privileged && (proxyEnabled || proxyInboundsEnabled); + name = "proxy-suite-daemon-guard"; + value = + let + load = [ + (ctx.constants.daemonMetadataGuard ctx.pkgs) + ] + ++ lib.optional firewallIncludes "-${routingScripts.persistDaemonGuardScript}"; + in + mkOneshotService { + description = "proxy-suite - keep cloud metadata and the loopback hops from other users"; + after = [ "nftables.service" ]; + wantedBy = [ "multi-user.target" ]; + execStart = load; + extraServiceConfig.ExecReload = load; + } + // { + reloadIfChanged = true; + } + // lib.optionalAttrs (!firewallIncludes) { + unitConfig.ReloadPropagatedFrom = [ "nftables.service" ]; }; } { enable = proxyEnabled && globalTproxy.enable; name = serviceNames.tproxy; - value = mkOneshotService { - description = "proxy-suite TProxy - nftables rules and policy routing"; - after = [ - "network.target" - "${serviceNames.socks}.service" - ]; - wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ]; - requires = [ "${serviceNames.socks}.service" ]; - wants = lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service"; - conflicts = [ - "${serviceNames.tun}.service" - "${serviceNames.perAppTproxy}.service" - ]; - execStart = tproxyUpScript; - execStop = tproxyDownScript; - }; + # Put back with the firewall: all the host's (and the LAN's) traffic, otherwise. + value = restartOnSwitch ( + reloadAfterFirewallUnlessIncluded tproxyReloadScript (mkOneshotService { + description = "proxy-suite TProxy - nftables rules and policy routing"; + after = [ + "network.target" + "${serviceNames.socks}.service" + ]; + wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ]; + # Wants=, not Requires=: a restart of the backend would restart this too, and the + # host's traffic go direct until it is back. + wants = [ + "${serviceNames.socks}.service" + ] + ++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service"; + conflicts = [ "${serviceNames.tun}.service" ]; + execStartPre = ctx.constants.stopPerAppUnits ctx.pkgs perAppUnderGlobalModes; + execStart = tproxyUpScript; + # Post: also after a start that failed partway, whose marking table would + # otherwise outlive it and send marked traffic out past the kill switch. + execStopPost = tproxyDownScript; + }) + ); } { enable = proxyEnabled && globalTun.enable; name = serviceNames.tun; - value = mkRestartingService { - description = "${backendDescription} TUN proxy client"; - after = [ "network-online.target" ]; - wants = [ - "network-online.target" - ] - ++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service"; - wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ]; - conflicts = [ "${serviceNames.tproxy}.service" ]; - execStartPre = tunCleanupScript; - execStart = scripts.startTun; - execStartPost = if pureXrayEnabled then xrayTunUpScript else null; - execStopPost = tunCleanupScript; - runtimeDirectory = serviceNames.tun; - stateDirectory = "proxy-suite"; - }; + value = restartOnSwitch ( + (if pureXrayEnabled then reloadAfterFirewallUnlessIncluded xrayTunReloadScript else lib.id) + (mkRestartingService { + description = "${backendDescription} TUN proxy client"; + after = [ "network-online.target" ]; + wants = [ + "network-online.target" + ] + ++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service"; + wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ]; + conflicts = [ "${serviceNames.tproxy}.service" ]; + execStartPre = [ + (ctx.constants.stopPerAppUnits ctx.pkgs perAppUnderGlobalModes) + tunCleanupScript + (ctx.constants.ensureHopLogin ctx.pkgs) + ]; + execStart = scripts.startTun; + execStartPost = if pureXrayEnabled then xrayTunUpScript else null; + execStopPost = tunCleanupScript; + runtimeDirectory = serviceNames.tun; + stateDirectory = "proxy-suite"; + }) + ); } { enable = proxyEnabled && perAppRoutingTun.enable; name = serviceNames.perAppTun; - value = mkRestartingService { - description = "proxy-suite per-app-routing TUN backend"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - execStartPre = perAppRouting.perAppTunDownScript; - execStart = scripts.startPerAppTun; - execStartPost = perAppRouting.perAppTunUpScript; - execStopPost = perAppRouting.perAppTunDownScript; - runtimeDirectory = serviceNames.perAppTun; - stateDirectory = "proxy-suite"; - }; + value = reloadAfterFirewall perAppRouting.perAppTunReloadScript ( + perAppSharedBackend (mkRestartingService { + description = "proxy-suite per-app-routing TUN backend"; + after = [ + "network-online.target" + (perAppDnsUnit "tun") + ]; + wants = [ + "network-online.target" + (perAppDnsUnit "tun") + ]; + execStartPre = [ + perAppRouting.perAppTunDownScript + (ctx.constants.ensureHopLogin ctx.pkgs) + ]; + execStart = scripts.startPerAppTun; + execStartPost = perAppRouting.perAppTunUpScript; + execStopPost = perAppRouting.perAppTunDownScript; + runtimeDirectory = serviceNames.perAppTun; + stateDirectory = "proxy-suite"; + }) + ); } { enable = proxyEnabled && perAppRoutingTun.enable; name = "${serviceNames.perAppTun}-user@"; - value = mkUserRuleService { + # Its rules back in after the backend's table, and the hold's, came back (After=). + value = reloadAfterFirewall "${perAppRouting.perAppTunUserRuleStart} %i" (mkUserRuleService { description = "Enable proxy-suite app TUN marking for user %i"; backendService = serviceNames.perAppTun; execStart = "${perAppRouting.perAppTunUserRuleStart} %i"; execStop = "${perAppRouting.perAppTunUserRuleStop} %i"; - }; + }); } { enable = proxyEnabled && perAppRoutingTproxy.enable; name = serviceNames.perAppTproxy; - value = mkOneshotService { - description = "proxy-suite per-app-routing TProxy backend"; - after = [ - "network.target" - "${serviceNames.socks}.service" - ]; - requires = [ "${serviceNames.socks}.service" ]; - conflicts = [ - "${serviceNames.tproxy}.service" - "${serviceNames.tun}.service" - ]; - execStart = perAppRouting.perAppTproxyUpScript; - execStop = perAppRouting.perAppTproxyDownScript; + value = reloadAfterFirewall perAppRouting.perAppTproxyReloadScript ( + perAppSharedBackend (mkOneshotService { + description = "proxy-suite per-app-routing TProxy backend"; + after = [ + "network.target" + "${serviceNames.socks}.service" + (perAppDnsUnit "tproxy") + ]; + requires = [ "${serviceNames.socks}.service" ]; + wants = [ (perAppDnsUnit "tproxy") ]; + execStartPre = ctx.constants.refuseUnderGlobal ctx.pkgs globalModeUnits; + execStart = perAppRouting.perAppTproxyUpScript; + # Post: after a start that failed partway too (see the global TProxy unit). + execStopPost = perAppRouting.perAppTproxyDownScript; + }) + ); + } + { + enable = proxyEnabled && perAppRoutingTun.enable; + name = "proxy-suite-per-app-tun-dns"; + value = mkPerAppDnsForwarder { + route = "tun"; + mark = perAppRoutingTun.fwmark; + basePort = ctx.constants.perAppTunDnsBasePort; + pinMarkBase = ctx.constants.perAppPinTunFwmarkBase; + pins = ctx.perAppPinTun; + }; + } + { + enable = proxyEnabled && perAppRoutingTproxy.enable; + name = "proxy-suite-per-app-tproxy-dns"; + value = mkPerAppDnsForwarder { + route = "tproxy"; + mark = perAppRoutingTproxy.fwmark; + basePort = ctx.constants.perAppTproxyDnsBasePort; + pinMarkBase = ctx.constants.perAppPinTproxyFwmarkBase; + pins = ctx.perAppPinTproxy; + # The mark takes the queries to a local route (see per_app_dns.py's BIND). + bind = [ "127.0.0.1" ]; }; } { enable = proxyEnabled && perAppRoutingTproxy.enable; name = "${serviceNames.perAppTproxy}-user@"; - value = mkUserRuleService { + # Its rules back in after the backend's table, and the hold's, came back (After=). + value = reloadAfterFirewall "${perAppRouting.perAppTproxyUserRuleStart} %i" (mkUserRuleService { description = "Enable proxy-suite app TProxy marking for user %i"; backendService = serviceNames.perAppTproxy; execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i"; execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i"; - }; + }); + } + # Declared with zapret's own units (zapret.nix, zapret2.nix). + { + enable = perAppZapretEnabled; + name = serviceNames.perAppZapret; + value = perAppSharedBackend { }; } { enable = perAppZapretEnabled; @@ -306,31 +577,54 @@ let { 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" ]; - }; - }; + # Its table, rules and users' rules back after a firewall reload that flushed them. + value = restartOnSwitch ( + reloadAfterFirewall + [ + "${perAppRouting.viaUp} %i" + "${perAppRouting.viaReapply} %i" + ] + (mkRestartingService { + description = "proxy-suite per-app routing via %i"; + execStartPre = "${perAppRouting.viaUp} %i"; + execStart = "${perAppRouting.viaDns} %i"; + # viaUp starts the table empty: after a restart, the users' rules go back in. + execStartPost = "${perAppRouting.viaReapply} %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; + # Root still, though with one capability: the disks' device nodes, /proc/sys and + # cgroups are root's to write without any, and the forwarder answers apps. + PrivateDevices = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + RestrictRealtime = true; + RestrictSUIDSGID = true; + LockPersonality = true; + # nft and ip rules, and SO_MARK on the forwarder's sockets. + CapabilityBoundingSet = [ "CAP_NET_ADMIN" ]; + # Netlink for nft and ip, unix for the readiness notice, IP for the forwarder. + RestrictAddressFamilies = [ + "AF_UNIX" + "AF_INET" + "AF_INET6" + "AF_NETLINK" + ]; + }; + }) + ); } ] # `apps run --via ` for any other outbound: a pin slot of per-app TProxy or TUN for @@ -343,21 +637,34 @@ let 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 ]; - }; + # Its table and its users' rules back after a firewall reload that flushed them. The + # users' holds keep their apps in while it rebuilds. + restartOnSwitch ( + reloadAfterFirewall + [ + "${perAppRouting.pinUp.${route}} %i" + "${perAppRouting.viaReapply} ${route}-%i" + ] + ( + mkOneshotService { + description = "proxy-suite per-app ${route} pin for the outbound %i (in hex)"; + execStart = "${perAppRouting.pinUp.${route}} %i"; + execStartPost = "${perAppRouting.viaReapply} ${route}-%i"; + execStop = "${perAppRouting.pinDown.${route}} %i"; + after = [ + backend + (perAppDnsUnit route) + ]; + requires = [ backend ]; + wants = [ (perAppDnsUnit route) ]; + # As per-app TProxy: under a global mode, proxy-ctl runs the app without its route. + execStartPre = ctx.constants.refuseUnderGlobal ctx.pkgs globalModeUnits; + } + // { + partOf = [ backend ]; + } + ) + ); }) (builtins.attrNames perAppRouting.pinUp) ++ [ { @@ -367,6 +674,12 @@ let description = "Enable proxy-suite per-app via marking for %i"; execStart = "${perAppRouting.viaUserStart} %i"; execStop = "${perAppRouting.viaUserStop} %i"; + # No unit names the via unit from -, so no Requires= can hold it for + # StopWhenUnneeded=: the last user's unit takes it down itself. + execStopPost = "${perAppRouting.viaRetire} %i"; + # A switch's stop would take the via unit down under the running apps; a new via + # unit puts the rules back itself (viaReapply). In [Service], where the switch reads it. + extraServiceConfig.X-RestartIfChanged = false; }; } { @@ -392,7 +705,20 @@ let value = mkOneshotService { description = "Set proxy-suite route mode to %i"; execStart = "${scripts.setRouteModeScript} %i"; - extraServiceConfig.RemainAfterExit = false; + # Root, started by userControl's group: it writes the mode file and restarts the + # proxy, nothing else. + extraServiceConfig = { + RemainAfterExit = false; + } + // spoolReaderSandbox [ ] + // lib.optionalAttrs ctx.constants.privileged { + # Where the mode file lives, which nothing else makes: kept between runs, and + # writable under ProtectSystem, whether or not it exists yet. + RuntimeDirectory = "proxy-suite"; + RuntimeDirectoryPreserve = "yes"; + NoNewPrivileges = true; + PrivateTmp = true; + }; }; } { diff --git a/modules/proxy-suite/ssh-proxy.nix b/modules/proxy-suite/ssh-proxy.nix index 942d124..49332bb 100644 --- a/modules/proxy-suite/ssh-proxy.nix +++ b/modules/proxy-suite/ssh-proxy.nix @@ -10,10 +10,30 @@ let s = cfg.sshProxy; inherit (derived.constants) serviceUser unprivilegedServiceConfig; destination = if s.server.user == null then s.server.host else "${s.server.user}@${s.server.host}"; + # ssh reads "::1:1091" as a bad forwarding spec: an IPv6 address goes in brackets. + listenHost = + if lib.hasInfix ":" s.listener.address then "[${s.listener.address}]" else s.listener.address; extraArgs = lib.concatMapStrings (arg: " args+=(${lib.escapeShellArg arg})\n") s.extraArgs; + # The server's keys: a known-hosts file, the one sing-box reads, or its keys as one. + knownHostsSource = + if s.knownHostsFile != null then + s.knownHostsFile + else if s.hostKeyFile != null then + s.hostKeyFile + else if s.hostKey != [ ] then + pkgs.writeText "proxy-suite-ssh-known-hosts" ( + lib.concatMapStrings ( + key: + "${ + if s.server.port == 22 then s.server.host else "[${s.server.host}]:${toString s.server.port}" + } ${key}\n" + ) s.hostKey + ) + else + null; # The service user's home is /var/empty: accepted host keys are kept in the state dir. knownHosts = - if s.knownHostsFile != null then + if knownHostsSource != null then ''"$CREDENTIALS_DIRECTORY/known_hosts"'' else if s.serviceUser == serviceUser then ''"$STATE_DIRECTORY/known_hosts"'' @@ -30,7 +50,7 @@ let -o ServerAliveCountMax=3 -o ConnectTimeout=10 -o StrictHostKeyChecking=${lib.escapeShellArg s.strictHostKeyChecking} - -D ${lib.escapeShellArg "${s.listener.address}:${toString s.listener.port}"} + -D ${lib.escapeShellArg "${listenHost}:${toString s.listener.port}"} ) ${lib.optionalString (s.server.port != 22) "args+=(-p ${toString s.server.port})"} ${lib.optionalString (s.identityFile != null) ''args+=(-i "$CREDENTIALS_DIRECTORY/identity")''} @@ -55,7 +75,7 @@ in # Copies the service user can read, whoever owns the originals. LoadCredential = lib.optional (s.identityFile != null) "identity:${s.identityFile}" - ++ lib.optional (s.knownHostsFile != null) "known_hosts:${s.knownHostsFile}"; + ++ lib.optional (knownHostsSource != null) "known_hosts:${knownHostsSource}"; StateDirectory = "proxy-suite/ssh"; StateDirectoryMode = "0700"; # `ssh -N` exits 0 when the server closes the connection cleanly, which diff --git a/modules/proxy-suite/tg-ws-proxy.nix b/modules/proxy-suite/tg-ws-proxy.nix index a673583..a13686c 100644 --- a/modules/proxy-suite/tg-ws-proxy.nix +++ b/modules/proxy-suite/tg-ws-proxy.nix @@ -94,9 +94,19 @@ in wants = [ "network-online.target" ]; wantedBy = [ "multi-user.target" ]; serviceConfig = - derived.constants.unprivilegedServiceConfig [ - "net_bind_service" - ] + # Not proxy-suite-daemon, whose traffic gets past TUN, TProxy and the kill switch whatever + # bypassTransparentProxy says: the bypass goes by the cgroup mark below. + builtins.removeAttrs + (derived.constants.unprivilegedServiceConfig [ + "net_bind_service" + ]) + [ + "User" + "Group" + ] + // lib.optionalAttrs cfg.host.privileged { + DynamicUser = true; + } // { ExecStart = startScript; LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}"; diff --git a/modules/proxy-suite/tor.nix b/modules/proxy-suite/tor.nix index 7b94a5c..0f2e87e 100644 --- a/modules/proxy-suite/tor.nix +++ b/modules/proxy-suite/tor.nix @@ -9,7 +9,15 @@ let t = derived.torCfg; - inherit (derived.constants) unprivilegedServiceConfig; + inherit (derived.constants) torUser; + # As the service user's, but Tor's own user: shares nothing with the inbounds or backend. + unprivilegedServiceConfig = + caps: + derived.constants.unprivilegedServiceConfig caps + // lib.optionalAttrs privileged { + User = torUser; + Group = torUser; + }; inherit (cfg.host) privileged; inherit (derived.localProxy) auth; @@ -26,11 +34,11 @@ let viaProxy = t.upstream == "proxy"; withProxyAuth = viaProxy && derived.localProxy.authEnabled; bridgesEnabled = t.bridges.lines != [ ] || t.bridges.file != null; + # A torrc string: Tor unescapes \\ and \" inside the quotes. + torQuote = s: ''"${builtins.replaceStrings [ "\\" "\"" ] [ "\\\\" "\\\"" ] s}"''; - # The control socket is Tor's own (and root's): with it, one can publish any loopback - # port as an onion service, point Tor at another upstream, or read the proxy password - # from its config. userControl's group asks for a new identity through - # proxy-suite-tor-newnym instead. + # The control socket is Tor's own user's: userControl's group asks for a new identity + # through proxy-suite-tor-newnym instead. controlSocket = derived.constants.torControlSocket; newnymScript = pkgs.writeShellScript "proxy-suite-tor-newnym" '' set -euo pipefail @@ -121,8 +129,12 @@ let echo "DataDirectory $STATE_DIRECTORY" echo "ControlSocket unix:$RUNTIME_DIRECTORY/control/socket" ${lib.optionalString withProxyAuth '' - echo "Socks5ProxyUsername "${lib.escapeShellArg auth.username} - printf 'Socks5ProxyPassword %s\n' "$(${pkgs.coreutils}/bin/head -n1 "$CREDENTIALS_DIRECTORY/proxy-password")" + # Quoted: bare, a "#" would start a comment, a leading quote open a string and a + # trailing backslash join the next line on. + echo ${lib.escapeShellArg "Socks5ProxyUsername ${torQuote auth.username}"} + password=$(${pkgs.coreutils}/bin/head -n1 "$CREDENTIALS_DIRECTORY/proxy-password") + password=''${password//\\/\\\\} + printf 'Socks5ProxyPassword "%s"\n' "''${password//\"/\\\"}" ''} ${lib.optionalString (t.bridges.file != null) '' ${pkgs.gnused}/bin/sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e '/^$/d' -e '/^#/d' \ @@ -141,6 +153,9 @@ let ''; in { + # Whatever the upstream: only its exemption from TUN and TProxy depends on it. + services.proxy-suite.internal.systemUsers = lib.optional privileged torUser; + services.proxy-suite.internal.services.proxy-suite-tor = { description = "proxy-suite - Tor"; after = [ "network-online.target" ] ++ lib.optional viaProxy "proxy-suite-socks.service"; @@ -154,8 +169,8 @@ in Type = "simple"; ExecStart = startScript; ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID"; - # The service user is excluded from TUN and TProxy capture, which is what keeps - # tor's own connections out of the proxy. + # Unless upstream = "proxy", its user is kept out of TUN and TProxy + # (constants.ownTrafficUsers), and with it Tor's own connections. StateDirectory = "proxy-suite/tor"; StateDirectoryMode = "0700"; RuntimeDirectory = "proxy-suite-tor"; @@ -173,15 +188,18 @@ in }; # `proxy-ctl tor newnym` for userControl's group ("services" scope), which cannot open - # the control socket. Root. + # the control socket. As Tor's own user: root without capabilities could not even enter + # the 0700 control directory. services.proxy-suite.internal.services.proxy-suite-tor-newnym = lib.mkIf privileged { description = "proxy-suite - new Tor circuits for new connections"; after = [ "proxy-suite-tor.service" ]; # Only a running Tor: this never starts one. unitConfig.Requisite = [ "proxy-suite-tor.service" ]; - serviceConfig = { + serviceConfig = unprivilegedServiceConfig [ ] // { Type = "oneshot"; ExecStart = newnymScript; + # A filesystem socket is all it opens. + RestrictAddressFamilies = [ "AF_UNIX" ]; }; }; } diff --git a/modules/proxy-suite/warp.nix b/modules/proxy-suite/warp.nix index 6290e7a..8279054 100644 --- a/modules/proxy-suite/warp.nix +++ b/modules/proxy-suite/warp.nix @@ -38,7 +38,7 @@ let # Fallback: a third-party generator registers from abroad and hands the profile back. # curl follows HTTPS_PROXY when it is set. generate() { - body=$(${pkgs.curl}/bin/curl -fsS --max-time 60 -A proxy-suite \ + body=$(${pkgs.curl}/bin/curl -fsS --max-time 60 --proto-redir =https -A proxy-suite \ ${lib.escapeShellArg w.generatorUrl}) || return 1 case "$body" in "[Interface]"*) printf '%s\n' "$body" ;; @@ -65,8 +65,14 @@ let proxied() { HTTPS_PROXY="socks5://''${userinfo}${hostPart}:${toString listener.port}" "$@" } - proxied register || register${fallbacks}${ - lib.optionalString (w.generatorUrl != null) " || proxied generate" + ${ + # Direct, as the service user: past the kill switch (killSwitch.directFallbacks). + if derived.killSwitchEnabled && !cfg.killSwitch.directFallbacks then + "proxied register${lib.optionalString (w.generatorUrl != null) " || proxied generate"}" + else + "proxied register || register${fallbacks}${ + lib.optionalString (w.generatorUrl != null) " || proxied generate" + }" } '' else @@ -132,6 +138,16 @@ in echo "proxy-suite: waiting for the WARP profile at $profile" >&2 until [ -s "$profile" ]; do sleep 5; done fi + # Root reads a profile in the service user's directory through no symlink, FIFO or endless + # file; one in a directory of root's (a secret's symlink) as it is. + if [ "$(${pkgs.coreutils}/bin/stat -L -c %u -- "$(${pkgs.coreutils}/bin/dirname -- "$profile")")" != 0 ]; then + (umask 077 && ${pkgs.coreutils}/bin/dd if="$profile" iflag=nofollow,nonblock bs=65536 count=1 status=none \ + > "$RUNTIME_DIRECTORY/warp-profile.conf") || { + echo "proxy-suite: the WARP profile at $profile is not a regular file" >&2 + exit 1 + } + profile="$RUNTIME_DIRECTORY/warp-profile.conf" + fi ''; inherit (d) tunnelPort @@ -152,20 +168,27 @@ in # Retried until it registers. Not a oneshot: a slow or failed registration must not # hold up or fail a switch. startLimitIntervalSec = 0; - serviceConfig = unprivilegedServiceConfig [ ] // { - Type = "simple"; - RemainAfterExit = true; - Restart = "on-failure"; - RestartSec = 30; - StateDirectory = "proxy-suite/${d.stateSubdir}"; - StateDirectoryMode = "0700"; - WorkingDirectory = "${derived.constants.stateDir}/${d.stateSubdir}"; - UMask = "0077"; - LoadCredential = lib.optional ( - cfg.proxy.enable && withProxyAuth - ) "proxy-password:${passwordSource}"; - ExecStart = registerScript; - }; + # Its direct lookups work under the kill switch: a global WARP profile waits on it. + # Through the proxy, wgcf hands the name over. + serviceConfig = + unprivilegedServiceConfig [ ] + // lib.optionalAttrs (!cfg.proxy.enable || cfg.killSwitch.directFallbacks) ( + derived.constants.killSwitchOwnLookups pkgs + ) + // { + Type = "simple"; + RemainAfterExit = true; + Restart = "on-failure"; + RestartSec = 30; + StateDirectory = "proxy-suite/${d.stateSubdir}"; + StateDirectoryMode = "0700"; + WorkingDirectory = "${derived.constants.stateDir}/${d.stateSubdir}"; + UMask = "0077"; + LoadCredential = lib.optional ( + cfg.proxy.enable && withProxyAuth + ) "proxy-password:${passwordSource}"; + ExecStart = registerScript; + }; }; # Only pulls registration in: a simple unit gives the profile no ordering guarantee. diff --git a/modules/proxy-suite/wg-tunnel.nix b/modules/proxy-suite/wg-tunnel.nix index c873467..be1983b 100644 --- a/modules/proxy-suite/wg-tunnel.nix +++ b/modules/proxy-suite/wg-tunnel.nix @@ -25,9 +25,14 @@ let # Past TUN and TProxy. Setting a mark takes CAP_NET_ADMIN, which a rootless host lacks, # and has nothing to capture its traffic anyway. mark = if cfg.host.privileged then cfg.proxy.tproxy.proxyMark else null; + # The tunnel's own listener takes the hop login ($HOP_PASSWORD), from curl's stdin. probe = port: url: '' - ${pkgs.curl}/bin/curl -s --noproxy "" -x socks5h://127.0.0.1:${toString port} -m "$timeout" \ - -o /dev/null ${url}''; + printf 'proxy-user = "${derived.constants.hopUser}:%s"\n' "$HOP_PASSWORD" | ${pkgs.curl}/bin/curl -K - -s --noproxy "" \ + -x socks5h://127.0.0.1:${toString port} -m "$timeout" -o /dev/null ${url}''; + # direct-in takes the login the start drew ($DIRECT_AUTH), from curl's stdin: argv is public. + probeDirect = port: url: '' + printf 'proxy-user = "probe:%s"\n' "$DIRECT_AUTH" | ${pkgs.curl}/bin/curl -K - -s --noproxy "" \ + -x socks5h://127.0.0.1:${toString port} -m "$timeout" -o /dev/null ${url}''; # Some lines drop a share of fresh handshakes for good, and both engines retry on the # same source port forever. A new process binds a new port, so the watchdog exits when @@ -36,10 +41,9 @@ let # gets three misses. sing-box's "direct-in" listener reaches Cloudflare through the uplink # with the backend's mark (not urlTest.url, which is picked to be blocked here): when that # fails too, the tunnel could not work from a new port either. wireproxy has no such - # listener (directPort = null), so it is restarted either way. + # listener (directPort = null), so it is restarted either way. The tag is $TUNNEL_TAG. mkWatchdog = { - tag, command, tunnelPort, directPort, @@ -57,13 +61,13 @@ let kill -0 "$tunnel" 2>/dev/null || { wait "$tunnel"; exit 1; } timeout=$(( healthy ? 10 : 4 )) if ${probe tunnelPort "-f ${lib.escapeShellArg cfg.proxy.urlTest.url}"}; then - (( healthy )) || echo "proxy-suite: ${tag} is answering" >&2 + (( healthy )) || echo "proxy-suite: $TUNNEL_TAG is answering" >&2 healthy=1 failures=0 uplink_down=0 continue fi ${lib.optionalString (directPort != null) '' - if ! ${probe directPort "https://1.1.1.1/cdn-cgi/trace"}; then - (( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging ${tag}" >&2 + if ! ${probeDirect directPort "https://1.1.1.1/cdn-cgi/trace"}; then + (( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging $TUNNEL_TAG" >&2 uplink_down=1 failures=0 since=$SECONDS continue fi @@ -71,10 +75,10 @@ let uplink_down=0 # proxy-suite-outbound-groups hears of the first miss: a failover group moves off it now. if (( healthy && failures == 0 )) && [[ -d ${hintDir} ]]; then - ${pkgs.coreutils}/bin/touch ${hintDir}/${lib.escapeShellArg tag} 2>/dev/null || true + ${pkgs.coreutils}/bin/touch "${hintDir}/$TUNNEL_TAG" 2>/dev/null || true fi if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then - echo "proxy-suite: ${tag} is not answering; restarting the tunnel on a new source port" >&2 + echo "proxy-suite: $TUNNEL_TAG is not answering; restarting the tunnel on a new source port" >&2 kill "$tunnel" wait "$tunnel" exit 1 @@ -88,7 +92,6 @@ let # rather than baked into the store; the engine itself runs as ${serviceUser}. singBoxEngine = { - tag, tunnelPort, directPort, endpoint, @@ -96,15 +99,19 @@ let }: { convert = '' - endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag}${markArg "--routing-mark"}${ + endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag "$TUNNEL_TAG"${markArg "--routing-mark"}${ lib.optionalString (endpoint != null) " --endpoint ${lib.escapeShellArg endpoint}" } < "$profile") + # direct-in gets past TProxy and the kill switch: a login drawn per start keeps other local + # users off it (read from the environment, as argv is public). + DIRECT_AUTH=$(${pkgs.coreutils}/bin/od -An -tx1 -N16 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n') + export DIRECT_AUTH # From a pipe: the endpoint holds the private key, and argv is public. - (umask 027 && ${pkgs.jq}/bin/jq -n --slurpfile ep <(printf '%s' "$endpoint") '$ep[0] as $ep | { + (umask 027 && ${pkgs.jq}/bin/jq -n --arg tag "$TUNNEL_TAG" --slurpfile ep <(printf '%s' "$endpoint") '$ep[0] as $ep | { log: {level: "warn"}, dns: {servers: [ ${builtins.toJSON (dnsServer "local" cfg.proxy.dns.local)}, - (${builtins.toJSON (dnsServer "remote" cfg.proxy.dns.remote)} + {detour: "${tag}", domain_resolver: "local"}) + (${builtins.toJSON (dnsServer "remote" cfg.proxy.dns.remote)} + {detour: $tag, domain_resolver: "local"}) ]}, route: { default_domain_resolver: ${ @@ -119,11 +126,13 @@ let ) }, rules: [{inbound: ["direct-in"], outbound: "direct"}], - final: "${tag}" + final: $tag }, inbounds: [ - {type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString tunnelPort}}, - {type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString directPort}} + {type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString tunnelPort}, + users: [{username: "${derived.constants.hopUser}", password: $ENV.HOP_PASSWORD}]}, + {type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString directPort}, + users: [{username: "probe", password: $ENV.DIRECT_AUTH}]} ], outbounds: [{type: "direct", tag: "direct"${ lib.optionalString (mark != null) ", routing_mark: ${toString mark}" @@ -154,13 +163,13 @@ let # `endpoint`, a host:port in place of the profile's Endpoint, and `domainStrategy`, the # address family it dials destinations over first. # - # A template unit passes `tag` and `tunnelPort` as shell words ("$TUNNEL_TAG") that - # `profile` exports: the watchdog runs as a script of its own, after the exec. + # The tag comes from $TUNNEL_TAG, never spliced in (an attribute name can hold anything). A + # template unit passes `tag = null` and `tunnelPort = "$TUNNEL_PORT"`, both from `profile`. mkTunnel = { description, unit, - tag, + tag ? null, profile, tunnelPort, directPort ? null, @@ -176,7 +185,6 @@ let let chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) { inherit - tag tunnelPort directPort endpoint @@ -185,7 +193,14 @@ let }; tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" '' set -euo pipefail + ${lib.optionalString (tag != null) "TUNNEL_TAG=${lib.escapeShellArg tag}"} ${profile} + export TUNNEL_TAG + # The hop login (constants.ensureHopLogin): the backend dials the listener with it, + # and the watchdog probes it so. Through the environment alone: argv is public. + ${derived.constants.ensureHopLogin pkgs} + HOP_PASSWORD=$(< ${lib.escapeShellArg derived.constants.hopLoginFile}) + export HOP_PASSWORD ${chosen.convert} ${ifPrivileged '' @@ -195,7 +210,7 @@ let exec ${runAsServiceUser pkgs [ "net_admin" ]} ${ mkWatchdog { - inherit tag tunnelPort; + inherit tunnelPort; inherit (chosen) command directPort; } } @@ -212,9 +227,26 @@ let ExecStart = if execArgs == "" then tunnelScript else "${tunnelScript}${execArgs}"; Restart = restart; RestartSec = 2; + # A profile that fails for good backs off to a minute rather than going through its + # conversion as root every 2 s. + RestartSteps = 5; + RestartMaxDelaySec = 60; RuntimeDirectory = runtimeDirectory; RuntimeDirectoryMode = "0750"; UMask = "0077"; + } + # Root only converts the profile; the engine gets net_admin alone. No ProtectHome: a + # configFile may sit under /home or /root. + // lib.optionalAttrs cfg.host.privileged { + NoNewPrivileges = true; + PrivateTmp = true; + ProtectSystem = "strict"; + # The watchdog's hints go to proxy-suite-outbound-groups' directory, which comes and + # goes with that unit: a bind of the directory itself would go stale. + ReadWritePaths = [ derived.constants.runtimeDir ]; + ProtectKernelTunables = true; + ProtectControlGroups = true; + RestrictSUIDSGID = true; }; }; in diff --git a/modules/proxy-suite/whitelist-bypass.nix b/modules/proxy-suite/whitelist-bypass.nix index 478658a..35f50d3 100644 --- a/modules/proxy-suite/whitelist-bypass.nix +++ b/modules/proxy-suite/whitelist-bypass.nix @@ -9,7 +9,11 @@ let w = derived.whitelistBypassCfg; - inherit (derived.constants) unprivilegedServiceConfig privileged serviceUser; + inherit (derived.constants) + unprivilegedServiceConfig + privileged + serviceUser + ; inherit (derived.localProxy) auth; # A file in the state directory, which the whitelistBypass scope's group writes to: a @@ -33,6 +37,9 @@ let groupAccess = privileged && derived.userControlAnyAllows "whitelistBypass"; stateDir = "${derived.constants.stateDir}/whitelist-bypass"; stateMode = if groupAccess then "0770" else "0700"; + # The creators' logins, which they rewrite as they run: the daemon's alone, out of the + # group's directory. + sessionsDir = "${derived.constants.stateDir}/whitelist-bypass-sessions"; stateGroup = if privileged && derived.userControlAllows "whitelistBypass" then cfg.userControl.group @@ -55,12 +62,17 @@ let // { Restart = "always"; RestartSec = 5; + RestartSteps = 5; + RestartMaxDelaySec = 120; StateDirectory = "proxy-suite/whitelist-bypass"; StateDirectoryMode = stateMode; } # The group writes the state directory: whatever a name there points at, the daemon - # writes nowhere else. - // lib.optionalAttrs privileged { ProtectSystem = "strict"; } + # writes nowhere else but the creators' sessions ("-": none without creators). + // lib.optionalAttrs privileged { + ProtectSystem = "strict"; + ReadWritePaths = [ "-${sessionsDir}" ]; + } // lib.optionalAttrs groupAccess { Group = stateGroup; } // serviceConfig; }; @@ -77,8 +89,15 @@ let # The link from the environment (pkgs/whitelist-bypass.nix): argv is public. WB_LINK=$(${readState ''"$join"''} | tr -d '[:space:]') export WB_LINK - exec ${w.package}/bin/headless-${j.platform}-joiner --socks-port ${toString j.port} + # Its listener takes the hop login, which the backend dials it with; the password + # from the environment as well. + WB_SOCKS_PASS=$(< ${lib.escapeShellArg derived.constants.hopLoginFile}) + export WB_SOCKS_PASS + exec ${w.package}/bin/headless-${j.platform}-joiner --socks-port ${toString j.port} \ + --socks-user ${derived.constants.hopUser} ''; + # Root draws it, where nothing has yet this boot (the daemon cannot write there). + ExecStartPre = "+${derived.constants.ensureHopLogin pkgs}"; LoadCredential = lib.optional (j.linkFile != null) "link:${j.linkFile}"; } // lib.optionalAttrs (j.linkFile == null) (waitFor "${j.tag}.join") @@ -92,10 +111,19 @@ let unit = mkUnit "proxy-suite - whitelist-bypass creator ${name}" { ExecStart = pkgs.writeShellScript "proxy-suite-wb-creator-${name}" '' set -euo pipefail - cookies="$STATE_DIRECTORY/${name}.cookies.json" + shared="$STATE_DIRECTORY/${name}.cookies.json" + cookies=${lib.escapeShellArg "${sessionsDir}/${name}.cookies.json"} links="$STATE_DIRECTORY/${name}.link" - # The creator opens it by name: not through a symlink the group left there. - if [ -L "$cookies" ]; then rm -f -- "$cookies"; fi + umask 077 + # A login `proxy-ctl wl auth` left replaces the working copy, read without following + # a symlink, then goes: what the creator refreshes is the copy's. + if [ -L "$shared" ]; then + rm -f -- "$shared" + elif [ -f "$shared" ]; then + ${readState ''"$shared"''} > "$cookies.new" + mv -f -- "$cookies.new" "$cookies" + rm -f -- "$shared" + fi ${lib.optionalString (c.cookiesFile != null) '' [ -e "$cookies" ] || install -m 600 "$CREDENTIALS_DIRECTORY/cookies" "$cookies" ''} @@ -127,8 +155,14 @@ let lib.nameValuePair "proxy-suite-wb-creator-${name}" ( unit // lib.optionalAttrs viaProxy { after = unit.after ++ [ "proxy-suite-socks.service" ]; } - # Without a login it has nothing to run on until `proxy-ctl wl auth` writes one. - // lib.optionalAttrs (c.cookiesFile == null) (waitFor "${name}.cookies.json") + # Without a login it has nothing to run on until `proxy-ctl wl auth` writes one, or + # one is in its working copy already. + // lib.optionalAttrs (c.cookiesFile == null) { + unitConfig.ConditionPathExists = [ + "|%S/proxy-suite/whitelist-bypass/${name}.cookies.json" + "|${sessionsDir}/${name}.cookies.json" + ]; + } ); in { @@ -138,6 +172,9 @@ in ); tmpfiles = [ "d ${stateDir} ${stateMode} ${if privileged then "${serviceUser} ${stateGroup}" else "- -"} -" - ]; + ] + ++ + lib.optional (w.creators != { }) + "d ${sessionsDir} 0700 ${if privileged then "${serviceUser} ${serviceUser}" else "- -"} -"; }; } diff --git a/modules/proxy-suite/zapret.nix b/modules/proxy-suite/zapret.nix index 6e25250..6d8592f 100644 --- a/modules/proxy-suite/zapret.nix +++ b/modules/proxy-suite/zapret.nix @@ -26,7 +26,8 @@ let ; }) awgServiceNames - perAppConflicts + perAppRefuseUnderGlobal + daemonSandbox perAppZapretMarkUpScript perAppZapretMarkDownScript ; @@ -46,6 +47,7 @@ let ; iptables = "${pkgs.iptables}/bin/iptables"; + ip6tables = "${pkgs.iptables}/bin/ip6tables"; zapretCommonPreStart = package: '' ${package}/opt/zapret/init.d/sysv/zapret stop || true @@ -59,22 +61,24 @@ let fi ''; + # An IPv6 range to iptables failed the script (set -e), and every range after it with it. + tablesFor = cidr: if lib.hasInfix ":" cidr then ip6tables else iptables; exemptStart = '' set -euo pipefail '' + lib.concatMapStrings (cidr: '' - while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done - while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done - ${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN - ${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN + while ${tablesFor cidr} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done + while ${tablesFor cidr} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done + ${tablesFor cidr} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN + ${tablesFor cidr} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN '') zapretCfg.cidrExemption.cidrs; exemptStop = '' set +e '' + lib.concatMapStrings (cidr: '' - while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done - while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done + while ${tablesFor cidr} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done + while ${tablesFor cidr} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done '') zapretCfg.cidrExemption.cidrs; in { @@ -100,24 +104,36 @@ in extraServiceConfig = { ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart"; Environment = globalZapretEnv; - }; + } + // daemonSandbox; }); services.proxy-suite.internal.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable - (mkOneshotService { - description = "proxy-suite per-app-routing zapret backend"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - conflicts = perAppConflicts ++ awgServiceNames; - preStart = zapretCommonPreStart perAppZapretPackage; - runtimeDirectory = "proxy-suite-per-app-zapret"; - execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start"; - execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop"; - execStartPre = "${perAppZapretMarkUpScript}"; - execStopPost = "${perAppZapretMarkDownScript}"; - extraServiceConfig.Environment = perAppZapretEnv; - }); + ( + lib.mkMerge [ + (mkOneshotService { + description = "proxy-suite per-app-routing zapret backend"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + preStart = zapretCommonPreStart perAppZapretPackage; + runtimeDirectory = "proxy-suite-per-app-zapret"; + execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start"; + execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop"; + execStartPre = "${perAppZapretMarkUpScript}"; + execStopPost = "${perAppZapretMarkDownScript}"; + extraServiceConfig = { + Environment = perAppZapretEnv; + } + // daemonSandbox; + }) + { + # Ahead of everything, preStart's script among them (mkBefore there): under a global + # mode nothing of it runs, not even the queue's firewall rules. + serviceConfig.ExecStartPre = lib.mkOrder 400 [ perAppRefuseUnderGlobal ]; + } + ] + ); services.proxy-suite.internal.services.proxy-suite-zapret-vm-exempt = lib.mkIf (zapretGlobalEnabled && zapretCfg.cidrExemption.enable) diff --git a/modules/proxy-suite/zapret/common.nix b/modules/proxy-suite/zapret/common.nix index 32a8cc3..b3aa0b9 100644 --- a/modules/proxy-suite/zapret/common.nix +++ b/modules/proxy-suite/zapret/common.nix @@ -36,10 +36,37 @@ in ); # The transparent backends steer the same packets; a per-app zapret instance replaces them. - perAppConflicts = [ - "proxy-suite-tproxy.service" - "proxy-suite-tun.service" - ]; + # The zapret units run as root: capabilities bounded to what the init scripts and nfqws + # use, and no new privileges (nfqws narrows itself further). + daemonSandbox = lib.optionalAttrs cfg.host.privileged { + NoNewPrivileges = true; + CapabilityBoundingSet = [ + "CAP_NET_ADMIN" + "CAP_NET_RAW" + "CAP_SETUID" + "CAP_SETGID" + "CAP_SETPCAP" + "CAP_SYS_MODULE" + "CAP_CHOWN" + "CAP_FOWNER" + "CAP_DAC_OVERRIDE" + "CAP_KILL" + ]; + LockPersonality = true; + RestrictRealtime = true; + }; + # The per-app instance's ExecStartPre: it has nothing to add under a global mode, which + # it never displaces (constants.refuseUnderGlobal); those take it down as they start. + perAppRefuseUnderGlobal = derived.constants.refuseUnderGlobal pkgs ( + [ + "proxy-suite-tproxy.service" + "proxy-suite-tun.service" + ] + ++ map (name: "proxy-suite-awg-${name}.service") ( + builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) + ) + ++ lib.optional derived.awgRuntimeGlobal "proxy-suite-awg@*.service" + ); perAppZapretMarkUpScript = pkgs.writeShellScript scriptName '' set -euo pipefail diff --git a/modules/proxy-suite/zapret2.nix b/modules/proxy-suite/zapret2.nix index a474010..8d0fbf4 100644 --- a/modules/proxy-suite/zapret2.nix +++ b/modules/proxy-suite/zapret2.nix @@ -38,7 +38,8 @@ let }) awgServiceNames tunInterfaces - perAppConflicts + perAppRefuseUnderGlobal + daemonSandbox perAppZapretMarkUpScript perAppZapretMarkDownScript ; @@ -89,17 +90,22 @@ let # nfqws2 and proxy-ctl expect the list files to exist. With userControl its group # edits them: proxy-ctl renames a new list in, so the directories are what it writes. + stateDirMode = + if userControlAllows "zapret" then + "2775 -g ${lib.escapeShellArg cfg.userControl.group}" + # userControl.groups only, through ACLs: the group bits (their mask) stay open. + else if userControlAnyAllows "zapret" then + "2775" + else + "0755"; mkPreStart = '' ${lib.getExe' pkgs.kmod "modprobe"} nfnetlink_queue 2>/dev/null || true - install -d -m ${ - if userControlAllows "zapret" then - "2775 -g ${lib.escapeShellArg cfg.userControl.group}" - # userControl.groups only, through ACLs: the group bits (their mask) stay open. - else if userControlAnyAllows "zapret" then - "2775" - else - "0755" - } ${runtime.stateDir} ${runtime.circularStateDir} + install -d -m ${stateDirMode} ${runtime.stateDir} + # A plain mkdir, not install -d, which would chmod and chown a symlink a member left in the + # group's state directory. + circular=${runtime.circularStateDir} + if [ -L "$circular" ]; then rm -f -- "$circular"; fi + mkdir -m ${lib.head (lib.splitString " " stateDirMode)} -- "$circular" 2>/dev/null || true touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile} # In this unit's sandbox: a name a member left here leads nowhere else. ${constants.grantDirAcl pkgs runtime.stateDir (userControlExtraGroupsFor "zapret") "rwX"} @@ -121,7 +127,8 @@ let // lib.optionalAttrs (userControlAllows "zapret") { Group = cfg.userControl.group; } # nfqws2 runs as root and writes its lists in a directory the zapret scope's group # writes to as well. - // constants.rootInSharedDirConfig; + // constants.rootInSharedDirConfig + // daemonSandbox; cutoff = import ./zapret2/cutoff.nix { inherit @@ -135,6 +142,25 @@ let directSync = import ./zapret2/direct-sync.nix { inherit lib pkgs cfg; }; + # autohostlist wants nf_conntrack_tcp_be_liberal on; the stop puts back what the host had. + # Outside the sandbox ("+"), which keeps /proc/sys read-only. + conntrackLiberalKey = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal"; + conntrackLiberalOn = "-+${pkgs.writeShellScript "proxy-suite-zapret2-liberal" '' + saved="$RUNTIME_DIRECTORY/conntrack-liberal" + # Created, never followed: this runs as root outside the sandbox. + if [ ! -e "$saved" ] && [ ! -L "$saved" ]; then + ${pkgs.coreutils}/bin/cat ${conntrackLiberalKey} | (set -o noclobber; cat > "$saved") 2>/dev/null || true + fi + echo 1 > ${conntrackLiberalKey} + ''}"; + conntrackLiberalRestore = "-+${pkgs.writeShellScript "proxy-suite-zapret2-liberal" '' + saved="$RUNTIME_DIRECTORY/conntrack-liberal" + value=$(${pkgs.coreutils}/bin/cat "$saved" 2>/dev/null || echo 0) + [[ $value =~ ^[01]$ ]] || value=0 + echo "$value" > ${conntrackLiberalKey} + ${pkgs.coreutils}/bin/rm -f "$saved" + ''}"; + in { services.proxy-suite.internal.services.proxy-suite-zapret2-direct = lib.mkIf ( @@ -166,7 +192,13 @@ in runtimeDirectory = "proxy-suite-zapret"; stateDirectory = "proxy-suite/zapret2"; execStart = "${runtime.daemonScript}"; - execStopPost = "${runtime.initScript} stop_fw"; + execStopPost = [ + "${runtime.initScript} stop_fw" + ] + ++ lib.optional zapretCfg.zapret2.autoHostlist.enable conntrackLiberalRestore; + # What zapret's start_fw would do for autohostlist, here outside the sandbox ("+"), + # once the firewall has loaded nf_conntrack. + execStartPost = if zapretCfg.zapret2.autoHostlist.enable then conntrackLiberalOn else null; extraServiceConfig = daemonConfig ( runtime.mkEnv { runtime = globalRuntime; @@ -177,25 +209,33 @@ in services.proxy-suite.internal.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable - (mkRestartingService { - description = "proxy-suite per-app-routing zapret2 backend"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - conflicts = perAppConflicts ++ awgServiceNames; - preStart = mkPreStart; - runtimeDirectory = "proxy-suite-per-app-zapret"; - stateDirectory = "proxy-suite/zapret2"; - execStart = "${runtime.daemonScript}"; - execStartPre = "${perAppZapretMarkUpScript}"; - execStopPost = [ - "${runtime.initScript} stop_fw" - "${perAppZapretMarkDownScript}" - ]; - extraServiceConfig = daemonConfig ( - runtime.mkEnv { - runtime = perAppRuntime; - pidDir = "/run/proxy-suite-per-app-zapret"; + ( + lib.mkMerge [ + (mkRestartingService { + description = "proxy-suite per-app-routing zapret2 backend"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + preStart = mkPreStart; + runtimeDirectory = "proxy-suite-per-app-zapret"; + stateDirectory = "proxy-suite/zapret2"; + execStart = "${runtime.daemonScript}"; + execStartPre = "${perAppZapretMarkUpScript}"; + execStopPost = [ + "${runtime.initScript} stop_fw" + "${perAppZapretMarkDownScript}" + ]; + extraServiceConfig = daemonConfig ( + runtime.mkEnv { + runtime = perAppRuntime; + pidDir = "/run/proxy-suite-per-app-zapret"; + } + ); + }) + { + # Ahead of everything, preStart's script among them (mkBefore there): under a global + # mode nothing of it runs, not even the queue's firewall rules. + serviceConfig.ExecStartPre = lib.mkOrder 400 [ perAppRefuseUnderGlobal ]; } - ); - }); + ] + ); } diff --git a/modules/proxy-suite/zapret2/cutoff-probe.template.sh b/modules/proxy-suite/zapret2/cutoff-probe.template.sh index 3a05068..d370052 100644 --- a/modules/proxy-suite/zapret2/cutoff-probe.template.sh +++ b/modules/proxy-suite/zapret2/cutoff-probe.template.sh @@ -11,9 +11,11 @@ for f in asn.txt sni.txt asn.new sni.new proxy.json proxy.json.tmp egress ts for done touch asn.txt sni.txt force=0 -if [ -e requests/force ]; then +if [ -e requests/force ] || [ -L requests/force ]; then force=1 - rm -f requests/force + # Whatever the group left under the name, a directory too: rm -f alone failed on one, and + # under set -e every run stopped here. + rm -rf -- requests/force fi now=$(date +%s) # Digits only: $(( )) would run what a[$(...)] in it names. diff --git a/modules/proxy-suite/zapret2/cutoff.nix b/modules/proxy-suite/zapret2/cutoff.nix index 17b600a..c36f6a6 100644 --- a/modules/proxy-suite/zapret2/cutoff.nix +++ b/modules/proxy-suite/zapret2/cutoff.nix @@ -104,7 +104,19 @@ in # `proxy-ctl zapret cutoff probe` drops its `force` file in requests/ instead. StateDirectoryMode = "0755"; } - // constants.rootInSharedDirConfig; + // constants.rootInSharedDirConfig + # z2k-detect's raw sockets, marks and nft table (NET_*); requests/, which the group writes + # (DAC_*, FOWNER). + // lib.optionalAttrs cfg.host.privileged { + CapabilityBoundingSet = [ + "CAP_NET_RAW" + "CAP_NET_ADMIN" + "CAP_DAC_OVERRIDE" + "CAP_DAC_READ_SEARCH" + "CAP_FOWNER" + ]; + NoNewPrivileges = true; + }; }; tmpfiles = [ diff --git a/modules/proxy-suite/zapret2/detect.lua b/modules/proxy-suite/zapret2/detect.lua index 2763b4e..28addec 100644 --- a/modules/proxy-suite/zapret2/detect.lua +++ b/modules/proxy-suite/zapret2/detect.lua @@ -30,33 +30,71 @@ local NOREPLY_MS = 4000 local STALL_MS = 6000 local SYN_MS = 3500 +-- Names in it come off the wire (a SNI): a newline would forge journal lines of its own. local function say(text) - io.stderr:write("zapret2: ", text, "\n") + io.stderr:write("zapret2: ", (tostring(text):gsub("%c", "?")), "\n") end -- --- verdicts -------------------------------------------------------------------------- local VERDICTS = os.getenv("PROXY_SUITE_ZAPRET2_VERDICTS") local status = {} -- "name proto" -> its last kind, so each change is written once +local status_count = 0 +-- Names past which no new one gets a verdict: every unanswered address a page dials would +-- add one for good (and a /32 to the proxy's rules), each read back whole on the next. +local MAX_VERDICT_KEYS = 20000 +local verdicts_full = false +-- Of them, addresses (ps_syn's), which a page can make by the thousand: never all of them. +local MAX_IP_VERDICT_KEYS = 2000 +local ip_count = 0 +local ip_full = false -- The last verdicts, as the file has them now: proxy-ctl's retries land there too. local function reload() local f = VERDICTS and io.open(VERDICTS, "r") if not f then return end - status = {} + status, status_count, ip_count = {}, 0, 0 for line in f:lines() do local kind, name, proto = line:match("^(%w+)\t([^\t]+)\t([^\t]*)") - if kind then status[name .. " " .. proto] = kind end + if kind then + local key = name .. " " .. proto + if status[key] == nil then + status_count = status_count + 1 + if proto == "ip" then ip_count = ip_count + 1 end + end + status[key] = kind + end end f:close() end reload() +-- A name as a rule can take it: the SNI comes from the wire, raw, and a tab or newline in it +-- would forge lines of its own in the verdicts and lists. +local function plain(name) + return type(name) == "string" and name:match("^[%w%.%-_:]+$") ~= nil +end + local function verdict(kind, name, proto, note) + if not plain(name) then return end local key = name .. " " .. proto if not VERDICTS or status[key] == kind then return end reload() if status[key] == kind then return end + if status[key] == nil and status_count >= MAX_VERDICT_KEYS then + if not verdicts_full then say("no verdict for " .. name .. ": " .. VERDICTS .. " holds " .. MAX_VERDICT_KEYS .. " names already") end + verdicts_full = true + return + end + if status[key] == nil and proto == "ip" and ip_count >= MAX_IP_VERDICT_KEYS then + if not ip_full then say("no verdict for " .. name .. ": " .. VERDICTS .. " holds " .. MAX_IP_VERDICT_KEYS .. " addresses already") end + ip_full = true + return + end + if status[key] == nil then + status_count = status_count + 1 + if proto == "ip" then ip_count = ip_count + 1 end + end status[key] = kind local f = io.open(VERDICTS, "a") if not f then return end @@ -193,10 +231,67 @@ end local stalled = {} -- host -> a transfer of it was cut short, within the window +-- A name a site can have: two labels at least, none empty, and not a public suffix (com, +-- co.uk), which would take every site under it. +local function learnable(host) + if not plain(host) or host:find("^%.") or host:find("%.$") or host:find("%.%.") or not host:find("%.") then + return false + end + return not proxy_suite_is_public_suffix(host) +end + +-- Learned names, and verdicts' names, past which no new one is taken: a wildcard domain's +-- fresh names would grow the lists without end. Real use stays far below. +local MAX_AUTO_LINES = 20000 + +local function bounded(t, count) + if count > 4096 then return {}, 1 end + return t, count +end +local learned_count, stalled_count = 0, 0 +local auto_full = false + +-- The site a name belongs to: the public suffix and one label more (example.co.uk). +local function registrable(host) + local labels = {} + for label in host:gmatch("[^.]+") do labels[#labels + 1] = label end + for i = #labels - 1, 1, -1 do + local candidate = table.concat(labels, ".", i) + if not proxy_suite_is_public_suffix(candidate) then return candidate end + end + return host +end + +-- Names of one site past which the site itself is learned instead, so one wildcard domain +-- cannot fill the list. +local MAX_NAMES_PER_SITE = 64 + local function learn(host, arg, n) + if not learnable(host) then return end + local site = registrable(host) + if site ~= host and learnable(site) then + local same, tail = 0, "." .. site + for _, line in ipairs(lines(arg.auto)) do + if line:sub(-#tail) == tail then same = same + 1 end + end + if same >= MAX_NAMES_PER_SITE then + say(site .. " has " .. same .. " names learned: learning the site instead of " .. host) + host = site + end + end + if not learned[host] then + learned, learned_count = bounded(learned, learned_count + 1) + end learned[host] = true if stalled[host] then verdict("stalls", host, "cutoff", "learned from transfers cut short") end - if covered(host, lines(arg.auto)) then return end + local auto = lines(arg.auto) + if covered(host, auto) then return end + if #auto >= MAX_AUTO_LINES then + if not auto_full then say("not learning " .. host .. ": " .. arg.auto .. " holds " .. MAX_AUTO_LINES .. " names already") end + auto_full = true + return + end + auto_full = false local f = io.open(arg.auto, "a") if not f then say("cannot learn " .. host .. ": " .. arg.auto .. " is not writable") @@ -227,7 +322,10 @@ local function failure(st, arg, why, stall) st.counted = true local host = st.host if learned[host] or excluded(host, arg) then return end - if stall then stalled[host] = true end + if stall and not stalled[host] then + stalled, stalled_count = bounded(stalled, stalled_count + 1) + stalled[host] = true + end local n, need = tally(host, tonumber(arg.time) or 300), tonumber(arg.fails) or 3 if arg.log then say(host .. ": " .. why .. " (" .. n .. "/" .. need .. " to learn)") end if n >= need then learn(host, arg, n) end diff --git a/modules/proxy-suite/zapret2/direct-sync.template.sh b/modules/proxy-suite/zapret2/direct-sync.template.sh index 644ae7a..b61a57c 100644 --- a/modules/proxy-suite/zapret2/direct-sync.template.sh +++ b/modules/proxy-suite/zapret2/direct-sync.template.sh @@ -13,10 +13,12 @@ export PATH=@path@ dir=$1 out=$2 +# The zapret scope's group writes these: never through a symlink it left (to a file only +# root may read, which would land in the world-readable rule-sets), nor into a FIFO. lists() { local f for f in "$@"; do - [ -r "$f" ] && cat "$f" + [ -r "$f" ] && dd if="$f" iflag=nofollow,nonblock status=none 2>/dev/null done true } @@ -31,15 +33,28 @@ write() { } # nfqws hostlists: one host per line, "#" comments, "^" for the name alone. -hosts='def hosts: split("\n") | map(gsub("^\\s+|\\s+$"; "") | ascii_downcase | ltrimstr("^")) - | map(select(. != "" and (startswith("#") | not))); +# The zapret scope can write them, and an entry sing-box cannot take (999.1.1.1, ::/0, +# fe80::1%eth0) would fail the rule-set and the proxy with it: only an address or a name. +hosts='def octet: "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"; + def ipv4: test("^(" + octet + "\\.){3}" + octet + "$"); + def ipv6: test("^[0-9a-f:]+$") and test(":::") == false + and (split("::") | length) <= 2 + and (split(":") | map(select(. != "")) | length <= 8 and all(length <= 4)) + and (test("::") or (split(":") | length) == 8) + and test("^:[^:]|[^:]:$") == false; + # Two labels at least: a bare "com" would send the whole TLD past the proxy. + def hostname: test("^[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?(\\.[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?)+$") + and test("^[0-9.]+$") == false and length <= 253; + def valid: ipv4 or ipv6 or hostname; + def hosts: split("\n") | map(gsub("^\\s+|\\s+$"; "") | ascii_downcase | ltrimstr("^")) + | map(select(. != "" and (startswith("#") | not) and valid)); def ip: test("^[0-9.]+$|:"); def cidr: map(. + (if test(":") then "/128" else "/32" end)); # A name and a site key cover each other either way round: www.notion.so and notion.so. def covers($b): . as $a | $a == $b or ($a | endswith("." + $b)) or ($b | endswith("." + $a)); # "kindnameproto...", the last per name and proto. # The zapret scope'"'"'s group can write the file: only names a rule can take. - def verdicts: split("\n") | map(split("\t") | select(length >= 3 and (.[1] | test("^[a-z0-9.-]+$|^[0-9a-f:.]+$")))) + def verdicts: split("\n") | map(split("\t") | select(length >= 3 and (.[1] | test("^[a-z0-9.-]+$|^[0-9a-f:.]+$") and valid))) | reduce .[] as $v ({}; .[$v[1] + "\t" + $v[2]] = $v[0]) | to_entries | map({name: (.key | split("\t")[0]), proto: (.key | split("\t")[1]), kind: .value}); def named($kind; $proto): map(select(.kind == $kind and .proto == $proto) | .name);' diff --git a/modules/proxy-suite/zapret2/public-suffix-hostkey.lua b/modules/proxy-suite/zapret2/public-suffix-hostkey.lua index 27dcd84..a673f34 100644 --- a/modules/proxy-suite/zapret2/public-suffix-hostkey.lua +++ b/modules/proxy-suite/zapret2/public-suffix-hostkey.lua @@ -44,6 +44,14 @@ local function public_suffix_nld(host, nld) return key end +-- For detect.lua (a chunk of its own): whether host is itself a public suffix, or a single +-- label, which no site is. +function proxy_suite_is_public_suffix(host) + local labels = {} + for label in host:lower():gsub("%.$", ""):gmatch("[^.]+") do labels[#labels + 1] = label end + return #labels <= suffix_labels(labels) +end + local standard = standard_hostkey if type(standard) ~= "function" then error("proxy-suite: zapret-auto.lua no longer defines standard_hostkey") diff --git a/modules/proxy-suite/zapret2/public-suffixes.py b/modules/proxy-suite/zapret2/public-suffixes.py index bf878cb..0cb3600 100644 --- a/modules/proxy-suite/zapret2/public-suffixes.py +++ b/modules/proxy-suite/zapret2/public-suffixes.py @@ -1,7 +1,11 @@ # The ICANN section of the public suffix list, one rule per line, every label in the -# xn-- form a TLS SNI carries ("рф" is "xn--p1ai" on the wire). +# xn-- form a TLS SNI carries ("рф" is "xn--p1ai" on the wire). With --private, the +# PRIVATE section too (workers.dev, github.io): names there belong to unrelated parties. import sys +with_private = "--private" in sys.argv[1:] +source = next(arg for arg in sys.argv[1:] if arg != "--private") + def ascii_label(label): return label if label == "*" or label.isascii() else "xn--" + label.encode("punycode").decode() @@ -14,12 +18,14 @@ def ascii_rule(rule): inside = False rules = [] -with open(sys.argv[1], encoding="utf-8") as f: +with open(source, encoding="utf-8") as f: for line in f: line = line.strip() - if line == "// ===BEGIN ICANN DOMAINS===": + if line == "// ===BEGIN ICANN DOMAINS===" or (with_private and line == "// ===BEGIN PRIVATE DOMAINS==="): inside = True - elif line == "// ===END ICANN DOMAINS===": + elif line == "// ===END ICANN DOMAINS===" and with_private: + inside = False + elif line in ("// ===END ICANN DOMAINS===", "// ===END PRIVATE DOMAINS==="): break elif inside and line and not line.startswith("//"): rules.append(ascii_rule(line.split()[0])) diff --git a/modules/proxy-suite/zapret2/runtime.nix b/modules/proxy-suite/zapret2/runtime.nix index 2cef02b..df2ec47 100644 --- a/modules/proxy-suite/zapret2/runtime.nix +++ b/modules/proxy-suite/zapret2/runtime.nix @@ -238,6 +238,9 @@ let [ "# Generated by proxy-suite. Do not edit." "WS_USER=root" + # /proc/sys is read-only in the units' sandbox: the unit sets autohostlist's + # nf_conntrack_tcp_be_liberal itself, outside it. + "SKIP_CONNTRACK_LIBERAL_MODE=1" "FWTYPE=nftables" "INIT_APPLY_FW=1" "QNUM=${toString qnum}" diff --git a/modules/proxy-suite/zapret2/strategy-log.lua b/modules/proxy-suite/zapret2/strategy-log.lua index 517e8ee..57e72d9 100644 --- a/modules/proxy-suite/zapret2/strategy-log.lua +++ b/modules/proxy-suite/zapret2/strategy-log.lua @@ -18,7 +18,8 @@ local function name(hrec) end local function log(hrec, text) - io.stderr:write("zapret2: ", name(hrec), ": ", text, "\n") + -- The host comes off the wire (a SNI): no control character, so no forged journal line. + io.stderr:write("zapret2: ", (tostring(name(hrec)):gsub("%c", "?")), ": ", (tostring(text):gsub("%c", "?")), "\n") end local function of(hrec) diff --git a/nix/checks.nix b/nix/checks.nix index 0dc465d..f20862a 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -66,6 +66,9 @@ moduleSuiteChecks proxy-suite-hosts = builtins.seq (builtins.deepSeq hostChecks.assertions true) ( pkgs.writeText "proxy-suite-hosts-check" "ok" ); + backend-config-validation = import ./checks/backend-config-validation.nix { + inherit pkgs checkLib; + }; proxy-helpers = import ./checks/proxy-helpers.nix { inherit pkgs; inherit (checkLib) evalProxySuite; diff --git a/nix/checks/amnezia-wg-outbound.nix b/nix/checks/amnezia-wg-outbound.nix index 398b418..9d8b499 100644 --- a/nix/checks/amnezia-wg-outbound.nix +++ b/nix/checks/amnezia-wg-outbound.nix @@ -158,9 +158,10 @@ in singBoxStart; assert hasInfix "_proxy_suite_record_tag_source plain awg" singBoxStart; assert hasInfix "--output \"$profile\"" plainTunnel && !(hasInfix "--outbound-fwmark" plainTunnel); - assert hasInfix "warp_outbound.py --tag plain --routing-mark 2" plainTunnel; + assert hasInfix "TUNNEL_TAG=plain\n" plainTunnel; + assert hasInfix ''warp_outbound.py --tag "$TUNNEL_TAG" --routing-mark 2'' plainTunnel; assert hasInfix "listen_port: 18602" plainTunnel; - assert hasInfix ''detour: "plain"'' plainTunnel; + assert hasInfix "detour: $tag" plainTunnel; assert !(services ? proxy-suite-awg-plain-watchdog); true ) diff --git a/nix/checks/amnezia-wg.nix b/nix/checks/amnezia-wg.nix index d6b5cb4..ec8dab1 100644 --- a/nix/checks/amnezia-wg.nix +++ b/nix/checks/amnezia-wg.nix @@ -288,11 +288,16 @@ in assert builtins.elem "proxy-suite-tun.service" homeService.conflicts; assert builtins.elem "proxy-suite-tproxy.service" homeService.conflicts; assert builtins.elem "proxy-suite-zapret.service" homeService.conflicts; - assert builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts; + # Per-app zapret never takes a global profile down: the profile stops it as it starts. + assert !(builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts); + assert pkgs.lib.hasInfix "proxy-suite-per-app-zapret.service proxy-suite-awg-app@home.service" ( + pkgs.lib.last homeService.serviceConfig.ExecStartPre + ); assert workService.wantedBy == [ ]; assert homeService.serviceConfig.NoNewPrivileges; - # Rendering, then stopping any profile added at runtime: they share an interface. - assert builtins.length homeService.serviceConfig.ExecStartPre == 2; + # Rendering, stopping any profile added at runtime (they share an interface), then + # per-app zapret and the profile's copy for apps. + assert builtins.length homeService.serviceConfig.ExecStartPre == 3; assert pkgs.lib.hasInfix "proxy-suite-awg@*.service" ( generated.readDerivation (builtins.elemAt homeService.serviceConfig.ExecStartPre 1) ); @@ -365,11 +370,13 @@ in withGlobalTun.config.systemd.services.proxy-suite-tproxy.conflicts; assert builtins.elem "proxy-suite-awg-home.service" withGlobalTun.config.systemd.services.proxy-suite-zapret.conflicts; - assert builtins.elem "proxy-suite-awg-home.service" - withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts; + assert + !(builtins.elem "proxy-suite-awg-home.service" withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts); + assert builtins.any (pkgs.lib.hasInfix "proxy-suite-awg-home.service") + withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.serviceConfig.ExecStartPre; assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.after; assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.wants; - assert builtins.length withGlobalAwgStartPre == 3; + assert builtins.length withGlobalAwgStartPre == 4; assert pkgs.lib.hasInfix "rule add" withGlobalAwgBypassUp; assert pkgs.lib.hasInfix "pref 8998" withGlobalAwgBypassUp; assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassUp; @@ -385,7 +392,8 @@ in ( assert runtimeTemplate.wantedBy == [ ]; assert builtins.elem "proxy-suite-awg-watchdog@%i.service" runtimeTemplate.wants; - assert builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.before; + # Not before it: the kill switch comes up ahead of the network these wait for. + assert !builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.before; assert builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.wants; assert builtins.elem "proxy-suite-tun.service" runtimeTemplate.conflicts; assert runtimeTemplate.serviceConfig.Group == "proxy-suite-awg"; @@ -435,9 +443,10 @@ in assert runtimeCtl.awgProfiles == [ ]; # Declared profiles only in a configuration that turns the runtime ones off. assert !(awgOnlyNoRuntime.config.systemd.services ? "proxy-suite-awg@"); + # Rendering, and taking down the per-app units it carries for. assert builtins.length awgOnlyNoRuntime.config.systemd.services.proxy-suite-awg-home.serviceConfig.ExecStartPre - == 1; + == 2; true ) ] diff --git a/nix/checks/backend-config-validation.nix b/nix/checks/backend-config-validation.nix new file mode 100644 index 0000000..af27296 --- /dev/null +++ b/nix/checks/backend-config-validation.nix @@ -0,0 +1,115 @@ +# The generated configs through the backends' own checks: `xray run -test` and `sing-box +# check`. Nothing else catches a value a backend refuses (its whole start fails over one +# rule), only the string assertions that pin what we meant to write. +{ + pkgs, + checkLib, +}: + +let + inherit (checkLib) evalProxySuite mkAssembly baseModule; + inherit (pkgs) lib; + + proxy = + backend: + evalProxySuite [ + baseModule + { + services.proxy-suite = { + killSwitch.enable = true; + proxy = { + backend = lib.mkForce backend; + selection = "urltest"; + tproxy.enable = true; + tun.enable = true; + dns.fakeIp.enable = true; + }; + perAppRouting = { + enable = true; + tun.enable = true; + tproxy.enable = true; + }; + }; + } + ]; + # Its routing.default "direct" leaves out the proxied DNS bridge, and urltest's balancer. + direct = + backend: + evalProxySuite [ + baseModule + { + services.proxy-suite.proxy = { + backend = lib.mkForce backend; + routing.default = "direct"; + tproxy.enable = true; + }; + } + ]; + inbounds = evalProxySuite [ + baseModule + { + services.proxy-suite.inbounds = { + enable = true; + serverAddress = "vpn.example.com"; + users.user.uuidFile = "/run/secrets/uuid"; + listeners.vless-in = { + type = "vless"; + port = 443; + users = [ "user" ]; + reality = { + enable = true; + serverNames = [ "www.microsoft.com" ]; + privateKeyFile = "/run/secrets/reality-key"; + publicKey = "public-key"; + shortIds = [ "0123abcd" ]; + }; + }; + }; + } + ]; + + configsOf = + fixture: attrs: + let + configs = (mkAssembly fixture).configs; + in + map (attr: configs.${attr}) (builtins.filter (attr: configs ? ${attr}) attrs); + proxyAttrs = [ + "tproxyFile" + "tunFile" + "perAppTunFile" + ]; + + xrayConfigs = + configsOf (proxy "xray") proxyAttrs + ++ configsOf (direct "xray") proxyAttrs + ++ configsOf inbounds [ "proxyInboundsFile" ]; + singBoxConfigs = + configsOf (proxy "sing-box") proxyAttrs ++ configsOf (direct "sing-box") proxyAttrs; + + xray = "${(proxy "xray").config.services.proxy-suite.proxy.xray.package}/bin/xray"; + singBox = "${(proxy "sing-box").config.services.proxy-suite.proxy.singBox.package}/bin/sing-box"; +in +pkgs.runCommand "proxy-suite-backend-config-validation-check" { nativeBuildInputs = [ pkgs.jq ]; } + '' + export HOME=$PWD + # The outbounds come at start: one of each kind the rules and balancers name stands in. + for config in ${lib.escapeShellArgs xrayConfigs}; do + jq '.outbounds += [{tag: "proxy-suite-ob-check", protocol: "freedom"}] + | if any(.outbounds[]; .tag == "proxy") or (.routing.balancers // [] | any(.tag == "proxy")) then . + else .outbounds += [{tag: "proxy", protocol: "freedom"}] end' "$config" > config.json + if ! ${xray} run -test -format json -c config.json > log 2>&1; then + echo "xray refuses $config:" >&2 + cat log >&2 + exit 1 + fi + done + for config in ${lib.escapeShellArgs singBoxConfigs}; do + if ! ${singBox} check -c "$config" > log 2>&1; then + echo "sing-box refuses $config:" >&2 + cat log >&2 + exit 1 + fi + done + touch "$out" + '' diff --git a/nix/checks/global-proxy-modes.nix b/nix/checks/global-proxy-modes.nix index 5260f89..be417f6 100644 --- a/nix/checks/global-proxy-modes.nix +++ b/nix/checks/global-proxy-modes.nix @@ -41,6 +41,11 @@ let tproxyLanStartScript killSwitchFixture killSwitchNftRules + killSwitchTproxyNftRules + killSwitchUpScript + killSwitchSubscriptionUpdate + tunSubscriptionUpdate + tproxyKillSwitchNftRules awgKillSwitchFixture awgKillSwitchNftRules awgKillSwitchPrepare @@ -91,12 +96,15 @@ in pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix needle) null (pkgs.lib.splitString "\n" rules); in assert pkgs.lib.hasInfix - ''iifname { "br0" } meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:1085 meta mark set 1'' + ''iifname { "br0" } meta nfproto ipv4 meta l4proto { tcp, udp } meta mark set 1 tproxy ip to 127.0.0.1:1085'' + rules; + assert pkgs.lib.hasInfix + ''iifname { "br0" } meta nfproto ipv6 meta l4proto { tcp, udp } meta mark set 1 tproxy ip6'' rules; - assert pkgs.lib.hasInfix ''iifname { "br0" } meta l4proto { tcp, udp } tproxy ip6'' rules; assert at "ip daddr 192.168.0.0/16 tcp dport != 53 return" < at ''iifname { "br0" }''; - assert at ''iifname { "br0" }'' < at "ip saddr $RESERVED_IP return"; - assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 accept'' + assert !(pkgs.lib.hasInfix "ip saddr" rules); + # Into the backend's transparent socket alone, not any listener while it restarts. + assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 socket transparent 1 accept'' cfg.networking.firewall.extraInputRules; assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 accept'' cfg.networking.firewall.extraReversePathFilterRules; @@ -107,30 +115,72 @@ in assert !(pkgs.lib.hasInfix "sysctl" tproxyManualStartScript); true ) - # The kill switch: pulled in by both modes, but not stopped with them; it lets the proxy's - # own traffic and its DNS hand-off past, and cuts gateway clients off from the internet. + # The kill switch: up from boot ahead of the network, pulled in again by both modes, and + # not stopped with them; it lets the proxy's own traffic and its DNS hand-off past, and + # cuts gateway clients and containers off from the internet. ( let units = killSwitchFixture.config.systemd.services; ks = units."proxy-suite-killswitch"; rules = killSwitchNftRules; - before = - a: b: - pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix a) null (pkgs.lib.splitString "\n" rules) - < pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix b) null (pkgs.lib.splitString "\n" rules); + lines = pkgs.lib.splitString "\n" rules; + at = needle: pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix needle) null lines; + before = a: b: at a < at b; in assert builtins.elem "proxy-suite-killswitch.service" units."proxy-suite-tun".wants; assert builtins.elem "proxy-suite-killswitch.service" units."proxy-suite-tproxy".wants; assert !(units."proxy-suite-tun" ? bindsTo) || units."proxy-suite-tun".bindsTo == [ ]; assert !(ks ? partOf) || ks.partOf == [ ]; - assert builtins.elem "proxy-suite-tun.service" ks.after; - assert ks.wantedBy == [ ]; - assert pkgs.lib.hasInfix ''meta skuid "proxy-suite-daemon" accept'' rules; + assert ks.wantedBy == [ "multi-user.target" ]; + assert builtins.elem "network-pre.target" ks.before; + assert builtins.elem "network-pre.target" ks.wants; + assert ks.unitConfig.DefaultDependencies == false; + assert builtins.elem "nftables.service" ks.after; + # Nothing that waits for the network: that would be an ordering cycle. + assert !builtins.elem "proxy-suite-tun.service" ks.after; + assert !builtins.elem "proxy-suite-socks.service" ks.after; + assert pkgs.lib.hasInfix ''meta skuid { "proxy-suite-daemon" } accept'' rules; assert pkgs.lib.hasInfix "meta mark { 1, 2 } accept" rules; assert pkgs.lib.hasInfix ''oifname "singtun0" accept'' rules; assert before "ip daddr 172.19.0.1/30 accept" "th dport 53 reject"; assert before "th dport 53 reject" "ip daddr $RESERVED_IP accept"; - assert pkgs.lib.hasInfix ''iifname { "br0" } reject'' rules; + # DHCP and NTP only from privileged ports or the time daemons: no STUN past it. + assert !(pkgs.lib.hasInfix "udp dport { 67, 68, 123 }" rules); + assert pkgs.lib.hasInfix "meta nfproto ipv4 udp sport 68 udp dport 67 accept" rules; + assert pkgs.lib.hasInfix "meta nfproto ipv6 udp sport 546 udp dport 547 accept" rules; + assert pkgs.lib.hasInfix "meta skuid @time_sync_uids udp dport 123 accept" rules; + assert + killSwitchFixture.config.services.proxy-suite.killSwitch.timeSyncUsers == [ "systemd-timesync" ]; + assert pkgs.lib.hasInfix "for user in systemd-timesync; do" killSwitchUpScript; + assert pkgs.lib.hasInfix "time_sync_uids {" killSwitchUpScript; + # Forwarded traffic leaves by the TUN or not at all, gateway clients' included. + assert before "chain forward" ''oifname { "singtun0" } accept''; + assert builtins.any (line: pkgs.lib.trim line == "reject with icmpx admin-prohibited") ( + pkgs.lib.drop (at "chain forward") lines + ); + assert !(pkgs.lib.hasInfix ''iifname { "br0" } reject'' rules); + # Containers' traffic passes while TProxy, which tags it, is up instead of the TUN. + assert before "chain forward" "meta mark and 16777216 != 0 accept"; + assert pkgs.lib.hasInfix ''iifname != { "br0" } meta mark set meta mark or 16777216'' + killSwitchTproxyNftRules; + # TProxy alone: only the gateway clients are held. + assert pkgs.lib.hasInfix ''iifname { "br0" } reject'' tproxyKillSwitchNftRules; + assert !(pkgs.lib.hasInfix "oifname {" tproxyKillSwitchNftRules); + # Subscriptions are fetched as proxy-suite-fetch, through whatever tunnel is up; only + # when that fails under the kill switch with no cache, as the service user. Without + # the kill switch, never. + assert pkgs.lib.hasInfix ''_proxy_suite_run_fetcher tunnel "$tag"'' killSwitchSubscriptionUpdate; + assert pkgs.lib.hasInfix ''{ true && ! _proxy_suite_valid_subscription_cache "$cache" &&'' + killSwitchSubscriptionUpdate; + assert pkgs.lib.hasInfix "fetching it directly, past the kill switch" killSwitchSubscriptionUpdate; + assert pkgs.lib.hasInfix "as=(" killSwitchSubscriptionUpdate; + assert pkgs.lib.hasInfix "setpriv --reuid=proxy-suite-daemon" killSwitchSubscriptionUpdate; + assert pkgs.lib.hasInfix "unshare --mount" killSwitchSubscriptionUpdate; + assert pkgs.lib.hasInfix "--links-fd 3" killSwitchSubscriptionUpdate; + assert pkgs.lib.hasInfix "{ false &&" tunSubscriptionUpdate; + assert !(pkgs.lib.hasInfix "unshare --mount" tunSubscriptionUpdate); + assert !(pkgs.lib.hasInfix "setpriv --reuid=proxy-suite-daemon" tunSubscriptionUpdate); + assert pkgs.lib.hasInfix "setpriv --reuid=proxy-suite-fetch" tunSubscriptionUpdate; # A switch reloads it: the new rules replace the old in one transaction, never a stop # that lifts it first. assert ks.reloadIfChanged; @@ -148,7 +198,8 @@ in rules = awgKillSwitchNftRules; in assert builtins.elem "proxy-suite-killswitch.service" home.wants; - assert builtins.elem "proxy-suite-awg-home.service" units.proxy-suite-killswitch.after; + assert !builtins.elem "proxy-suite-awg-home.service" units.proxy-suite-killswitch.after; + assert units.proxy-suite-killswitch.wantedBy == [ "multi-user.target" ]; assert !builtins.elem "proxy-suite-killswitch.service" (home.conflicts or [ ]); assert (units.proxy-suite-killswitch.conflicts or [ ]) == [ ]; assert home.serviceConfig.Group == "proxy-suite-awg"; @@ -159,7 +210,17 @@ in assert pkgs.lib.hasInfix ''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}", "awg-rt" } accept'' rules; + # Forwarded traffic too, through either. + assert pkgs.lib.hasInfix "chain forward" rules; + assert + builtins.length ( + pkgs.lib.splitString ''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}", "awg-rt" } accept'' rules + ) == 3; assert pkgs.lib.hasInfix "meta mark { 1, 2, 51820 } accept" rules; + # killSwitch.allowedSubnets in place of TProxy's localSubnets, out and forwarded. + assert builtins.length (pkgs.lib.splitString "ip6 daddr 2001:db8:1::/64 accept" rules) == 3; + assert !(pkgs.lib.hasInfix "ip daddr 192.168.0.0/16 accept" rules); + assert pkgs.lib.hasInfix "ip daddr 192.168.0.0/16 accept" killSwitchNftRules; assert !(pkgs.lib.hasInfix "skgid" killSwitchNftRules); assert !(units.proxy-suite-awg-home-watchdog.serviceConfig ? Group); true @@ -176,20 +237,34 @@ in assert pkgs.lib.hasInfix "-6 rule add fwmark 1 table 100" tproxyManualStartScript; assert pkgs.lib.hasInfix "-6 rule del fwmark 1 table 100" tproxyManualStopScript; assert pkgs.lib.hasInfix "table inet singbox" tproxyManualNftRules; - assert pkgs.lib.hasInfix "meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:1085 meta mark set 1" + # Only what the output chain marked, this host's own traffic: a neighbour routing + # through this host is not handed the proxy. + assert pkgs.lib.hasInfix + "meta mark 1 meta nfproto ipv4 meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:1085" tproxyManualNftRules; - assert pkgs.lib.hasInfix "meta l4proto { tcp, udp } tproxy ip6 to [::1]:1085 meta mark set 1" + assert pkgs.lib.hasInfix + "meta mark 1 meta nfproto ipv6 meta l4proto { tcp, udp } tproxy ip6 to [::1]:1085" tproxyManualNftRules; + # Marked traffic that leaves anywhere but lo lost its ip rule: dropped, not sent direct. + assert pkgs.lib.hasInfix ''meta mark 1 oifname != { "lo" } drop'' tproxyManualNftRules; assert tproxyTags tproxyManualConfig == [ "tproxy-in" "tproxy-in6" ]; - assert !(pkgs.lib.hasInfix "-6 rule add" tproxyIPv4OnlyStartScript); + # IPv4 only: IPv6 is not taken by the proxy, but marked into an unreachable route rather + # than left to go out directly. + assert !(pkgs.lib.hasInfix "-6 route replace local default" tproxyIPv4OnlyStartScript); + assert pkgs.lib.hasInfix "-6 route replace unreachable default table 100" tproxyIPv4OnlyStartScript; + assert pkgs.lib.hasInfix "-6 rule add fwmark 1 table 100" tproxyIPv4OnlyStartScript; assert pkgs.lib.hasInfix "-6 rule del fwmark 1 table 100" tproxyIPv4OnlyStartScript; assert !(pkgs.lib.hasInfix "tproxy ip6" tproxyIPv4OnlyNftRules); assert pkgs.lib.hasInfix "meta nfproto ipv4 meta l4proto { tcp, udp } meta mark set 1" tproxyIPv4OnlyNftRules; + assert pkgs.lib.hasInfix "meta nfproto ipv6 meta mark set 1" tproxyIPv4OnlyNftRules; + # On-link IPv6 leaves marked by the main table: not dropped as misrouted. + assert pkgs.lib.hasInfix ''meta nfproto ipv4 meta mark 1 oifname != { "lo" } drop'' + tproxyIPv4OnlyNftRules; assert tproxyTags tproxyIPv4OnlyConfig == [ "tproxy-in" ]; true ) @@ -215,7 +290,9 @@ in assert !(pkgs.lib.hasInfix "-6 addr replace" ipv4OnlyPerAppTunUpScript); assert xrayGateway xrayIPv4OnlyTunConfig == [ "172.19.0.1/30" ]; assert !(pkgs.lib.hasInfix "-6 addr replace" xrayIPv4OnlyTunUpScript); - assert !(pkgs.lib.hasInfix "-6 route replace" xrayIPv4OnlyTunUpScript); + # IPv6 only into an unreachable route, as the sing-box and per-app TUNs have it. + assert !(pkgs.lib.hasInfix "-6 route replace default dev" xrayIPv4OnlyTunUpScript); + assert pkgs.lib.hasInfix "-6 route replace unreachable default table" xrayIPv4OnlyTunUpScript; assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStopScript; true ) @@ -235,7 +312,11 @@ in ) (ok (tunManualFixture.config.networking.nftables.enable)) ( - assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost; + # Per-app units it carries for go first (they never take it down), then the clean-up. + assert builtins.elemAt tunServiceConfig.ExecStartPre 1 == tunServiceConfig.ExecStopPost; + assert pkgs.lib.hasInfix "proxy-suite-per-app-tproxy.service" ( + builtins.head tunServiceConfig.ExecStartPre + ); assert pkgs.lib.hasInfix "delete table inet sing-box" tunCleanupScript; assert pkgs.lib.hasInfix "rule del table ${toString checkConstants.tunAutoRouteTableIndex}" tunCleanupScript; diff --git a/nix/checks/global-proxy-modes/fixtures.nix b/nix/checks/global-proxy-modes/fixtures.nix index 7249a3f..741ef02 100644 --- a/nix/checks/global-proxy-modes/fixtures.nix +++ b/nix/checks/global-proxy-modes/fixtures.nix @@ -42,7 +42,7 @@ let tproxyManualServiceConfig = tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig; tproxyManualStartScript = generated.readDerivation tproxyManualServiceConfig.ExecStart; - tproxyManualStopScript = generated.readDerivation tproxyManualServiceConfig.ExecStop; + tproxyManualStopScript = generated.readDerivation tproxyManualServiceConfig.ExecStopPost; tproxyManualConfig = mkTProxyConfig tproxyManualFixture; tproxyManualNftRules = mkTProxyNftRules tproxyManualFixture; @@ -74,6 +74,22 @@ let } ]; killSwitchNftRules = mkNftRules killSwitchFixture "killSwitchRulesFile"; + killSwitchTproxyNftRules = mkTProxyNftRules killSwitchFixture; + killSwitchUpScript = generated.readDerivation killSwitchFixture.config.systemd.services.proxy-suite-killswitch.serviceConfig.ExecStart; + killSwitchSubscriptionUpdate = generated.readDerivation killSwitchFixture.config.systemd.services.proxy-suite-subscription-update.serviceConfig.ExecStart; + tunSubscriptionUpdate = generated.readDerivation tunManualFixture.config.systemd.services.proxy-suite-subscription-update.serviceConfig.ExecStart; + + # TProxy alone diverts no forwarded traffic: only the gateway clients are held to the LAN. + tproxyKillSwitchNftRules = mkNftRules (evalProxySuite [ + baseModule + { + services.proxy-suite.killSwitch.enable = true; + services.proxy-suite.proxy.tproxy = { + enable = true; + lanInterfaces = [ "br0" ]; + }; + } + ]) "killSwitchRulesFile"; # A global AmneziaWG profile alone, no proxy. awgKillSwitchFixture = evalProxySuite [ @@ -81,7 +97,10 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; - killSwitch.enable = true; + killSwitch = { + enable = true; + allowedSubnets = [ "2001:db8:1::/64" ]; + }; amneziaWg = { enable = true; kernelModulePackage = null; @@ -208,6 +227,11 @@ in tproxyLanStartScript killSwitchFixture killSwitchNftRules + killSwitchTproxyNftRules + killSwitchUpScript + killSwitchSubscriptionUpdate + tunSubscriptionUpdate + tproxyKillSwitchNftRules awgKillSwitchFixture awgKillSwitchNftRules awgKillSwitchPrepare diff --git a/nix/checks/gui.nix b/nix/checks/gui.nix index bc3687b..6b801e4 100644 --- a/nix/checks/gui.nix +++ b/nix/checks/gui.nix @@ -37,6 +37,7 @@ let ]; guiPackage = ".*/[^/]*proxy-suite-gui(-[0-9.]+)?$"; + inherit (import ./read-generated.nix) readDerivation; in { assertions = [ @@ -61,19 +62,35 @@ in true ) ( - # pkexec of this proxy-ctl, and only it, keeps the admin password for a while. + # pkexec of this proxy-ctl, and only it, keeps the admin password for a while: an action + # of its own, not a rule on org.freedesktop.policykit.exec, whose kept authorization + # would cover any program the GUI ran through pkexec next. let - rules = guiFixture.config.security.polkit.extraConfig; + cfg = guiFixture.config; + actions = cfg.services.proxy-suite.internal.polkit.actions; + policy = readDerivation actions."io.github.FUFSoB.ProxySuite.proxy-ctl.policy"; + proxyCtl = builtins.head ( + builtins.filter (p: builtins.match ".*/[^/]*-proxy-ctl$" p != null) ( + map (p: builtins.unsafeDiscardStringContext (toString p)) cfg.environment.systemPackages + ) + ); + has = text: builtins.match ".*${text}.*" (builtins.unsafeDiscardStringContext policy) != null; in - assert guiFixture.config.security.polkit.enable; + assert cfg.security.polkit.enable; # nixpkgs 26.11+: no setuid pkexec unless asked for, and without it pkexec refuses to run. + assert cfg.security.wrappers ? pkexec && cfg.security.wrappers.pkexec.enable; assert - guiFixture.config.security.wrappers ? pkexec && guiFixture.config.security.wrappers.pkexec.enable; - assert - builtins.match ''.*action\.lookup\("program"\) === "/nix/store/[^"]*proxy-ctl/bin/proxy-ctl".*AUTH_ADMIN_KEEP.*'' rules - != null; - assert - builtins.match ".*AUTH_ADMIN_KEEP.*" tuiOffFixture.config.security.polkit.extraConfig == null; + builtins.match ".*(policykit\\.exec|AUTH_ADMIN_KEEP).*" cfg.security.polkit.extraConfig == null; + # The path the GUI runs proxy-ctl by, which pkexec matches after realpath. + assert has + ''${proxyCtl}/bin/proxy-ctl''; + # Never kept: a kept grant is the whole session's, and proxy-ctl as root runs commands. + assert has "auth_admin"; + assert has "auth_admin"; + assert has "auth_admin"; + # Where NixOS's polkitd reads actions: the system profile's share/polkit-1/actions. + assert packagePathMatches cfg.environment.systemPackages ".*-proxy-suite-polkit-actions$"; + assert tuiOffFixture.config.services.proxy-suite.internal.polkit.actions == { }; true ) ( diff --git a/nix/checks/hosts.nix b/nix/checks/hosts.nix index 90ca2ab..7859a48 100644 --- a/nix/checks/hosts.nix +++ b/nix/checks/hosts.nix @@ -87,6 +87,7 @@ let fixture: map (a: a.message) (lib.filter (a: !a.assertion) fixture.config.assertions); # Through JSON: derivations stop at their store paths, which is where the scripts get built. forced = value: builtins.isString (builtins.toJSON value); + packageNamed = name: lib.findFirst (p: lib.getName p == name) null; proxy = { enable = true; @@ -238,7 +239,12 @@ in assert smCfg.systemd.services.proxy-suite-socks.serviceConfig.SyslogIdentifier == "proxy-suite-socks"; assert smCfg.systemd.services ? proxy-suite-tproxy; + # No NixOS time daemon options to read: the kill switch tries the usual users. + assert builtins.elem "chrony" smCfg.services.proxy-suite.killSwitch.timeSyncUsers; + assert builtins.elem "systemd-timesync" smCfg.services.proxy-suite.killSwitch.timeSyncUsers; assert smCfg.environment.etc ? "polkit-1/rules.d/50-proxy-suite.rules"; + # The GUI's pkexec action, where the distribution's polkit (126+) reads it. + assert smCfg.environment.etc ? "polkit-1/actions/io.github.FUFSoB.ProxySuite.proxy-ctl.policy"; assert smCfg.environment.etc ? "systemd/user/proxy-suite-gui.service"; assert forced smCfg.systemd.services; true @@ -257,6 +263,29 @@ in # Android bans apps from netlink's route groups, which stock sing-box subscribes to. assert nodCfg.services.proxy-suite.proxy.singBox.package.passthru.rootlessNetlink or false; assert !(hmCfg.services.proxy-suite.proxy.singBox.package.passthru.rootlessNetlink or false); + # Space on a phone: no systemd (proxy-suitectl stands in), lnav or curl-impersonate. + assert lib.all + ( + name: + let + wrapper = (packageNamed name nodCfg.environment.packages).buildCommand; + in + lib.all (dep: !(lib.hasInfix dep wrapper)) [ + "-systemd-" + "-lnav-" + "-curl-impersonate-" + ] + ) + [ + "proxy-ctl" + "proxy-tui" + ]; + # Elsewhere they stay. + assert lib.all (dep: lib.hasInfix dep (packageNamed "proxy-ctl" hmCfg.home.packages).buildCommand) [ + "-systemd-" + "-lnav-" + "-curl-impersonate-" + ]; true ) ( diff --git a/nix/checks/local-proxy-auth.nix b/nix/checks/local-proxy-auth.nix index 8f562ab..9c7054c 100644 --- a/nix/checks/local-proxy-auth.nix +++ b/nix/checks/local-proxy-auth.nix @@ -107,7 +107,7 @@ in # Authenticated mixed inbound is injected at runtime. ( - assert pkgs.lib.hasInfix ''LOCAL_PROXY_PASSWORD="$(cat "'' localProxyAuthStartScript; + assert pkgs.lib.hasInfix ''LOCAL_PROXY_PASSWORD="$(cat '' localProxyAuthStartScript; assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" localProxyAuthStartScript; assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' localProxyAuthStartScript; assert pkgs.lib.hasInfix "--arg user local-user" localProxyAuthStartScript; diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index d7ea5da..6dcded0 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -65,6 +65,8 @@ let }; inherit (coreProxyChecks) ruDefaultConfig; + optionTypeChecks = import ./option-types.nix { inherit checkLib minimal; }; + routeModeChecks = import ./route-mode.nix { inherit checkLib; inherit @@ -342,6 +344,7 @@ let ++ guiChecks.assertions ++ subscriptionChecks.assertions ++ routeModeChecks.assertions + ++ optionTypeChecks.assertions ++ perAppRoutingChecks.assertions ++ perAppRoutingAwgChecks.assertions ++ serverModuleChecks.assertions diff --git a/nix/checks/option-types.nix b/nix/checks/option-types.nix new file mode 100644 index 0000000..e5ad5ba --- /dev/null +++ b/nix/checks/option-types.nix @@ -0,0 +1,112 @@ +# Interface names, addresses and CIDRs go into nft rules and scripts as they are: their +# types must turn away anything that would end the token there. +{ checkLib, minimal }: + +let + opts = minimal.options.services.proxy-suite; + elemCheck = option: option.type.nestedTypes.elemType.check; + accepts = check: builtins.all check; + refuses = check: builtins.all (value: !(check value)); + injected = [ + "" + "br0\" accept" + "br0 }" + "br0; flush ruleset" + "$(reboot)" + "eth0 eth1" + "a\nb" + ]; +in +{ + assertions = [ + ( + let + check = elemCheck opts.proxy.tproxy.lanInterfaces; + in + assert accepts check [ + "br0" + "br-lan" + "eth0.100" + "wlp3s0" + "a+b" + "123456789012345" + ]; + assert refuses check ( + injected + ++ [ + "1234567890123456" + "." + "-x" + "eth*" + ] + ); + assert refuses opts.proxy.tun.interface.type.check injected; + assert refuses opts.perAppRouting.tun.interface.type.check injected; + true + ) + ( + let + subnets = [ + opts.proxy.tproxy.localSubnets + opts.perAppRouting.tun.localSubnets + opts.perAppRouting.tproxy.localSubnets + opts.perAppRouting.via.localSubnets + opts.zapret.cidrExemption.cidrs + ]; + in + assert builtins.all ( + option: + accepts (elemCheck option) [ + "192.168.0.0/16" + "10.1.2.3" + "fd00::/8" + "::1" + "::ffff:10.0.0.1/128" + ] + && refuses (elemCheck option) ( + injected + ++ [ + "10.0.0.0/8 accept" + "10.0.0.0/33" + "256.0.0.0/8" + "fd00::/129" + "example.com" + ] + ) + ) subnets; + true + ) + ( + assert accepts opts.proxy.tun.address.type.check [ "172.19.0.1/30" ]; + assert refuses opts.proxy.tun.address.type.check ( + injected + ++ [ + "172.19.0.1" + "fd00::1/64" + "172.19.0.1/30 accept" + ] + ); + assert refuses opts.perAppRouting.tun.address.type.check [ "172.20.0.1/30; drop" ]; + true + ) + ( + assert accepts opts.proxy.listener.address.type.check [ + "127.0.0.1" + "::" + "localhost" + ]; + assert refuses opts.proxy.listener.address.type.check injected; + true + ) + # A bad value stops the evaluation; it is not quietly left out. + ( + assert + !(checkLib.forceEval + (minimal.extendModules { + modules = [ { services.proxy-suite.proxy.tproxy.lanInterfaces = [ "br0\" accept" ]; } ]; + }).config.services.proxy-suite.proxy.tproxy.lanInterfaces + ).success; + true + ) + ]; +} diff --git a/nix/checks/per-app-routing-awg.nix b/nix/checks/per-app-routing-awg.nix index 42ca5c2..963d73d 100644 --- a/nix/checks/per-app-routing-awg.nix +++ b/nix/checks/per-app-routing-awg.nix @@ -51,7 +51,10 @@ let viaDns = generated.readDerivation perAppRouting.viaDns; appCopy = services."proxy-suite-awg-app@"; viaFile = builtins.fromJSON (generated.readDerivation perAppRouting.perAppViaFile); + viaUserRule = generated.readDerivation perAppRouting.viaUserRule; viaUserStart = generated.readDerivation perAppRouting.viaUserStart; + viaRetire = generated.readDerivation perAppRouting.viaRetire; + viaReapply = generated.readDerivation perAppRouting.viaReapply; anchor = fixture.config.systemd.user.services."proxy-suite-per-app-via-anchor@"; dePrepare = generated.readDerivation ( builtins.head services.proxy-suite-awg-de.serviceConfig.ExecStartPre @@ -100,7 +103,7 @@ let pinTproxyUp = generated.readDerivation pinPerApp.pinUp.tproxy; pinTproxyDown = generated.readDerivation pinPerApp.pinDown.tproxy; pinTunUp = generated.readDerivation pinPerApp.pinUp.tun; - pinUserStart = generated.readDerivation pinPerApp.viaUserStart; + pinUserStart = generated.readDerivation pinPerApp.viaUserRule; pinTproxyConfig = checkLib.mkTProxyConfig pinFixture; pinTunConfig = checkLib.mkPerAppTunConfig pinFixture; pinNft = import ../../modules/proxy-suite/nftables.nix { @@ -152,14 +155,41 @@ in ) # 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 hasInfix "^([0-9]+)-((awg|app|tproxy|tun)-[0-9a-f]+)$" viaUserRule; + assert hasInfix "nft_chain=app_mark" viaUserRule; + assert hasInfix ''-name "$slice_name"'' viaUserRule; + assert hasInfix "meta mark set $mark ct mark set $mark" viaUserRule; assert anchor.serviceConfig.Slice == "proxy-suite-per-app-via-%i.slice"; assert services ? "proxy-suite-per-app-via-user@"; true ) + # The via unit is every user's: perApp members only start it (polkit.nix), and the last + # user's unit takes it down, under the lock a rule goes in by, so none lands in a table + # on its way out. A restart puts the users' rules back in its fresh table. + ( + let + user = services."proxy-suite-per-app-via-user@".serviceConfig; + lock = ''exec 8>>"/run/proxy-suite-per-app-via/users-$key.lock"''; + in + assert pkgs.lib.hasSuffix " %i" user.ExecStopPost; + # Not on its own restart, nor through a switch's stop and start. + assert hasInfix ''$3 == "restart"'' viaRetire; + assert !services."proxy-suite-per-app-via-user@".serviceConfig.X-RestartIfChanged; + assert hasInfix lock viaUserStart && hasInfix lock viaRetire; + assert hasInfix ''show --property=ActiveState --value "$via_unit") != active'' viaUserStart; + assert hasInfix ''via_unit="proxy-suite-per-app-via@$key.service"'' viaRetire; + assert hasInfix ''via_unit="proxy-suite-per-app-via-''${key%%-*}@''${key#*-}.service"'' viaRetire; + assert hasInfix "--state=active,activating,reloading" viaRetire; + assert hasInfix "-v self=\"proxy-suite-per-app-via-user@$1.service\" '$1 != self')" viaRetire; + # The profile brought up for the apps after the via unit, whose stop reads its slot. + assert + builtins.match ''.*stop "\$via_unit".*stop "proxy-suite-awg-app@\$tag\.service".*'' viaRetire + != null; + assert pkgs.lib.hasSuffix " %i" via.serviceConfig.ExecStartPost; + assert hasInfix ''"proxy-suite-per-app-via-user@*-''${1:-}.service"'' viaReapply; + assert hasInfix "--state=active " viaReapply; + 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. @@ -175,9 +205,11 @@ in ( 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; + # Never up with the profile itself, and never taking it down: refused while it is up. + assert (appCopy.conflicts or [ ]) == [ ]; + assert hasInfix "proxy-suite-awg-%i.service proxy-suite-awg@%i.service" ( + builtins.head appCopy.serviceConfig.ExecStartPre + ); 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"; @@ -198,8 +230,15 @@ in 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; + # Restarted with the backend, the slot's table comes back empty: the users' rules too. + assert pkgs.lib.hasSuffix " tun-%i" + pinServices."proxy-suite-per-app-via-tun@".serviceConfig.ExecStartPost; + assert pkgs.lib.hasSuffix " tproxy-%i" + pinServices."proxy-suite-per-app-via-tproxy@".serviceConfig.ExecStartPost; + # Under a global mode it stays down rather than take the mode down. + assert (pinServices."proxy-suite-per-app-via-tun@".conflicts or [ ]) == [ ]; + assert pkgs.lib.hasInfix "proxy-suite-tproxy.service proxy-suite-tun.service" + pinServices."proxy-suite-per-app-via-tun@".serviceConfig.ExecStartPre; 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@"); @@ -248,7 +287,7 @@ in ); # 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 "nft_chain=app_mark" pinUserStart; assert hasInfix "23168" (checkLib.mkNftRules pinFixture "killSwitchRulesFile"); true ) @@ -267,6 +306,18 @@ in }; } )) + # A table a pin slot takes for itself, named by an option too: the two would flush each + # other's routes. + (rejectsProxySuite "route table 170 (proxy.tproxy.routeTable" ( + pinConfig + // { + proxy = pinConfig.proxy // { + tproxy = pinConfig.proxy.tproxy // { + routeTable = 170; + }; + }; + } + )) (rejectsProxySuite "outbound 'plain' needs route \"tproxy\" or \"tun\"" ( config // { diff --git a/nix/checks/per-app-routing-tproxy.nix b/nix/checks/per-app-routing-tproxy.nix index e65269d..9df403d 100644 --- a/nix/checks/per-app-routing-tproxy.nix +++ b/nix/checks/per-app-routing-tproxy.nix @@ -29,7 +29,7 @@ let perAppRoutingTproxyServiceConfig = perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy".serviceConfig; perAppRoutingTproxyStartScript = generated.readDerivation perAppRoutingTproxyServiceConfig.ExecStart; - perAppRoutingTproxyStopScript = generated.readDerivation perAppRoutingTproxyServiceConfig.ExecStop; + perAppRoutingTproxyStopScript = generated.readDerivation perAppRoutingTproxyServiceConfig.ExecStopPost; perAppRoutingTproxyUserStartScript = generated.readDerivation ( (mkPerAppUserRules perAppRoutingTproxyFixture).perAppTproxyUserRuleStart ); @@ -62,13 +62,19 @@ in assert perAppRoutingTproxyFixture.config.systemd.services ? "proxy-suite-per-app-tproxy-user@"; assert perAppRoutingTproxyFixture.config.systemd.user.services ? "proxy-suite-per-app-tproxy-anchor"; + assert + perAppRoutingTproxyFixture.config.systemd.services.proxy-suite-per-app-tproxy.unitConfig.StopWhenUnneeded; + assert + perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy-user@".requires == [ + "proxy-suite-per-app-tproxy.service" + ]; true ) # -- perAppRouting: app TProxy helper installs socket cgroup mark rules -- ( assert pkgs.lib.hasInfix "socket cgroupv2" perAppRoutingTproxyUserStartScript; - assert pkgs.lib.hasInfix "add rule inet proxy_suite_per_app_tproxy output" + assert pkgs.lib.hasInfix "add rule inet proxy_suite_per_app_tproxy app_mark" perAppRoutingTproxyUserStartScript; assert pkgs.lib.hasInfix "meta mark set" perAppRoutingTproxyUserStartScript; assert pkgs.lib.hasInfix "ct mark set" perAppRoutingTproxyUserStartScript; @@ -91,6 +97,15 @@ in assert guardedBeforeMark (builtins.elemAt chains 1); # This host's own addresses are not tproxied. assert hasInfix "fib daddr type local return" (builtins.elemAt chains 0); + # Every lookup of a tproxied app, a LAN or loopback resolver's too, is marked, ahead + # of the reserved ranges, and goes to the route's DNS forwarder; its own do not. + assert hasInfix "th dport 53 goto app_mark" ( + builtins.head (splitString "daddr $RESERVED_IP return" (builtins.elemAt chains 1)) + ); + assert hasInfix + "meta mark 17 meta l4proto { tcp, udp } th dport 53 ip daddr != 192.0.2.53 redirect to :19200" + perAppRoutingTproxyNftRules; + assert hasInfix "meta mark 17 ct mark set 17 return" perAppRoutingTproxyNftRules; true ) diff --git a/nix/checks/per-app-routing-tun.nix b/nix/checks/per-app-routing-tun.nix index 9f71843..8c47035 100644 --- a/nix/checks/per-app-routing-tun.nix +++ b/nix/checks/per-app-routing-tun.nix @@ -145,8 +145,21 @@ in ( assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun"; assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun-user@"; + # Every user's: it goes once the last user's marking that requires it stops; never by a + # member's stop under the others' apps. Requires=, not BindsTo=, so the marking stays up + # through a crash and its automatic restart, which restarts the marking too. + assert + perAppRoutingTunFixture.config.systemd.services.proxy-suite-per-app-tun.unitConfig.StopWhenUnneeded; + assert + perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun-user@".requires == [ + "proxy-suite-per-app-tun.service" + ]; + assert + perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun-user@".bindsTo == [ ]; assert perAppRoutingTunFixture.config.systemd.user.services ? "proxy-suite-per-app-tun-anchor"; - assert perAppRoutingTunServiceConfig.ExecStartPre == perAppRoutingTunServiceConfig.ExecStopPost; + assert + builtins.head perAppRoutingTunServiceConfig.ExecStartPre + == perAppRoutingTunServiceConfig.ExecStopPost; # With proxy.ipv6, wrapped apps' IPv6 goes through the app TUN too. assert pkgs.lib.hasInfix "link set dev psperapptun0 up" perAppRoutingTunUpScript; assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev psperapptun0'' perAppRoutingTunUpScript; diff --git a/nix/checks/per-app-routing-zapret.nix b/nix/checks/per-app-routing-zapret.nix index b82a823..4ac020b 100644 --- a/nix/checks/per-app-routing-zapret.nix +++ b/nix/checks/per-app-routing-zapret.nix @@ -202,6 +202,12 @@ in perAppRoutingZapretFixture.config.systemd.user.services ? "proxy-suite-per-app-zapret-anchor"; assert builtins.elem "network-online.target" perAppRoutingZapretService.after; assert builtins.elem "network-online.target" perAppRoutingZapretService.wants; + # Declared with zapret's units; units.nix adds that it goes once no user needs it. + assert perAppRoutingZapretService.unitConfig.StopWhenUnneeded; + assert + perAppRoutingZapretFixture.config.systemd.services."proxy-suite-per-app-zapret-user@".requires == [ + "proxy-suite-per-app-zapret.service" + ]; true ) diff --git a/nix/checks/proxy-inbounds-runtime.nix b/nix/checks/proxy-inbounds-runtime.nix index df34f53..fe688c5 100644 --- a/nix/checks/proxy-inbounds-runtime.nix +++ b/nix/checks/proxy-inbounds-runtime.nix @@ -46,6 +46,8 @@ pkgs.testers.runNixOSTest { inbounds = { enable = true; inherit serverAddress; + # The origin is this host's own web server: through the tunnel only as a listed port. + serverPorts = [ 80 ]; routing.via = "direct"; openFirewall = true; users = { @@ -74,6 +76,16 @@ pkgs.testers.runNixOSTest { services.nginx = { enable = true; virtualHosts."origin".locations."/".return = "200 'served-from-origin'"; + # On every address, kept from the internet by the firewall alone. + virtualHosts."internal" = { + listen = [ + { + addr = "0.0.0.0"; + port = 8080; + } + ]; + locations."/".return = "200 'internal-only'"; + }; }; networking.firewall.allowedTCPPorts = [ 80 ]; # Written at boot, so the listener's spec carries only the paths. @@ -149,6 +161,17 @@ pkgs.testers.runNixOSTest { "curl -sS --fail --max-time 15 --proxy socks5h://127.0.0.1:1080" " http://127.0.0.1/ 2>&1" ) + # Nor into a port of its own the firewall closes: "direct" would dial it over lo. The + # fence carries the addresses its interfaces had at start, the private one too. + cfg = "/run/proxy-suite-inbounds/config.json" + server.succeed(f"jq -e '[.outbounds[] | select(.tag == \"direct\") | .settings.finalRules[] | select(.ip and (.ip | index(\"${serverPrivateAddress}\")))] | length == 2' {cfg}") + server.succeed(f"jq -e '[.. | objects | select(has(\"_hostAddresses\"))] == []' {cfg}") + server.succeed("curl -sS --fail --max-time 5 http://${serverAddress}:8080/ | grep -q internal-only") + client.fail("curl -sS --fail --max-time 5 http://${serverAddress}:8080/") + client.fail( + "curl -sS --fail --max-time 15 --proxy socks5h://127.0.0.1:1080" + " http://${serverAddress}:8080/ 2>&1" + ) with subtest("share links are generated and readable by proxy-ctl"): links = "/run/proxy-suite-inbounds/links.json" @@ -171,13 +194,17 @@ pkgs.testers.runNixOSTest { # The reload's restart returns once the start script is forked: config.json is # gone until it renders it again. server.wait_until_succeeds(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\", \"friend\"]' {cfg}") - server.succeed("proxy-ctl inbounds add rt vless --port 9001 --user friend --user tester") + server.succeed("proxy-ctl inbounds add rt vless --port 9001 --user friend") server.wait_for_open_port(9001) server.succeed("proxy-ctl inbounds users | grep friend | grep -q rt") - # Refused, and nothing else disturbed. + # Refused, and nothing else disturbed. A declared user's uuid stays off a plain listener. server.fail("proxy-ctl inbounds add far vless --port 30000 --user friend") + server.fail("proxy-ctl inbounds add clear vless --port 9002 --user tester") + server.fail("proxy-ctl inbounds bind tester rt") server.fail("proxy-ctl inbounds bind tester vless-in") server.succeed("test ! -e /var/lib/proxy-suite/inbounds.d/listeners/far.json") + server.succeed("test ! -e /var/lib/proxy-suite/inbounds.d/listeners/clear.json") + server.succeed("jq -e '.users | index(\"tester\") == null' /var/lib/proxy-suite/inbounds.d/listeners/rt.json") # The runtime user's link works from the client, as a runtime outbound there. XRay # refuses plain VLESS to a public IP, so it dials the private one. link = server.succeed("proxy-ctl inbounds link rt friend").strip() diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index 6b91ecd..29b903a 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -949,17 +949,93 @@ let true ) (ok ((ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ])) - # Names that resolve private are refused where XRay dials them itself. + # Names that resolve private are refused where XRay dials them itself. This host's own + # addresses only on its public ports: "direct" dials them over lo, past the firewall. + # The start script adds the interfaces' addresses to the marked rules. XRay's own resolvers + # stay reachable on their port, should one be on this host. ( + let + hostAddresses = [ + "127.0.0.0/8" + "::1/128" + "0.0.0.0/32" + "::/128" + ]; + in assert (lib.findFirst (ob: ob.tag == "direct") null relayConfig.outbounds).settings.finalRules == [ { action = "block"; ip = [ "geoip:private" ]; } + { + action = "allow"; + ip = [ "1.1.1.1" ]; + port = "53"; + } + { + action = "allow"; + ip = hostAddresses; + port = "443"; + _hostAddresses = true; + } + { + action = "block"; + ip = hostAddresses; + _hostAddresses = true; + } ]; true ) + # blockPrivate = false opens the LAN, not the rest of this host. + ( + let + rules = (lib.findFirst (ob: ob.tag == "direct") null unguardedConfig.outbounds).settings.finalRules; + in + assert + map (rule: rule.action) rules == [ + "block" + "allow" + "allow" + "block" + "allow" + ]; + # Nor cloud metadata. + assert builtins.elem "169.254.169.254" (builtins.elemAt rules 0).ip; + assert (builtins.elemAt rules 1).ip == [ "1.1.1.1" ]; + assert (builtins.elemAt rules 2) ? _hostAddresses && (builtins.elemAt rules 2).port == "443"; + assert (builtins.elemAt rules 3) ? _hostAddresses && !((builtins.elemAt rules 3) ? port); + assert lib.last rules == { action = "allow"; }; + true + ) + # The serverSource ranges and the IPs of serverAddress and serverAliases are this host's + # too; the fence takes the share ports the routing rules do. + ( + let + fence = + builtins.elemAt + (lib.findFirst (ob: ob.tag == "direct") null selfSourceConfig.outbounds).settings.finalRules + 2; + in + assert + lib.drop 4 fence.ip == [ + "10.78.0.0/24" + "fd78:78:78::/64" + "203.0.113.10" + "2001:db8::10" + ]; + assert fence.port == (ruleByTag selfSourceConfig "inbound-server-address-direct-ip").port; + true + ) + ( + let + startScript = readInboundsStart relayFixture; + in + assert lib.hasInfix "addr show | " startScript; + assert lib.hasInfix "--argjson host_addresses \"$HOST_ADDRESSES\"" startScript; + assert lib.hasInfix "select(._hostAddresses)" startScript; + true + ) # Only the listener ports, not every service on this host. (ok ((ruleByTag namedConfig "inbound-server-address-direct").port == "443")) (ok ((ruleByTag blockedConfig "inbound-proxy-domain").inboundTag == [ "open" ])) @@ -1149,7 +1225,21 @@ let (ok (hasFailed runtimeNoPortsFixture "inbounds.runtime.enable needs inbounds.runtime.ports")) (ok ((ruleByTag aliasedConfig "inbound-server-address-direct").port == "443,993,7882-7885")) (ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").port == "443,993,7882-7885")) - (ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").outboundTag == "direct")) + # One allowed UDP packet would carry its whole session direct (XRay routes it once): an + # address goes to an outbound dialing those alone, a name over TCP alone. + (ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").outboundTag == "direct-server")) + (ok ((ruleByTag aliasedConfig "inbound-server-address-direct").network == "tcp")) + (ok ( + (lib.findFirst (ob: ob.tag == "direct-server") null aliasedConfig.outbounds).settings.finalRules + == [ + { + action = "allow"; + ip = (ruleByTag aliasedConfig "inbound-server-address-direct-ip").ip; + port = "443,993,7882-7885"; + } + { action = "block"; } + ] + )) (ok (!builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig))) # A per-listener via becomes its own rule; listeners on the default do not. @@ -1315,6 +1405,18 @@ let assert lib.hasInfix "chmod 640 \"$tmp\"" (statsScript controlFixture); assert !lib.hasInfix "chgrp" (statsScript relayFixture); assert lib.hasInfix "chmod 600 \"$tmp\"" (statsScript relayFixture); + # Who is online goes in it too: the API, which can reset the counters, is root's. + assert lib.hasInfix ".online = (\\$online.users // [])" (statsScript controlFixture); + true + ) + ( + let + startScript = readInboundsStart controlFixture; + in + assert lib.hasSuffix ",0600" (builtins.head relayConfig.inbounds).listen; + assert lib.hasInfix "install -d -m 0700 -o proxy-suite-daemon -g proxy-suite-daemon \"$API_DIR\"" + startScript; + assert !lib.hasInfix "setfacl" startScript; true ) diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index 6328115..11e6cbb 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -56,6 +56,13 @@ let constants.readSourceFunction = _: '' _proxy_suite_read_source() { cat -- "$1"; } ''; + # The hop login, in the build directory. + constants.hopUser = "hop"; + constants.hopLoginFile = "hop-login"; + constants.ensureHopLogin = + _: pkgs.writeShellScript "proxy-suite-hop-login" "[ -s hop-login ] || printf s3cret > hop-login"; + # The build runs as its own user: no one to drop to. + constants.runAsServiceUser = _: _: ""; pureXrayEnabled = false; collapseNamedOutbounds = null; backend = null; @@ -68,6 +75,7 @@ let mkSubscriptionBlock = null; mkSubscriptionLoadHelperBlock = null; runtimeSubscriptionsBlock = null; + singBoxBin = "${pkgs.sing-box}/bin/sing-box"; }; in { @@ -377,6 +385,65 @@ in } ); + # The runner's spool, as members fill it: read through no link or FIFO, and emptied of + # what it took; and an install from before it, whose state dir the group wrote to. + autoproxy-spool = + let + runner = pkgs.writeShellScript "proxy-suite-autoproxy" ( + fillTemplate ../../modules/proxy-suite/autoproxy-run.template.sh { + # The build dir's stub/ first: proxy-ctl answers every probe. + path = "$PWD/stub:${ + pkgs.lib.makeBinPath [ + pkgs.coreutils + pkgs.curl + pkgs.findutils + pkgs.gawk + pkgs.gnugrep + pkgs.gnused + pkgs.jq + pkgs.util-linux + ] + }"; + stateDir = "/nonexistent"; + spoolDir = "/nonexistent"; + runtimeDir = "/nonexistent"; + ttlDays = "30"; + migrate = import ../../modules/proxy-suite/autoproxy-migrate.nix { inherit pkgs; }; + editJq = ../../modules/proxy-suite/autoproxy-edit.jq; + render = pkgs.writeShellScript "proxy-suite-autoproxy-render" ( + fillTemplate ../../modules/proxy-suite/autoproxy-render.template.sh { + path = pkgs.lib.makeBinPath [ + pkgs.coreutils + pkgs.jq + ]; + serviceUser = "proxy-suite-daemon"; + groupArg = ""; + } + ); + strikeJq = ../../modules/proxy-suite/autoproxy-strike.jq; + roundsJq = ../../modules/proxy-suite/autoproxy-rounds.jq; + interval = "1h"; + journalctl = "false"; + excludeHosts = ""; + excludeSampleHosts = ""; + slowJudgeJq = ../../modules/proxy-suite/autoproxy-slow-judge.jq; + probesPerRun = "5"; + publicSuffixes = + pkgs.runCommand "proxy-suite-autoproxy-public-suffixes" { nativeBuildInputs = [ pkgs.python3 ]; } + "python3 ${../../modules/proxy-suite/zapret2/public-suffixes.py} --private ${pkgs.publicsuffix-list}/share/publicsuffix/public_suffix_list.dat >$out"; + } + ); + in + pkgs.runCommand "proxy-suite-autoproxy-spool-check" { + nativeBuildInputs = [ + pkgs.coreutils + pkgs.diffutils + pkgs.findutils + pkgs.gnugrep + pkgs.jq + ]; + } (fillTemplate ./repo/autoproxy-spool.template.sh { inherit runner; }); + # A probe that exits 0 printing nothing: jq reads "" as no input at all, so the # "error" guard downstream saw "" instead of "error" and let it through to # `--argjson r ""`, which failed every autoProxy run until the state changed. @@ -488,9 +555,12 @@ in echo '{"type": "tor", "executable_path": "/tmp/x"}' > obd/tor.json echo '{"type": "ssh", "server": "h", "private_key_path": "/root/.ssh/id_ed25519"}' > obd/ssh.json echo '{"type": "vless", "server": "h", "tls": {"enabled": true, "certificate_path": "/etc/shadow"}}' > obd/cert.json + # A field the backend does not know would fail its whole start: this one alone goes. + echo '{"type": "socks", "server": "127.0.0.1", "server_prot": 1080}' > obd/typo.json ${loadRuntime} 2> err cat err jq -e '[.[].tag] == ["ok", "ws"]' outbounds.json > /dev/null + grep -q "runtime outbound 'typo' is not one the backend takes" err grep -q "runtime outbound 'tor' names local files or programs (executable_path, type: tor)" err grep -q "runtime outbound 'ssh' names local files or programs (private_key_path)" err grep -q "runtime outbound 'cert' names local files or programs (certificate_path)" err diff --git a/nix/checks/repo/autoproxy-spool.template.sh b/nix/checks/repo/autoproxy-spool.template.sh new file mode 100644 index 0000000..5c5f83b --- /dev/null +++ b/nix/checks/repo/autoproxy-spool.template.sh @@ -0,0 +1,62 @@ +set -euo pipefail +# The runner as the units run it, against scratch dirs: what members queue in the spool, +# and an install from before it, whose state dir the group wrote to. +mkdir -p state spool run stub +export AUTOPROXY_STATE_DIR=$PWD/state AUTOPROXY_SPOOL_DIR=$PWD/spool PROBE_EXITS_FILE=$PWD/run/probe-exits.json +printf 'secret.example\n' > secret +# Every probe reaches its destination through exit x; each host asked for is logged. +cat > stub/proxy-ctl <<'EOF' +#!/bin/sh +for a; do host=$a; done +echo "$host" >> "$PROBED" +echo '{"verdict":"destination","exit":"x","path":"/"}' +EOF +chmod +x stub/proxy-ctl +export PROBED=$PWD/probed + +# --- the old layout: queues, and what a member could leave, in a 0771 state dir --- +echo '{"domains":{"gone.example":{"verdict":"destination","exit":"x","host":"gone.example","at":1}}, + "hosts":{},"exits":{"x":{"at":"a[$(touch pwned)]"}},"backlog":{}}' > state/state.json +printf 'old.example\n' > state/requests +printf 'forget gone.example\n' > state/edits.taking +# Root opens lock for writing, appends to samples and installs into rules/ by name. +ln -s "$PWD/secret" state/lock +ln -s "$PWD/secret" state/samples +ln -s "$PWD/run" state/rules +mkfifo state/fifo +chmod 0771 state + +# No probe listeners yet: only the edits, which the old queue held. +timeout 60 @runner@ --requests-only > log +grep -q 'no probe listeners' log +test "$(stat -c %a state)" = 751 +test -z "$(find state -mindepth 1 \( -type l -o -type p \))" +test "$(cat secret)" = secret.example +jq -e '.domains == {}' state/state.json > /dev/null +# The old requests wait in the spool, edits are applied and gone. +grep -qx old.example spool/requests.migrated.* +test -z "$(find spool -name 'edits*')" +test ! -e state/requests && test ! -e state/edits.taking + +# --- what members queue now, and what one may leave in the spool besides --- +printf '[{"i":0,"tag":"direct","port":1,"path":"%s/state/rules/rs-0.json"}, + {"i":1,"tag":"x","port":2,"path":"%s/state/rules/rs-1.json"}]\n' "$PWD" "$PWD" > run/probe-exits.json +printf 'new.example\n' > spool/requests.2.1 +ln -s "$PWD/secret" spool/requests.3.1 +mkfifo spool/requests.4.1 +mkdir spool/requests.5.1 +printf 'half.example\n' > spool/.requests.6.1.tmp +timeout 60 @runner@ --requests-only > log + +# Never through the link, never stuck on the FIFO, never the file still being written. +sort -u probed > probed.sorted +printf 'new.example\nold.example\n' | cmp - probed.sorted +test "$(cat secret)" = secret.example +# Only that one is left; what the run took is gone, whatever it was. +test "$(ls -A spool)" = .requests.6.1.tmp +jq -e '.domains | keys == ["new.example", "old.example"]' state/state.json > /dev/null +jq -e '.rules[0].domain_suffix | sort == ["new.example", "old.example"]' state/rules/rs-1.json > /dev/null +test "$(stat -c %a state/state.json)" = 640 +# The exit's "at" from the old state ran nothing. +test ! -e pwned +touch "$out" diff --git a/nix/checks/repo/proxy-ctl-complete.template.sh b/nix/checks/repo/proxy-ctl-complete.template.sh index 52eb672..95196d1 100644 --- a/nix/checks/repo/proxy-ctl-complete.template.sh +++ b/nix/checks/repo/proxy-ctl-complete.template.sh @@ -59,6 +59,18 @@ grep -qx "$(printf 'own-vps\tproxy.outbounds')" words run inbounds link > /dev/null env AWG_PROFILES_FILE=/nonexistent python3 "$proxy_ctl" __complete awg on +# A candidate is whatever a group member named a file: never shell code to whoever completes. +mkdir -p fake +printf '%s\n' '#!/bin/sh' "printf '%s\\n' 'ok-tag' '\$(touch pwned)' '\`touch pwned\`'" > fake/proxy-ctl +chmod +x fake/proxy-ctl +PATH="$PWD/fake:$PATH" bash -c 'source @bashCompletion@; COMP_WORDS=(proxy-ctl proxy outbounds rm ""); COMP_CWORD=4; _proxy_ctl; printf "%s\n" "${COMPREPLY[@]}"' > completed +[ ! -e pwned ] || { echo "bash completion ran a candidate" >&2; exit 1; } +grep -qx ok-tag completed +mkdir -p spool +touch 'spool/$(touch pwned).url' spool/fine.url +env RUNTIME_OUTBOUNDS_DIR="$PWD/spool" python3 "$proxy_ctl" __complete proxy outbounds rm | cut -f1 > words +! grep -q 'pwned' words || { echo "__complete offered shell code" >&2; exit 1; } + # Every shell's completion file at least parses. bash -n @bashCompletion@ @zsh@/bin/zsh -n @zshCompletion@ diff --git a/nix/checks/repo/proxy-ctl-outbounds.template.sh b/nix/checks/repo/proxy-ctl-outbounds.template.sh index 6b24713..90e5181 100644 --- a/nix/checks/repo/proxy-ctl-outbounds.template.sh +++ b/nix/checks/repo/proxy-ctl-outbounds.template.sh @@ -14,8 +14,7 @@ mkdir -p stub printf '%s\n' 'fi' printf '%s\n' 'exit 0' } > stub/systemctl -printf '#!/bin/sh\nprintf %%s "$2"\n' > stub/systemd-escape -chmod +x stub/systemctl stub/systemd-escape +chmod +x stub/systemctl export PATH="$PWD/stub:$PATH" mkdir -p obd subd cache @@ -68,10 +67,11 @@ done # Removing something that was never added says so. ! run proxy outbounds rm nope 2>/dev/null -# A good add lands in the spool group-readable, not world-readable. +# A good add lands in the spool root's alone: the link holds credentials, which the rest of +# the group sees only with the "secrets" scope. run proxy outbounds add spool-one http://example.com:1 | grep -q 'Added outbound: spool-one' [ "$(cat obd/spool-one.url)" = "http://example.com:1" ] -[ "$(stat -c %a obd/spool-one.url)" = "640" ] +[ "$(stat -c %a obd/spool-one.url)" = "600" ] run proxy outbounds | grep -q 'spool-one *runtime' # Adding it twice is refused. ! run proxy outbounds add spool-one http://example.com:1 2>/dev/null diff --git a/nix/checks/route-mode.nix b/nix/checks/route-mode.nix index 276938c..6e94d50 100644 --- a/nix/checks/route-mode.nix +++ b/nix/checks/route-mode.nix @@ -109,12 +109,17 @@ in true ) - # Setter unit is present and writes into /run. + # Setter unit is present and writes into /run: its directory outlives each run, and is + # the one place a root unit the group starts may write. ( let setterSvc = routeModeFixture.config.systemd.services."proxy-suite-route-mode@"; in - assert !(setterSvc.serviceConfig ? RuntimeDirectory); + assert setterSvc.serviceConfig.RuntimeDirectory == "proxy-suite"; + assert setterSvc.serviceConfig.RuntimeDirectoryPreserve == "yes"; + assert setterSvc.serviceConfig.ProtectSystem == "strict"; + assert setterSvc.serviceConfig.NoNewPrivileges; + assert !(setterSvc.serviceConfig ? ReadWritePaths); assert pkgs.lib.hasInfix "/run/proxy-suite/route-mode" routeModeSetterScript; # One case arm lists every mode the setter accepts. assert pkgs.lib.hasInfix "default | whitelist | blacklist | all-proxy | all-bypass)" diff --git a/nix/checks/server-module.nix b/nix/checks/server-module.nix index 749e525..42906c7 100644 --- a/nix/checks/server-module.nix +++ b/nix/checks/server-module.nix @@ -76,6 +76,12 @@ in (ok (failedAssertions ipServer == [ ])) (ok (failedAssertions domainServer == [ ])) (ok (failedAssertions diskoServer == [ ])) + # SSH on the REALITY port: refused, not left for the two to fight over at boot. + (ok ( + failedAssertions (mkServer { + sshPort = 443; + }) != [ ] + )) # disko: btrfs subvolumes, compressed, the swap file, and GRUB on the disk once. (ok (diskoFs."/".fsType == "btrfs" && builtins.elem "subvol=@" diskoFs."/".options)) diff --git a/nix/checks/subscriptions-runtime.nix b/nix/checks/subscriptions-runtime.nix index efa2cf6..f082da6 100644 --- a/nix/checks/subscriptions-runtime.nix +++ b/nix/checks/subscriptions-runtime.nix @@ -134,12 +134,77 @@ in true ) - # The fetcher's output must land in the cache, not after a stray newline. + # Private servers are kept only for a declared subscription that opts in: the flag rides + # both entry points to the fetcher; runtime subscriptions and the rest never pass it. ( - assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"'' + let + generated = import ./read-generated.nix; + fixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + backend = "sing-box"; + subscriptions = [ + { + tag = "lan"; + url = "https://sub.lan.example/token"; + allowPrivateServers = true; + } + { + tag = "community"; + url = "https://example.com/sub/token"; + } + ]; + }; + }; + } + ]; + unitScript = + unit: generated.readDerivation fixture.config.systemd.services.${unit}.serviceConfig.ExecStart; + linesWith = + infix: script: builtins.filter (pkgs.lib.hasInfix infix) (pkgs.lib.splitString "\n" script); + flagged = pkgs.lib.hasInfix " --allow-private-servers"; + flaggedOnly = + call: script: + builtins.all flagged (linesWith "${call} lan " script) + && linesWith "${call} lan " script != [ ] + && !(builtins.any flagged (linesWith "${call} community " script)) + && !(builtins.any flagged (linesWith ''${call} "$RUNTIME_SUB_TAG"'' script)); + start = unitScript "proxy-suite-socks"; + update = unitScript "proxy-suite-subscription-update"; + in + assert flaggedOnly "_proxy_suite_load_subscription" start; + assert flaggedOnly "_proxy_suite_fetch_subscription" update; + assert pkgs.lib.hasInfix ''_proxy_suite_fetch_subscription "$tag" "$src" "''${@:3}"'' start; + # Both the fetch through the tunnel and the kill switch's direct retry. + assert pkgs.lib.hasInfix + ''_proxy_suite_run_fetcher tunnel "$tag" "$src" "$cache_tmp" "$links_tmp" "''${@:3}"'' + update; + assert pkgs.lib.hasInfix + ''_proxy_suite_run_fetcher direct "$tag" "$src" "$cache_tmp" "$links_tmp" "''${@:3}"'' + update; + # Through the tunnel too, the subscription server's answer is not parsed as root. + assert pkgs.lib.hasInfix + "setpriv --reuid=proxy-suite-fetch --regid=proxy-suite-fetch --clear-groups" + update; + # Runtime ones over https only, unless the admin allows http. + assert pkgs.lib.hasInfix + ''_proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC" --https-only'' + update; + true + ) + + # The fetcher's output must land in the cache, not after a stray newline; each fetch in + # a temporary file of its own, which start scripts running at once do not share. + ( + assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-fd 3 "$@" > "$cache_tmp" 3> "$links_tmp"'' subscriptionOnlyStartScript; - assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"'' + assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-fd 3 "$@" > "$cache_tmp" 3> "$links_tmp"'' subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix ''tmp=$(mktemp "$1.XXXXXX")'' subscriptionOnlyUpdateScript; true ) diff --git a/nix/checks/tg-ws-proxy.nix b/nix/checks/tg-ws-proxy.nix index e2e66da..713532f 100644 --- a/nix/checks/tg-ws-proxy.nix +++ b/nix/checks/tg-ws-proxy.nix @@ -76,8 +76,10 @@ in # Global TUN/TProxy bypass mark keeps relay traffic out of transparent capture. ( assert !(tgWithGlobalTunServiceConfig ? SocketMark); - # The relay runs as the service user; only the bypass scripts are privileged. - assert tgWithGlobalTunServiceConfig.User == "proxy-suite-daemon"; + # The relay runs as a user of its own, not the backends' (whose files and traffic + # exemptions it would share); only the bypass scripts are privileged. + assert !(tgWithGlobalTunServiceConfig ? User); + assert tgWithGlobalTunServiceConfig.DynamicUser; assert tgWithGlobalTunServiceConfig.ExecStartPre == "+${tgWithGlobalTunModule.bypassUpScript}"; assert tgWithGlobalTunServiceConfig.ExecStopPost == "+${tgWithGlobalTunModule.bypassDownScript}"; assert pkgs.lib.hasInfix "\"system.slice/proxy-suite-tg-ws-proxy.service\" meta mark set 4" diff --git a/nix/checks/tor.nix b/nix/checks/tor.nix index 8459a44..ac06b92 100644 --- a/nix/checks/tor.nix +++ b/nix/checks/tor.nix @@ -179,10 +179,11 @@ let guardRuntime = pkgs.runCommand "proxy-suite-tor-guard-check" { nativeBuildInputs = [ pkgs.jq ]; } '' echo '{"inbounds":[],"outbounds":[],"dns":{"rules":[]},"route":{"rules":[]}}' | jq --slurpfile obs <(echo '[]') --argjson auth_enabled false --arg user "" --arg password "" \ - --argjson route_enabled true --argjson route_rules "$(cat ${guardRouteRules})" \ + --argjson route_enabled true --slurpfile route_rules ${guardRouteRules} \ --arg route_final proxy --arg dns_final remote --argjson clear_dns_rules false \ - --argjson probe_inbounds '[]' --argjson autoproxy_rule_sets '[]' --argjson autoproxy_rules '[]' \ - --argjson probe_pin_rules '[{"inbound":["probe-in-0"],"outbound":"direct"}]' \ + --slurpfile probe_inbounds <(echo '[]') --slurpfile autoproxy_rule_sets <(echo '[]') \ + --slurpfile autoproxy_rules <(echo '[]') \ + --slurpfile probe_pin_rules <(echo '[{"inbound":["probe-in-0"],"outbound":"direct"}]') \ -f ${guardFilter} > rules.json jq -e ' .route.rules as $r @@ -381,16 +382,20 @@ in true ) ( + # After the loopback guard, which every route mode keeps first. assert - xrayRouting.xrayRouteModeRules.common == [ - { - type = "field"; - ruleTag = "tor-onion"; - domain = [ "domain:onion" ]; - outboundTag = "tor"; - } - ] - && lib.head xrayRouting.xrayRoutingRules == lib.head xrayRouting.xrayRouteModeRules.common; + lib.last xrayRouting.xrayRouteModeRules.common == { + type = "field"; + ruleTag = "tor-onion"; + domain = [ "domain:onion" ]; + outboundTag = "tor"; + } + && + lib.take (builtins.length xrayRouting.xrayRouteModeRules.common) xrayRouting.xrayRoutingRules + == xrayRouting.xrayRouteModeRules.common + # Sniffing must not turn a transparent client's connection into one to this host. + && (lib.head xrayRouting.xrayRoutingRules).ruleTag == "guard-loopback-ip" + && (lib.head xrayRouting.xrayRoutingRules).outboundTag == "block"; true ) ( @@ -448,10 +453,12 @@ in true ) - # Tor runs as the service user, which TUN and TProxy let through, and keeps its keys private. + # Tor runs as a user of its own, which TUN and TProxy let through as they do the service + # user, and keeps its keys private: no other daemon's compromise reaches its control + # socket or onion key. ( assert - singBoxTorUnit.serviceConfig.User == "proxy-suite-daemon" + singBoxTorUnit.serviceConfig.User == "proxy-suite-tor" && singBoxTorUnit.serviceConfig.StateDirectory == "proxy-suite/tor" && singBoxTorUnit.serviceConfig.StateDirectoryMode == "0700"; true @@ -470,15 +477,22 @@ in ) # The control socket is Tor's alone, with userControl or without: with it the group could # publish any loopback port as an onion service. `proxy-ctl tor newnym` goes through a - # root unit, which polkit's "services" scope may start. + # unit running as Tor's own user, which polkit's "services" scope may start. ( assert - (services controlled).proxy-suite-tor.serviceConfig.Group == "proxy-suite-daemon" + (services controlled).proxy-suite-tor.serviceConfig.Group == "proxy-suite-tor" && hasInfix "mkdir -p -m 0700" (torStartOf controlled) && !(hasInfix "ControlSocketsGroupWritable" (torStartOf controlled)) && (services controlled) ? proxy-suite-tor-newnym + && (services controlled).proxy-suite-tor-newnym.serviceConfig.User == "proxy-suite-tor" + && (services controlled).proxy-suite-tor-newnym.serviceConfig.NoNewPrivileges + && + (services controlled).proxy-suite-tor-newnym.serviceConfig.RestrictAddressFamilies == [ + "AF_UNIX" + ] && hasInfix "\"proxy-suite-tor-newnym.service\"" (controlled.config.security.polkit.extraConfig) - && singBoxTorUnit.serviceConfig.Group == "proxy-suite-daemon" + && singBoxTorUnit.serviceConfig.Group == "proxy-suite-tor" + && builtins.elem "proxy-suite-tor" singBox.config.services.proxy-suite.internal.systemUsers && !(singBoxTorUnit.serviceConfig ? ExecStartPre) && (mkProxyCtlDerived singBox).wrapperEnv.TOR_CONTROL_SOCKET == "/run/proxy-suite-tor/control/socket"; @@ -499,11 +513,19 @@ in ( assert hasInfix "Socks5Proxy 127.0.0.1:1080" viaProxyStart - && hasInfix ''echo "Socks5ProxyUsername "local-user'' viaProxyStart + && hasInfix "echo 'Socks5ProxyUsername \"local-user\"'" viaProxyStart && hasInfix ''"$CREDENTIALS_DIRECTORY/proxy-password"'' viaProxyStart && builtins.elem "proxy-password:/run/secrets/local-proxy-password" viaProxyTor.serviceConfig.LoadCredential; true ) + # Through the local proxy Tor still runs as its own user, which must exist. + ( + assert + viaProxyTor.serviceConfig.User == "proxy-suite-tor" + && viaProxy.config.users.users.proxy-suite-tor.isSystemUser + && viaProxy.config.users.groups ? proxy-suite-tor; + true + ) # The onion service forwards each listener's share port to where it listens. ( diff --git a/nix/checks/user-control.nix b/nix/checks/user-control.nix index 5173f3b..09f743d 100644 --- a/nix/checks/user-control.nix +++ b/nix/checks/user-control.nix @@ -118,6 +118,13 @@ in assert hasInfix ''"proxy-suite-per-app-via-user@" ? instance.split("-")[0]'' ( polkitConfig allFixture ); + # What every user's apps share a member brings up, never down or through a restart: + # that would send the other users' apps out unmarked. Their own marking, either way. + assert hasInfix + ''if (scope === "perApp" && !own && ["start","reset-failed"].indexOf(verb) === -1) {'' + (polkitConfig allFixture); + assert hasInfix " own = true;\n }\n known = true;" (polkitConfig allFixture); + assert hasInfix "\"proxy-suite-per-app-\":\"perApp\"" (polkitConfig allFixture); assert groupReadsSecrets allFixture; assert hasInfix "chown proxy-suite-daemon:proxy-suite \"$backend_config\"" (socksStart allFixture); assert @@ -126,21 +133,34 @@ in "proxy-suite" "proxy-suite" ]; - assert (service allFixture "proxy-suite-autoproxy").StateDirectoryMode == "0771"; - # Root writes by fixed names in that group-writable directory: nowhere else. + # The state is root's to write, the group's to read; what members ask for goes to a + # sticky spool beside it, where no member takes away another's request. + assert (service allFixture "proxy-suite-autoproxy").StateDirectoryMode == "0751"; + assert builtins.elem "d /var/lib/proxy-suite/autoproxy-requests 3770 root proxy-suite -" ( + allFixture.config.systemd.tmpfiles.rules + ); + # Root removes what members queued in that group-writable spool: nothing else changes. assert builtins.all ( unit: let c = service allFixture unit; in - c.ProtectSystem == "strict" && c.ProtectHome && c.PrivateTmp + c.ProtectSystem == "strict" + && c.ProtectHome + && c.PrivateTmp + && c.ReadWritePaths == [ "-/var/lib/proxy-suite/autoproxy-requests" ] ) [ "proxy-suite-autoproxy" "proxy-suite-autoproxy-learn" "proxy-suite-autoproxy-sample" ]; + # An install from before the spool is made root's before the socks start writes there. + assert hasInfix + "-proxy-suite-autoproxy-migrate \"$AUTOPROXY_DIR\" /var/lib/proxy-suite/autoproxy-requests" + (socksStart allFixture); + assert (wrapperEnv allFixture).AUTOPROXY_SPOOL_DIR == "/var/lib/proxy-suite/autoproxy-requests"; assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 2770 root proxy-suite -" ( allFixture.config.systemd.tmpfiles.rules ); @@ -172,6 +192,9 @@ in null ]; assert (service routingOnlyFixture "proxy-suite-autoproxy").StateDirectoryMode == "0751"; + assert builtins.elem "d /var/lib/proxy-suite/autoproxy-requests 0700 root root -" ( + routingOnlyFixture.config.systemd.tmpfiles.rules + ); assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 0700 root root -" ( routingOnlyFixture.config.systemd.tmpfiles.rules ); @@ -216,10 +239,18 @@ in null null ]; - assert (service fixture "proxy-suite-autoproxy").StateDirectoryMode == "0771"; + assert (service fixture "proxy-suite-autoproxy").StateDirectoryMode == "0751"; assert derived.userControlExtraGroupsFor "autoProxy" == [ "proxy-admins" ]; + # The state dir read through its own unit's ACLs; the spool written through + # proxy-suite-acls', there before any autoProxy unit has run. assert pkgs.lib.hasSuffix "-proxy-suite-autoproxy-acl" (service fixture "proxy-suite-autoproxy").ExecStartPre; + assert builtins.elem "d /var/lib/proxy-suite/autoproxy-requests 3770 root root -" ( + fixture.config.systemd.tmpfiles.rules + ); + assert hasInfix + "setfacl -R -P -n -m g:proxy-admins:rwX,d:g:proxy-admins:rwX -- /var/lib/proxy-suite/autoproxy-requests" + acls; # Secrets to proxy-admins alone, still 600 for the primary group. assert hasInfix "chmod 600 \"$SHARE_TMP\"" start; assert hasInfix "setfacl -m g:proxy-admins:r -- \"$SHARE_TMP\"" start; diff --git a/nix/checks/warp.nix b/nix/checks/warp.nix index 4ac903b..968c99e 100644 --- a/nix/checks/warp.nix +++ b/nix/checks/warp.nix @@ -42,7 +42,7 @@ let generated.readDerivation fixture.config.systemd.services."proxy-suite-warp-tunnel".serviceConfig.ExecStart; convertCall = - fixture: "warp_outbound.py --tag warp --routing-mark ${markOf fixture} < \"$profile\""; + fixture: "warp_outbound.py --tag \"$TUNNEL_TAG\" --routing-mark ${markOf fixture} < \"$profile\""; singBoxHop = ''"server":"127.0.0.1","server_port":18538,"tag":"warp","type":"socks"''; xrayHop = ''"protocol":"socks","settings":{"address":"127.0.0.1","port":18538},"tag":"warp"''; @@ -276,6 +276,33 @@ in assert hasInfix (convertCall singBox) singBoxTunnel; true ) + # The tag reaches the scripts as a variable, never spliced into shell or jq text. + ( + assert + hasInfix "TUNNEL_TAG=warp\n" singBoxTunnel + && hasInfix "export TUNNEL_TAG" singBoxTunnel + && hasInfix ''jq -n --arg tag "$TUNNEL_TAG"'' singBoxTunnel + && hasInfix "final: $tag" singBoxTunnel + && !(hasInfix ''"warp"'' singBoxTunnel); + true + ) + # The root conversion step is sandboxed; the runtime directory stays writable for the + # watchdog's hints. + ( + let + sc = singBox.config.systemd.services."proxy-suite-warp-tunnel".serviceConfig; + in + assert + sc.NoNewPrivileges + && sc.PrivateTmp + && sc.ProtectSystem == "strict" + && sc.ReadWritePaths == [ "/run" ] + && sc.ProtectKernelTunables + && sc.ProtectControlGroups + && sc.RestrictSUIDSGID + && !(sc ? ProtectHome); + true + ) ( assert !(hasInfix "PrivateKey" singBoxTunnel); true @@ -331,7 +358,9 @@ in assert hasInfix "--reuid=proxy-suite-daemon" singBoxTunnel && hasInfix "--ambient-caps=-all,+net_admin --bounding-set" singBoxTunnel - && hasInfix ''{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: 18539}'' singBoxTunnel + && hasInfix ''{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: 18539,'' singBoxTunnel + # It reaches the uplink past the kill switch: a login drawn per start, never in argv. + && hasInfix ''users: [{username: "probe", password: $ENV.DIRECT_AUTH}]'' singBoxTunnel && hasInfix ''{type: "direct", tag: "direct", routing_mark: ${markOf singBox}}'' singBoxTunnel; true ) diff --git a/nix/checks/xray-backend-runtime/jq-filter-runtime.template.sh b/nix/checks/xray-backend-runtime/jq-filter-runtime.template.sh index 6b41cc6..1902cfa 100644 --- a/nix/checks/xray-backend-runtime/jq-filter-runtime.template.sh +++ b/nix/checks/xray-backend-runtime/jq-filter-runtime.template.sh @@ -13,7 +13,7 @@ check_runtime() { --arg user "" \ --arg password "" \ --argjson route_enabled true \ - --argjson route_rules '[]' \ + --slurpfile route_rules <(echo '[]') \ --arg route_final "proxy" \ --arg dns_final "remote" \ --argjson clear_dns_rules false \ diff --git a/nix/checks/xray-backend-runtime/tun/global.nix b/nix/checks/xray-backend-runtime/tun/global.nix index 02bd5ab..e2a499e 100644 --- a/nix/checks/xray-backend-runtime/tun/global.nix +++ b/nix/checks/xray-backend-runtime/tun/global.nix @@ -44,7 +44,7 @@ "172.19.0.1/30" checkConstants.globalTunIPv6Address ]; - assert tunInbound.sniffing.destOverride == [ "fakedns" ]; + assert tunInbound.sniffing.destOverride == [ "fakedns+others" ]; assert tunInbound.sniffing.metadataOnly == false; assert xrayTunConfig.routing.domainStrategy == "IPIfNonMatch"; assert tunHasFinalRuleTag; @@ -99,11 +99,13 @@ assert pkgs.lib.hasInfix "rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}" xrayTunUpScript; + # Both families, but IPv6 only where the kernel has it (ipv6.disable=1 refuses every -6). + assert pkgs.lib.hasInfix "if [ -e /proc/net/if_inet6 ]; then families+=(-6); fi" xrayTunUpScript; assert pkgs.lib.hasInfix - "-6 rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101" + ''"$family" rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101'' xrayTunUpScript; assert pkgs.lib.hasInfix - "-6 rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}" + ''"$family" rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}'' xrayTunUpScript; assert pkgs.lib.hasInfix ''"$family" rule add pref ${toString checkConstants.xrayTunMarkBypassRulePriority} fwmark 2 lookup main'' diff --git a/nix/checks/xray-backend-runtime/tun/per-app.nix b/nix/checks/xray-backend-runtime/tun/per-app.nix index faa3f2b..9ebe5b7 100644 --- a/nix/checks/xray-backend-runtime/tun/per-app.nix +++ b/nix/checks/xray-backend-runtime/tun/per-app.nix @@ -25,7 +25,7 @@ "172.20.0.1/30" checkConstants.perAppTunIPv6Address ]; - assert perAppTunInbound.sniffing.destOverride == [ "fakedns" ]; + assert perAppTunInbound.sniffing.destOverride == [ "fakedns+others" ]; assert perAppTunInbound.sniffing.metadataOnly == false; assert xrayPerAppTunConfig.routing.domainStrategy == "IPIfNonMatch"; assert (builtins.head xrayPerAppTunConfig.dns.servers).address == "fakedns"; diff --git a/nix/checks/zapret2.nix b/nix/checks/zapret2.nix index 6835329..157a85d 100644 --- a/nix/checks/zapret2.nix +++ b/nix/checks/zapret2.nix @@ -116,8 +116,16 @@ in in assert gc.Type == "notify" && sc.Type == "notify"; assert gc.Restart == "on-failure" && sc.Restart == "on-failure"; - assert lib.hasSuffix "stop_fw" gc.ExecStopPost; + assert lib.hasSuffix "stop_fw" (builtins.head gc.ExecStopPost); assert builtins.length sc.ExecStopPost == 2; + # Root in a directory the zapret scope writes to: a symlink there must not reach + # /proc/sys, /sys or devices. Hence also the conntrack sysctl outside it ("+"). + assert gc.ProtectKernelTunables && gc.PrivateDevices && sc.ProtectKernelTunables; + # And put back as it was on stop, not forced to 0. + assert + lib.hasPrefix "-+" gc.ExecStartPost + && lib.hasSuffix "-proxy-suite-zapret2-liberal" gc.ExecStartPost; + assert lib.hasSuffix "-proxy-suite-zapret2-liberal" (lib.last gc.ExecStopPost); true ) @@ -286,6 +294,13 @@ in end assert(key("a.b.foo.co.uk", "3") == "b.foo.co.uk") assert(key("1.2.3.4", "2", true) == "standard") + -- What detect.lua must never learn: a suffix takes every site under it. + for _, host in ipairs({ "com", "co.uk", "CO.UK.", "localhost" }) do + assert(proxy_suite_is_public_suffix(host), host) + end + for _, host in ipairs({ "example.com", "foo.co.uk", "github.io" }) do + assert(not proxy_suite_is_public_suffix(host), host) + end assert(key("www.google.com", nil) == "standard") ' # What nfqws2's learner and z2k's detector miss: flaky sites, stalled transfers, @@ -293,7 +308,8 @@ in # proxy routes by: works, unfixable, blocked by address. mkdir -p detect touch detect/verdicts.tsv - DETECT=$(grep -oE '/nix/store/[^ ]+-detect\.lua' "${z2kRuntime}/config") WORK="$PWD/detect" \ + PSL=$(grep -oE '/nix/store/[^ ]+-proxy-suite-zapret2-public-suffix-hostkey\.lua' "${z2kRuntime}/config") \ + DETECT=$(grep -oE '/nix/store/[^ ]+-detect\.lua' "${z2kRuntime}/config") WORK="$PWD/detect" \ PROXY_SUITE_ZAPRET2_VERDICTS="$PWD/detect/verdicts.tsv" lua ${./zapret2/detect-test.lua} # nfqws2 finds the verdicts file by its environment; the last profile watches # connections for addresses blocked outright. @@ -427,7 +443,9 @@ in grep -qF -- '[[ $last =~ ^[0-9]+$ ]] || last=0' ${cutoffProbe} if grep -qF -- '$((now - $(cat ts' ${cutoffProbe}; then exit 1; fi # The group's probe request comes through requests/, not the directory root works in. - grep -qF -- 'if [ -e requests/force ]; then' ${cutoffProbe} + grep -qF -- 'if [ -e requests/force ] || [ -L requests/force ]; then' ${cutoffProbe} + # Whatever a member left under the name goes, a directory too: set -e stopped every run. + grep -qF -- 'rm -rf -- requests/force' ${cutoffProbe} # Cut-off networks without a name become the proxy's rule-set; named ones stay with zapret2. rules=$(grep -oE '/nix/store/[^ ]+-proxy-suite-zapret2 asn.txt' ${cutoffProbe} | cut -d' ' -f1) diff --git a/nix/checks/zapret2/detect-test.lua b/nix/checks/zapret2/detect-test.lua index 7bc5b4d..e9b3862 100644 --- a/nix/checks/zapret2/detect-test.lua +++ b/nix/checks/zapret2/detect-test.lua @@ -51,6 +51,8 @@ local hrec = { nstrategy = 1, ctstrategy = 50 } function automate_host_record() return hrec end function z2k_fail_tls_alert() return "z2k" end +-- detect.lua's public suffixes, loaded before it as nfqws2 does. +dofile(os.getenv("PSL")) dofile(os.getenv("DETECT")) local auto = work .. "/auto.txt" @@ -233,4 +235,14 @@ end assert(verdicts()["149.154.167.99 ip"] == "blocked" and not verdicts()["192.168.1.1 ip"], "blocked by address") syn("149.154.167.99", true) assert(verdicts()["149.154.167.99 ip"] == "reachable", "an answer clears it") +-- A wildcard domain whose every fresh name resets: past its share of the list, the site +-- itself is learned, which covers the rest, rather than one more name of it. +local f2 = io.open(auto, "a") +for i = 1, 64 do f2:write("r" .. i .. ".wild.example\n") end +f2:close() +for _ = 1, 3 do + hello(flow("r65.wild.example")) + fire("psln_") +end +assert(learned()["wild.example"] and not learned()["r65.wild.example"], "a flooding site learned whole") print("detect.lua ok") diff --git a/nix/options-doc.nix b/nix/options-doc.nix index 6da7dea..d04ae64 100644 --- a/nix/options-doc.nix +++ b/nix/options-doc.nix @@ -115,6 +115,10 @@ import ./options-doc/render-options-markdown.nix { name = "tui"; summary = "The `proxy-tui` terminal UI."; } + { + name = "tools"; + summary = "Heavy helpers `proxy-ctl` can do without: lnav and curl-impersonate."; + } ]; defaultConfigText = lib.generators.toPretty { allowPrettyValues = true; } ( visibleConfig eval.options.services.proxy-suite eval.config.services.proxy-suite diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 056f667..ce6f325 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -8,6 +8,13 @@ # (modules/proxy-suite/service/control.nix); proxy_ctl.py reads every name with env(). env, guiRefreshInterval ? 3, + # Off where proxy-suitectl runs the units (nix-on-droid): proxy-ctl reaches it through + # SUPERVISOR_CTL, and systemd stays out of the closure. + withSystemd ? true, + # `proxy-ctl logs` follows in less without it. + withLnav ? true, + # Probes go through plain curl without it. + withCurlImpersonate ? true, # These four are also passed as derivations: the checks read the files' contents through # passthru.proxySuiteCheck, which toString in env would lose. subscriptionTagsFile, @@ -22,6 +29,17 @@ let "#!${pkgs.python3}/bin/python3\n" + builtins.readFile ./proxy-ctl/proxy_ctl.py ); wrapperEnv = env; + # Probes present a browser's TLS fingerprint: bot protection refuses plain + # curl. The newest Chrome profile the package ships, since the set varies by + # version; the build fails if there is none. + findProbeCurl = lib.optionalString withCurlImpersonate '' + probe_curl=$(ls ${pkgs.curl-impersonate}/bin/curl_chrome[0-9]* | grep -E '/curl_chrome[0-9]+$' | sort -V | tail -n 1) + [ -x "$probe_curl" ] + ''; + # Unset, proxy_ctl.py probes with the curl on PATH. + probeCurlFlag = lib.optionalString withCurlImpersonate ( + ''--set PROBE_CURL "$probe_curl" \'' + "\n " + ); envFlags = lib.concatStringsSep " " ( lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv ); @@ -47,12 +65,7 @@ let # /run/wrappers/bin first: the store's sudo, earlier on a PATH, refuses to run without setuid. wrapProgram "$out/bin/proxy-tui" \ --prefix PYTHONPATH : ${pythonModules} \ - --prefix PATH : "${ - lib.makeBinPath [ - proxyCtl - pkgs.systemd - ] - }" \ + --prefix PATH : "${lib.makeBinPath ([ proxyCtl ] ++ lib.optional withSystemd pkgs.systemd)}" \ --prefix PATH : /run/wrappers/bin ${envFlags} ''; }; @@ -133,11 +146,7 @@ let "''${gappsWrapperArgs[@]}" \ --prefix PYTHONPATH : "${pythonModules}:$out/lib/proxy-suite-gui" \ --prefix PATH : "${ - lib.makeBinPath [ - proxyCtl - pkgs.systemd - pkgs.qrencode - ] + lib.makeBinPath ([ proxyCtl ] ++ lib.optional withSystemd pkgs.systemd ++ [ pkgs.qrencode ]) }" \ --prefix PATH : /run/wrappers/bin \ --set PROXY_GUI_ICON_DIR "$out/share/proxy-suite-gui/icons" \ @@ -164,32 +173,28 @@ let ; script = unwrapped.drvAttrs.text; }; - # Probes present a browser's TLS fingerprint: bot protection refuses plain - # curl. The newest Chrome profile the package ships, since the set varies by - # version; the build fails if there is none. postBuild = '' install -Dm644 ${./proxy-ctl/completions/proxy-ctl.bash} \ "$out/share/bash-completion/completions/proxy-ctl" install -Dm644 ${./proxy-ctl/completions/_proxy-ctl} "$out/share/zsh/site-functions/_proxy-ctl" install -Dm644 ${./proxy-ctl/completions/proxy-ctl.fish} \ "$out/share/fish/vendor_completions.d/proxy-ctl.fish" - probe_curl=$(ls ${pkgs.curl-impersonate}/bin/curl_chrome[0-9]* | grep -E '/curl_chrome[0-9]+$' | sort -V | tail -n 1) - [ -x "$probe_curl" ] - wrapProgram "$out/bin/proxy-ctl" \ - --set PROBE_CURL "$probe_curl" \ - --set PROXY_CTL_MODULES ${pythonModules} \ + ${findProbeCurl}wrapProgram "$out/bin/proxy-ctl" \ + ${probeCurlFlag}--set PROXY_CTL_MODULES ${pythonModules} \ --prefix PATH : "${ - lib.makeBinPath [ + lib.makeBinPath ( # curl-impersonate's curl_chrome* wrappers are `#!/usr/bin/env bash`. - pkgs.bash - pkgs.curl - pkgs.fzf - # `proxy-ctl logs` follows in lnav. - pkgs.lnav - pkgs.proxychains-ng - pkgs.qrencode - pkgs.systemd - ] + lib.optional withCurlImpersonate pkgs.bash + ++ [ + pkgs.curl + pkgs.fzf + # `proxy-ctl logs` follows in lnav, or in less without it. + (if withLnav then pkgs.lnav else pkgs.less) + pkgs.proxychains-ng + pkgs.qrencode + ] + ++ lib.optional withSystemd pkgs.systemd + ) }" ${envFlags} ''; }; diff --git a/pkgs/proxy-ctl/completions/proxy-ctl.bash b/pkgs/proxy-ctl/completions/proxy-ctl.bash index c582bfe..333e456 100644 --- a/pkgs/proxy-ctl/completions/proxy-ctl.bash +++ b/pkgs/proxy-ctl/completions/proxy-ctl.bash @@ -1,8 +1,13 @@ # proxy-ctl knows its own verbs, tags, profiles and units: ask it. # It answers worddescription; bash has no room for the description. +# Not `compgen -W`: it expands its words, and a tag or list entry is whatever a member of +# the userControl groups named a file. _proxy_ctl() { - mapfile -t COMPREPLY < <( - compgen -W "$(proxy-ctl __complete "${COMP_WORDS[@]:1:COMP_CWORD-1}" 2>/dev/null | cut -f1)" \ - -- "${COMP_WORDS[COMP_CWORD]}") + local cur=${COMP_WORDS[COMP_CWORD]} word + COMPREPLY=() + while IFS= read -r word; do + word=${word%%$'\t'*} + [[ $word == "$cur"* ]] && COMPREPLY+=("$word") + done < <(proxy-ctl __complete "${COMP_WORDS[@]:1:COMP_CWORD-1}" 2>/dev/null) } complete -F _proxy_ctl proxy-ctl diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index fbd9c3b..1a01591 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -4,7 +4,10 @@ Configuration arrives through the environment the Nix wrapper sets. """ import base64 +import contextlib import datetime +import errno +import fcntl import getpass import http.client import importlib @@ -94,7 +97,7 @@ Changes and secrets need root or the userControl group. proxy mode [default|whitelist|blacklist|all-proxy|all-bypass] show or override the routing mode proxy subs [list|update] subscriptions; update refetches them - proxy subs add [tag] add a subscription (no tag: named after its host) + proxy subs add [tag] add a subscription (no tag: named after its host; -: stdin) proxy subs rm remove a runtime subscription proxy subs link [--qr] its URL proxy rulesets [list|update] rule sets and when they were fetched; update refetches @@ -263,6 +266,24 @@ def read_text(path): return f.read() +# Lists the zapret and outbounds groups write to: zapret's learned hosts run to thousands of +# lines, never to this. +SHARED_TEXT_MAX_BYTES = 16 * 1024 * 1024 + + +def read_shared_text(path, limit=SHARED_TEXT_MAX_BYTES): + """A file in a directory a group writes to: regular, not through a symlink, at most limit + bytes, else OSError. A member's link, FIFO or /dev/zero must not be read by root's run.""" + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, "rb") as f: + if not stat.S_ISREG(os.fstat(f.fileno()).st_mode): + raise OSError(errno.EINVAL, "not a regular file", path) + data = f.read(limit + 1) + if len(data) > limit: + raise OSError(errno.EFBIG, "file too large", path) + return data.decode("utf-8", errors="replace") + + def lines(text): """Lines the way awk and grep see them: a missing final newline is fine.""" if not text: @@ -324,7 +345,8 @@ def _spool_write(path, text="", mode=0o640): try: with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(text) - os.chmod(tmp, mode) + # By fd: a member may swap tmp for a symlink before a chmod by path. + os.fchmod(f.fileno(), mode) os.replace(tmp, path) except BaseException: try: @@ -334,6 +356,55 @@ def _spool_write(path, text="", mode=0o640): raise +LOCK_WAIT = 10 + + +def _lock_path(path): + return os.path.join(os.path.dirname(path) or ".", f".{os.path.basename(path)}.lock") + + +@contextlib.contextmanager +def _file_lock(path): + """flock on ..lock over a read-modify-write of path, so two proxy-ctl don't drop each + other's change. Yields whether it is held: no lock file to be had means unlocked, as before.""" + lock = _lock_path(path) + deadline = time.monotonic() + LOCK_WAIT + while True: + # Read-only and O_NOFOLLOW: flock needs no more, and the directory may be the group's. + try: + fd = os.open(lock, os.O_RDONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o660) + except OSError: + yield False + return + try: + held = False + while not held: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + held = True + except BlockingIOError: + if time.monotonic() >= deadline: + die(f"Something else is still changing {path} (it holds {lock}); try again.") + time.sleep(0.05) + except OSError: + break # a lock flock refuses: unlocked, as without one + # Removed by its holder meanwhile (groups rm): lock the one there now instead. + if held and not _same_file(fd, lock): + continue + yield held + return + finally: + os.close(fd) + + +def _same_file(fd, path): + try: + st, fst = os.stat(path, follow_symlinks=False), os.fstat(fd) + except OSError: + return False + return (st.st_dev, st.st_ino) == (fst.st_dev, fst.st_ino) + + def _run(argv, capture=False, quiet=False, stdin=None): """Runs argv; (exit status, stdout if captured). A missing binary is 127.""" sys.stdout.flush() @@ -350,11 +421,11 @@ def _run(argv, capture=False, quiet=False, stdin=None): return p.returncode, p.stdout or "" -def _run_foreground(argv): +def _run_foreground(argv, env=None): """Waits on argv the way a shell does: Ctrl-C is the child's to handle.""" sys.stdout.flush() try: - p = subprocess.Popen(argv) + p = subprocess.Popen(argv, env=env) except OSError: return 127 old = signal.signal(signal.SIGINT, signal.SIG_IGN) @@ -431,7 +502,10 @@ def _toggle(unit, name, verb="status", *_): die(f"{name} is not enabled in this configuration.") verb = _flip(unit, verb) if verb == "status": - systemctl("is-active", unit) + # is-active's code too, as systemctl gives it (3: not active): `if proxy-ctl tor status` works. + status, _ = systemctl("is-active", unit) + if status: + sys.exit(status) elif verb == "on": must("start", unit) elif verb == "off": @@ -475,13 +549,18 @@ def cmd_warp(*args): _toggle(devices[0][1], "warp", *args) return verb = args[0] if args else "status" + states = [] for tag, unit in devices: if verb == "status": state = systemctl("is-active", unit, capture=True, quiet=True)[1].strip() or "inactive" + states.append(state) print(f"{tag:<16} {state}") else: print(f"{tag}:", flush=True) _toggle(unit, tag, verb) + # As `systemctl is-active` with several units: 0 when any is active, else 3. + if verb == "status" and "active" not in states: + sys.exit(3) def _tor_control(*commands): @@ -756,7 +835,7 @@ COMPLETE = { "words": { "list": "subscription caches", "update": "refetch the subscriptions", - "add": "add a subscription at runtime: [tag] ", + "add": "add a subscription at runtime: [tag] ", "rm": "remove a runtime subscription", "link": "its URL", } @@ -801,10 +880,10 @@ COMPLETE = { } }, "zapret auto retry": {"args": lambda: _names(name for name, _ in _zapret_proxied())}, - "zapret auto forget": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-auto.txt"))))}, - "zapret auto exclude": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-auto.txt"))))}, - "zapret auto unpin": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-user.txt"))))}, - "zapret auto include": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-user-exclude.txt"))))}, + "zapret auto forget": {"args": lambda: _names(lines(read_shared_text(_zapret_auto_file("zapret-hosts-auto.txt"))))}, + "zapret auto exclude": {"args": lambda: _names(lines(read_shared_text(_zapret_auto_file("zapret-hosts-auto.txt"))))}, + "zapret auto unpin": {"args": lambda: _names(lines(read_shared_text(_zapret_auto_file("zapret-hosts-user.txt"))))}, + "zapret auto include": {"args": lambda: _names(lines(read_shared_text(_zapret_auto_file("zapret-hosts-user-exclude.txt"))))}, "zapret cutoff": {"words": {"status": "networks this line cuts at 16 KB", "probe": "probe this line again now"}}, "awg": { "words": { @@ -949,6 +1028,11 @@ def _complete_tree(*words): return candidates +# A completion word as a shell may take it: many come from group-writable files, and bash's +# `compgen -W` expands "$(...)" in them as whoever pressed TAB. +COMPLETION_WORD = re.compile(r"[\w.@:+=,/%-]+") + + def cmd_complete(*words): """The hidden verb the shell completions call. It never fails or speaks.""" try: @@ -956,6 +1040,9 @@ def cmd_complete(*words): except Exception: return for word, description in candidates.items(): + if not isinstance(word, str) or not COMPLETION_WORD.fullmatch(word): + continue + description = _UNPRINTABLE.sub("", str(description or "").replace("\t", " ").replace("\n", " ")) print(f"{word}\t{description}" if description else word) @@ -989,11 +1076,16 @@ def _unit_states(units): """unit -> ActiveState for the units that exist, in one systemctl call.""" if not units: return {} - _, out = systemctl("show", "--property=Id,LoadState,ActiveState", "--", *units, capture=True, quiet=True) + status, out = systemctl("show", "--property=Id,LoadState,ActiveState", "--", *units, capture=True, quiet=True) + if status: + return {} # unread, as when it prints nothing: the front ends show it as unavailable + # By Id, not position: a block skipped or out of order must not shift states onto other units. + names = {**{f"{u}.service": u for u in units}, **{u: u for u in units}} states = {} - for unit, block in zip(units, out.strip().split("\n\n"), strict=False): + for block in (out or "").strip().split("\n\n"): props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line) - if props.get("LoadState") not in (None, "not-found"): + unit = names.get(props.get("Id", "")) + if unit and props.get("LoadState") not in (None, "not-found"): states[unit] = props.get("ActiveState", "unknown") return states @@ -1010,6 +1102,18 @@ KILL_SWITCH = "proxy-suite-killswitch" BUSY_STATES = ("activating", "deactivating", "reloading") +def _lift_kill_switch(): + """Stops the kill switch once a global tunnel is stopped on purpose, unless another one still runs.""" + if not svc_exists(KILL_SWITCH): + return + tunnels = ["proxy-suite-tun", "proxy-suite-tproxy", *map(_awg_service, _awg_profiles())] + running = sorted(u for u, s in _unit_states(tunnels).items() if s in ("active", "activating", "reloading")) + if running: + print(f"The kill switch stays up for {', '.join(running)}; lift it anyway with: proxy-ctl killswitch off", file=sys.stderr) + return + systemctl("stop", KILL_SWITCH) + + def _snapshot_units(): profiles = _awg_profiles() # WARP devices have no profile to toggle, but their units can fail (_warp_devices). A wrapper @@ -1174,7 +1278,7 @@ def _status_zapret(): if not readable(auto): return "" try: - return str(sum(1 for line in lines(read_text(auto)) if line)) + return str(sum(1 for line in lines(read_shared_text(auto)) if line)) except OSError: return "" @@ -1226,9 +1330,10 @@ def cmd_proxy(verb="status", *args): elif verb == "off": if not svc_exists("proxy-suite-socks"): die("proxy is not enabled in this configuration.") - for svc in ("proxy-suite-tproxy", "proxy-suite-tun", KILL_SWITCH): + for svc in ("proxy-suite-tproxy", "proxy-suite-tun"): if svc_exists(svc): systemctl("stop", svc) + _lift_kill_switch() must("stop", "proxy-suite-socks") elif verb == "outbounds": cmd_outbounds(*args) @@ -1252,8 +1357,8 @@ def cmd_proxy(verb="status", *args): action = _flip(f"proxy-suite-{verb}", *args[:1]) _toggle(f"proxy-suite-{verb}", f"proxy {verb}", action) # A mode stopped on purpose lifts the kill switch; one that fails leaves it up. - if action == "off" and svc_exists(KILL_SWITCH): - systemctl("stop", KILL_SWITCH) + if action == "off": + _lift_kill_switch() elif verb == "clash-broker": # proxy-suite-clash-api's ExecStart. _clash_broker_serve() @@ -1465,6 +1570,8 @@ def _clash_via_broker(broker, method, path, body, timeout): # let any of them switch what everyone dials and see everyone's connections. CLASH_TEST_SELECTOR = "proxy-suite-test" +# What delay tests fetch when the start script names no proxy.urlTest.url. +URL_TEST_DEFAULT = "https://www.gstatic.com/generate_204" CLASH_BROKER_MAX_BODY = 64 * 1024 # Any local user may connect: a caller that stalls, or opens many, holds no thread for long # and never all of them. @@ -1506,12 +1613,20 @@ def _broker_scopes(uid): return held -def _broker_allows(method, path, scopes): - """Whether a caller holding `scopes` may make this request; `path` without its query. +def _broker_test_urls(): + """The URLs a delay test through the broker may fetch: urlTest.url, as proxy-ctl reads it.""" + test = read_json_or(_runtime_file("outbound-test.json"), {}) + return {_s(test.get("url") or URL_TEST_DEFAULT), _s(_outbound_inventory().get("url") or URL_TEST_DEFAULT)} + + +def _broker_allows(method, path, scopes, query=""): + """Whether a caller holding `scopes` may make this request; `path` and its `query` apart. Only what proxy-ctl asks: reads and delay tests for any member, the download test's own selector too, switching the others with `routing`, live connections with `secrets`. Nothing else: not closing connections, the config, the logs or the traffic stream. + A delay test fetches the configured test URL only: any other would have the backend + fetch what the caller names, LAN addresses included. """ if "*" in scopes: return True @@ -1524,7 +1639,13 @@ def _broker_allows(method, path, scopes): return ( parts == ["proxies"] or (parts[0] == "proxies" and len(parts) == 2) - or (parts[0] in ("proxies", "group") and len(parts) == 3 and parts[2] == "delay") + or ( + parts[0] in ("proxies", "group") + and len(parts) == 3 + and parts[2] == "delay" + and len(urls := urllib.parse.parse_qs(query, keep_blank_values=True).get("url") or []) == 1 + and urls[0] in _broker_test_urls() + ) or (parts == ["connections"] and "secrets" in scopes) ) if method == "PUT" and parts[0] == "proxies" and len(parts) == 2: @@ -1563,7 +1684,7 @@ def _clash_broker_server(path): uid = _peer_uid(self.connection) scopes = _broker_scopes(uid) parts = urllib.parse.urlsplit(self.path) - if scopes is None or not _broker_allows(method, parts.path, scopes): + if scopes is None or not _broker_allows(method, parts.path, scopes, parts.query): # repr: the path is the caller's, escape sequences and all. print(f"proxy-suite-clash-api: refused uid {uid}: {method} {parts.path!r}", file=sys.stderr) return self._reply(403, {"message": "not allowed for your userControl scopes"}) @@ -1608,9 +1729,8 @@ def _clash_broker_server(path): return False def process_request(self, request, client_address): - # A full house holds the next one back a while (proxy-ctl alone tests 16 - # outbounds at once), then lets it go. - if not self.slots.acquire(timeout=CLASH_BROKER_TIMEOUT): + # A full house turns the next one away at once: waiting here would stall accept(). + if not self.slots.acquire(blocking=False): self.shutdown_request(request) return try: @@ -1687,6 +1807,16 @@ def _test_delay(backend_tag, url): return {0: "no API", 504: "timeout"}.get(status, "failed") +def _probe_login(): + """(user, password) of the probe and test listeners, drawn on each start (they reach any + exit, so not every local user may); None when unreadable.""" + try: + user, sep, password = read_text(_runtime_file("probe-login")).strip().partition(":") + except OSError: + return None + return (user, password) if sep and user and password else None + + def _timed_download(port): """Megabits per second through the test listener, None when nothing arrived. @@ -1694,7 +1824,7 @@ def _timed_download(port): anywhere else. """ conn = http.client.HTTPSConnection("127.0.0.1", port, timeout=TEST_DOWNLOAD_SECONDS) - login = _local_proxy_login() + login = _probe_login() auth = {"Proxy-Authorization": "Basic " + base64.b64encode(":".join(login).encode()).decode()} if login else {} conn.set_tunnel(TEST_DOWNLOAD_HOST, headers=auth) got = 0 @@ -1763,7 +1893,7 @@ def cmd_outbounds_test(*args): if not backend.get(tag): return "-" if kind == "delay": - return _test_delay(backend[tag], test.get("url") or "https://www.gstatic.com/generate_204") + return _test_delay(backend[tag], test.get("url") or URL_TEST_DEFAULT) return _test_download(backend[tag], test) # Ping and delay all at once, and done before any download competes with them. @@ -1980,11 +2110,22 @@ def _pick_pin(choices, header): return "" if status else tag +def unit_escape(text): + """systemd-escape, in-process: proxy-suitectl hosts have no systemd to run it from.""" + out = [] + for i, byte in enumerate(text.encode()): + char = chr(byte) + if char == "/": + out.append("-") + elif (char == "." and i == 0) or not (char.isascii() and (char.isalnum() or char in ":_.")): + out.append(f"\\x{byte:02x}") + else: + out.append(char) + return "".join(out) + + def _start_pin_unit(instance): - status, escaped = _run(["systemd-escape", "--", instance], capture=True) - if status: - sys.exit(status) - unit = "proxy-suite-outbound-pin@" + escaped.rstrip("\n") + unit = "proxy-suite-outbound-pin@" + unit_escape(instance) if systemctl("start", f"{unit}.service")[0]: die(f"Failed - see: proxy-ctl logs {unit}") @@ -2168,15 +2309,17 @@ class GroupWatch: names = os.listdir(directory) except OSError: return fresh + seen = {} for name in names: try: - mtime = os.stat(os.path.join(directory, name)).st_mtime + mtime = os.lstat(os.path.join(directory, name)).st_mtime except OSError: continue - if self.seen_hints.get(name) != mtime: - if name in self.seen_hints: - fresh.append(name) - self.seen_hints[name] = mtime + if self.seen_hints.get(name) != mtime and name in self.seen_hints: + fresh.append(name) + seen[name] = mtime + # Only what is there now: names removed since are forgotten, not kept for good. + self.seen_hints = seen return fresh def step(self, inventory, hinted=()): @@ -2184,10 +2327,11 @@ class GroupWatch: groups = self.watched(inventory) if not groups: return [] - url = _s(inventory.get("url") or "https://www.gstatic.com/generate_204") + url = _s(inventory.get("url") or URL_TEST_DEFAULT) disabled = set(inventory.get("disabled") or []) now_clock = self.clock() - hinted = set(hinted) + # Anyone may leave a hint: only a watched member's is worth a test and a place in the state. + hinted = set(hinted) & {m for info in groups.values() for m in info.get("members") or [] if m != "block"} results = {} # A hinted tag is tested at once, and so is everything around it. for tag in hinted: @@ -2241,17 +2385,21 @@ class GroupWatch: fd, tmp = tempfile.mkstemp(dir=_groups_dir(), prefix=".groups-state.") with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(self.state(_group_nows()), f) - os.chmod(tmp, 0o644) + os.fchmod(f.fileno(), 0o644) os.replace(tmp, path) except OSError: pass def run(self): health = os.path.join(_groups_dir(), "health") - os.makedirs(health, exist_ok=True) # Watchdogs run as other users (the WARP tunnel as the service user). A hint only makes - # this test sooner, so anyone may leave one; nobody may list or remove another's. - os.chmod(health, 0o1733) + # this test sooner, so they may leave one; nobody may list or remove another's. As + # root, the unit makes it first, for the service user's group alone. + try: + os.mkdir(health) + os.chmod(health, 0o1733) + except FileExistsError: + pass self.hints() # what is there already is no news last_state = 0.0 while True: @@ -2271,8 +2419,7 @@ def _group_file(tag): def _read_group_file(tag): try: - with open(_group_file(tag), encoding="utf-8") as f: - data = json.load(f) + data = json.loads(read_shared_text(_group_file(tag), RUNTIME_APP_MAX_BYTES)) except FileNotFoundError: die(f"'{tag}' is not a group added with proxy-ctl; declared groups change in the configuration.") except (OSError, ValueError): @@ -2280,6 +2427,14 @@ def _read_group_file(tag): return data if isinstance(data, dict) else {} +def _group_lock(tag): + """_file_lock over a runtime group's file; dies first for a tag that is no such group.""" + _check_tag_shape("group", tag) + if not os.path.lexists(_group_file(tag)): + _read_group_file(tag) # says why + return _file_lock(_group_file(tag)) + + def _write_group_file(tag, data): path = _group_file(tag) try: @@ -2379,52 +2534,63 @@ def cmd_groups(verb="list", *args): usage(GROUP_ADD_SHAPE) tag, members = rest[0], rest[1:] _check_runtime_tag("outbound", tag) - if tag in _outbound_groups() or os.path.exists(_group_file(tag)): + if tag in _outbound_groups() or os.path.lexists(_group_file(tag)): die(f"A group named '{tag}' already exists.") if not members and not opts["subscriptions"] and not opts["match"]: die("A group needs members, a --sub or a --match.") _group_check_members(tag, members) - _write_group_file(tag, {"outbounds": members, **opts}) + with _file_lock(_group_file(tag)): + if os.path.lexists(_group_file(tag)): + die(f"A group named '{tag}' already exists.") + _write_group_file(tag, {"outbounds": members, **opts}) _runtime_reload() print(f"Added group: {tag}") elif verb == "rm": if len(args) != 1: usage("proxy groups rm ") tag = args[0] - _read_group_file(tag) - try: - os.unlink(_group_file(tag)) - except OSError: - denied(_group_file(tag), "remove") + # Locked: a members or strategy edit under way would write it back. + with _group_lock(tag) as held: + _read_group_file(tag) + try: + os.unlink(_group_file(tag)) + except OSError: + denied(_group_file(tag), "remove") + # Only the holder's: one waiting on it relocks the new one (_file_lock). + if held: + with contextlib.suppress(OSError): + os.unlink(_lock_path(_group_file(tag))) _runtime_reload() print(f"Removed group: {tag}") elif verb == "members": if len(args) < 3 or args[1] not in ("add", "rm"): usage("proxy groups members add|rm ") tag, action, names = args[0], args[1], list(args[2:]) - data = _read_group_file(tag) - members = [m for m in data.get("outbounds") or [] if isinstance(m, str)] - if action == "add": - _group_check_members(tag, names) - members += [n for n in names if n not in members] - else: - missing = [n for n in names if n not in members] - if missing: - die(f"Not listed in '{tag}': {', '.join(missing)}") - members = [m for m in members if m not in names] - if not members and not data.get("subscriptions") and not data.get("match"): - die(f"That would leave '{tag}' empty; remove the group instead: proxy-ctl proxy groups rm {tag}") - data["outbounds"] = members - _write_group_file(tag, data) + with _group_lock(tag): + data = _read_group_file(tag) + members = [m for m in data.get("outbounds") or [] if isinstance(m, str)] + if action == "add": + _group_check_members(tag, names) + members += [n for n in names if n not in members] + else: + missing = [n for n in names if n not in members] + if missing: + die(f"Not listed in '{tag}': {', '.join(missing)}") + members = [m for m in members if m not in names] + if not members and not data.get("subscriptions") and not data.get("match"): + die(f"That would leave '{tag}' empty; remove the group instead: proxy-ctl proxy groups rm {tag}") + data["outbounds"] = members + _write_group_file(tag, data) _runtime_reload() print(f"{tag}: {', '.join(members) or '(members from --sub/--match only)'}") elif verb == "strategy": if len(args) != 2 or args[1] not in GROUP_STRATEGIES: usage(f"proxy groups strategy {'|'.join(GROUP_STRATEGIES)}") tag, strategy = args - data = _read_group_file(tag) - data["strategy"] = strategy - _write_group_file(tag, data) + with _group_lock(tag): + data = _read_group_file(tag) + data["strategy"] = strategy + _write_group_file(tag, data) _runtime_reload() print(f"{tag}: {strategy}") else: @@ -2442,8 +2608,7 @@ def _priority_file(): def _runtime_priority(): - data = read_json_or(_priority_file(), {}) - return {k: v for k, v in data.items() if isinstance(v, int)} if isinstance(data, dict) else {} + return {k: v for k, v in _read_shared_json(_priority_file()).items() if isinstance(v, int)} def cmd_priority(*args): @@ -2462,30 +2627,32 @@ def cmd_priority(*args): tag, value = args if tag not in _outbound_tags() and tag not in _outbound_groups(): die(f"Unknown outbound or group: {tag}") - data = _runtime_priority() - if value == "--clear": - data.pop(tag, None) - elif value in ("up", "down"): - # Every top-level entry numbered in the new order, 10 apart: room to slot one in by hand. - top = [_s(t) for t in _outbound_inventory().get("top") or []] - if tag not in top: - die(f"'{tag}' is not at the top level; a group orders its members itself.") - i = top.index(tag) - j = i - 1 if value == "up" else i + 1 - if not 0 <= j < len(top): - print(f"{tag} is already {'first' if value == 'up' else 'last'}.") - return - top[i], top[j] = top[j], top[i] - data.update({t: 10 * (n + 1) for n, t in enumerate(top)}) - elif re.fullmatch(r"-?\d+", value): - data[tag] = int(value) - else: - usage("proxy priority |up|down|--clear") path = _priority_file() - try: - _spool_write(path, json.dumps(data, indent=2, sort_keys=True) + "\n") - except OSError: - denied(path, "write") + # Read to write under one lock: the GUI and a terminal at once would drop one's change. + with _file_lock(path): + data = _runtime_priority() + if value == "--clear": + data.pop(tag, None) + elif value in ("up", "down"): + # Every top-level entry numbered in the new order, 10 apart: room to slot one in by hand. + top = [_s(t) for t in _outbound_inventory().get("top") or []] + if tag not in top: + die(f"'{tag}' is not at the top level; a group orders its members itself.") + i = top.index(tag) + j = i - 1 if value == "up" else i + 1 + if not 0 <= j < len(top): + print(f"{tag} is already {'first' if value == 'up' else 'last'}.") + return + top[i], top[j] = top[j], top[i] + data.update({t: 10 * (n + 1) for n, t in enumerate(top)}) + elif re.fullmatch(r"-?\d+", value): + data[tag] = int(value) + else: + usage("proxy priority |up|down|--clear") + try: + _spool_write(path, json.dumps(data, indent=2, sort_keys=True) + "\n") + except OSError: + denied(path, "write") _runtime_reload() print(f"{tag}: {'default order' if value == '--clear' else 'moved ' + value if value in ('up', 'down') else value}") @@ -2543,8 +2710,10 @@ def _local_file_keys(ob): if isinstance(item, dict): for key, child in item.items(): k = str(key).lower() + # Non-ASCII: Go's JSON decoding folds "ſ" to s and "K" to k (localFileKeysJq). if ( - k.endswith(("file", "directory")) + not k.isascii() + or k.endswith(("file", "directory")) or (k.endswith("path") and k != "path") or k in ("masterkeylog", "torrc", "extra_args") ): @@ -2572,13 +2741,25 @@ def _runtime_json_outbound(text): return json.dumps(ob, ensure_ascii=False) -def _check_runtime_tag(kind, tag): - 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): +RUNTIME_TAG = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") + + +def _check_tag_shape(kind, tag): + """What add accepts; rm and edits too, so a tag never walks out of the spool (../).""" + if not RUNTIME_TAG.fullmatch(tag): die(f"Invalid {kind} tag '{tag}': letters, digits, dot, dash and underscore only.") - if tag in _runtime_tags(kind): - die(f"A runtime {kind} named '{tag}' already exists; remove it first.") + + +# As the start script skips them, with proxy-suite-*: "priority" would be priority.json in the +# outbounds spool, "tor" the Tor outbound (reserved here whether or not this host has one). +RUNTIME_RESERVED_TAGS = ("proxy", "direct", "block", "priority", "tor") + + +def _check_runtime_tag(kind, tag): + if tag in RUNTIME_RESERVED_TAGS or tag.startswith("proxy-suite-"): + die(f"'{tag}' is reserved; pick another {kind} tag.") + _check_tag_shape(kind, tag) + _check_runtime_unused(kind, tag) if kind == "outbound": if tag in _outbound_tags(): die(f"An outbound named '{tag}' already exists.") @@ -2591,11 +2772,21 @@ def _check_runtime_tag(kind, tag): RUNTIME_TAG_MAX = 32 +def _check_runtime_unused(kind, tag): + if tag in _runtime_tags(kind): + die(f"A runtime {kind} named '{tag}' already exists; remove it first.") + + +def _runtime_lock(kind): + """Held over an add or rm in a runtime spool: two at once could take one tag, or AmneziaWG port.""" + return _file_lock(os.path.join(_runtime_dir(kind), "entries")) + + def _runtime_source(kind, arg): """Whether an add argument is the entry itself rather than its tag.""" if kind == "outbound" and (_awg_source(arg) or _awg_file(arg)): return True - return "://" in arg or (kind == "outbound" and (arg == "-" or arg.lstrip().startswith("{"))) + return "://" in arg or arg == "-" or (kind == "outbound" and arg.lstrip().startswith("{")) def _vmess_name(url): @@ -2649,7 +2840,7 @@ def _runtime_tag_for(kind, source): def _unique_runtime_tag(kind, name, fallback): """`name` as a tag nothing else has taken: -2, -3... after it.""" base = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-._")[:RUNTIME_TAG_MAX].strip("-._") or fallback - taken = {"proxy", "direct", "block", *_runtime_tags(kind), *(_outbound_tags() if kind == "outbound" else _sub_tags())} + taken = {*RUNTIME_RESERVED_TAGS, *_runtime_tags(kind), *(_outbound_tags() if kind == "outbound" else _sub_tags())} tag, n = base, 1 while tag in taken: n += 1 @@ -2659,7 +2850,7 @@ def _unique_runtime_tag(kind, name, fallback): def _runtime_entry_add(kind, *args, detour="", container="", awg_kind=""): - what = " [--detour ]" if kind == "outbound" else "" + 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]): tag, url = "", args[0] @@ -2674,8 +2865,11 @@ def _runtime_entry_add(kind, *args, detour="", container="", awg_kind=""): # The start script checks the chain again, and leaves the outbound out if it breaks later. if detour and (detour == tag or detour not in _outbound_tags()): die(f"Cannot chain through '{detour}': not an outbound. See: proxy-ctl proxy outbounds") - if kind == "outbound" and url == "-": + # "-": the link on stdin, out of argv, so out of ps, sudo's and pkexec's logs while it waits to come up. + if url == "-": url = sys.stdin.read() + if not url.strip(): + die(f"Nothing on stdin: pipe the {'link or JSON' if kind == 'outbound' else 'URL'} in.") if kind == "outbound" and _awg_file(url): url = _awg_input(url) if kind == "outbound" and _awg_source(url): @@ -2685,6 +2879,13 @@ def _runtime_entry_add(kind, *args, detour="", container="", awg_kind=""): die("--container only applies to an AmneziaWG vpn:// link.") if awg_kind: die(f"--{awg_kind} only applies to an AmneziaWG config.") + # Over plain http anyone on the path could swap in their own servers. + scheme = url.strip().split("://", 1)[0].lower() + if kind == "subscription" and scheme != "https" and not (scheme == "http" and env("RUNTIME_SUBS_ALLOW_HTTP") == "1"): + die( + "A subscription must be an https:// URL: fetched over plain http, anyone on the path could rewrite its entries." + + (" An admin may allow http:// with services.proxy-suite.proxy.runtimeSubscriptions.allowHttp." if scheme == "http" else "") + ) if not tag: tag = _runtime_tag_for(kind, url) _check_runtime_tag(kind, tag) @@ -2697,16 +2898,20 @@ def _runtime_entry_add(kind, *args, detour="", container="", awg_kind=""): else: url = url.strip() path = os.path.join(_runtime_dir(kind), tag + ext) - try: - # The hop first: the entry is what the start script looks for. - hop = os.path.join(_runtime_dir(kind), f"{tag}.detour") - if detour: - _spool_write(hop, f"{detour}\n") - elif os.path.lexists(hop): - os.unlink(hop) # left from an earlier entry of this name: it would chain this one too - _spool_write(path, f"{url}\n") - except OSError: - denied(path, "write") + with _runtime_lock(kind): + _check_runtime_unused(kind, tag) + try: + # The hop first: the entry is what the start script looks for. + hop = os.path.join(_runtime_dir(kind), f"{tag}.detour") + if detour: + _spool_write(hop, f"{detour}\n") + elif os.path.lexists(hop): + os.unlink(hop) # left from an earlier entry of this name: it would chain this one too + # Root's alone to read: the link (or JSON) holds the server's credentials, which + # other members of the group need the "secrets" scope to see (`link`). + _spool_write(path, f"{url}\n", 0o600) + except OSError: + denied(path, "write") _runtime_reload() _runtime_entry_verify(kind, tag) @@ -2749,22 +2954,24 @@ def cmd_outbound_chain(tag="", hop="", new_tag="", *_): def _runtime_entry_rm(kind, tag="", *_): if not tag: usage(f"proxy {_runtime_noun(kind)} rm ") - path = _runtime_path(kind, tag) - if not os.path.exists(path): - # The dir may be root-only: an entry that is there looks absent from outside it. - if _runtime_hidden(kind): - die(f"Cannot see the entry for '{tag}' in {_runtime_dir(kind)} - {ask_group()}") - die(f"No runtime {kind} named '{tag}'. Ones declared in the NixOS configuration are removed there.") - 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", ".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: - pass - except OSError: - denied(path, "remove") + _check_tag_shape(kind, tag) + with _runtime_lock(kind): + path = _runtime_path(kind, tag) + if not os.path.exists(path): + # The dir may be root-only: an entry that is there looks absent from outside it. + if _runtime_hidden(kind): + die(f"Cannot see the entry for '{tag}' in {_runtime_dir(kind)} - {ask_group()}") + die(f"No runtime {kind} named '{tag}'. Ones declared in the NixOS configuration are removed there.") + 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", ".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: + pass + except OSError: + denied(path, "remove") _runtime_reload() print(f"Removed {kind}: {tag}") @@ -2817,7 +3024,9 @@ def cmd_outbound_disable(tag="", *_): def cmd_outbound_enable(tag="", *_): if not tag: usage("proxy outbounds enable ") - if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", tag): + # A subscription's tags keep their letters (sub-Россия), which disable took: the running + # proxy's list of disabled ones vouches for those. Never a path of its own. + if "/" in tag or tag in (".", "..") or not (RUNTIME_TAG.fullmatch(tag) or tag in _outbound_disabled()): die(f"Not disabled: {tag}") marker = _outbound_disabled_marker(tag) if not os.path.exists(marker): @@ -2850,8 +3059,8 @@ def _runtime_entry_verify(kind, tag): if tag in _outbound_tags(): print(f"Added outbound: {tag}") return - elif os.path.isfile(_subscription_cache(tag)): - print(f"Added subscription: {tag} ({_subscription_proxy_count_text(_subscription_cache(tag))} proxies)") + elif state := _subscription_state(tag): + print(f"Added subscription: {tag} ({state[1]} proxies)") return if time.monotonic() >= deadline: break @@ -2890,14 +3099,29 @@ def _subscription_proxy_count_text(path): return "?" -def _subscription_row(tag, source): +def _subscription_state(tag): + """(cache mtime, proxy count), None without a cache. The cache is root's without the + "secrets" scope: then the running proxy's inventory counts them, and the mtime is None.""" cache = _subscription_cache(tag) - if os.path.isfile(cache): - try: - age = datetime.datetime.fromtimestamp(os.path.getmtime(cache)).strftime("%Y-%m-%d %H:%M:%S") - except OSError: - age = "unknown" - count = _subscription_proxy_count_text(cache) + try: + st = os.stat(cache) + except PermissionError: + st = None + except OSError: + return None + if st is not None and not stat.S_ISREG(st.st_mode): + return None + if st is not None and os.access(cache, os.R_OK): + return st.st_mtime, _subscription_proxy_count_text(cache) + count = sum(1 for source in (_outbound_inventory().get("sources") or {}).values() if source == f"sub:{tag}") + return (st and st.st_mtime, str(count)) if st or count else None + + +def _subscription_row(tag, source): + state = _subscription_state(tag) + if state: + mtime, count = state + age = datetime.datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S") if mtime else "unknown" else: age = "(no cache)" count = "-" @@ -2941,7 +3165,7 @@ def cmd_subscription(verb="list", *args): must("start", "proxy-suite-subscription-update") print("Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update") else: - usage("proxy subs [list|update|add [tag] |rm |link ]") + usage("proxy subs [list|update|add [tag] |rm |link ]") RULE_SETS_UNIT = "proxy-suite-rulesets" @@ -3042,8 +3266,13 @@ def _probe_fetch(domain, path, *selector): ua = [] if curl else ["-A", env("PROBE_UA", "Mozilla/5.0 (X11; Linux x86_64) proxy-suite-probe")] result = "" with tempfile.TemporaryDirectory(prefix="proxy-ctl-probe-") as tmp: - # The listener's login through a file in this private directory: argv is public. - login = _local_proxy_login() if "--proxy" in selector else None + # The listener's login through a file in this private directory: argv is public. A + # probe listener's own (_probe_login), or the local proxy's when there are none. + login = None + if "--proxy" in selector: + proxy_url = selector[selector.index("--proxy") + 1] + local = proxy_url == env("LOCAL_PROXY_URL", "http://127.0.0.1:1080") + login = _local_proxy_login() if local else _probe_login() auth = [] if login: curlrc = os.path.join(tmp, "login.curlrc") @@ -3068,6 +3297,10 @@ def _probe_fetch(domain, path, *selector): env("PROBE_MAX_TIME", "15"), "-w", PROBE_WRITE_OUT, + # After the first hop url is the server's Location: no globbing, no file: or other schemes. + "--globoff", + "--proto", + "=http,https", *auth, *selector, url, @@ -3082,11 +3315,31 @@ def _probe_fetch(domain, path, *selector): if not re.fullmatch(r"3..", _probe_field(result, 3)) or _probe_redirect_is_block(result): break url = _probe_field(result, 6) - if not url or _probe_site(url) != site: + if not url or _probe_site(url) != site or _probe_local_target(url): break return result +def _probe_local_target(url): + """Whether a Location names this host or its LAN by literal (no DNS): never followed.""" + try: + host = (urllib.parse.urlsplit(url).hostname or "").rstrip(".") + except ValueError: + return True + if host == "localhost" or host.endswith(".localhost"): + return True + try: + ip = ipaddress.ip_address(host) + except ValueError: + try: + # What curl's resolver also takes as IPv4: 127.1, 0x7f000001, 2130706433. + ip = ipaddress.IPv4Address(socket.inet_aton(host)) + except (OSError, ValueError): + return False + ip = getattr(ip, "ipv4_mapped", None) or ip + return ip.is_loopback or ip.is_link_local or ip.is_private or ip.is_unspecified + + def _probe_block_page(code, head, body): """The PROBE_BLOCK_PAGES name a refusal's page matches; "" for none.""" if not re.fullmatch(r"[45]..", code): @@ -3368,6 +3621,11 @@ def _autoproxy_dir(): return env("AUTOPROXY_STATE_DIR", f"{state_dir()}/autoproxy") +def _autoproxy_spool(): + """Where `proxy auto learn|forget|relearn|clear` queue for the prober: root's state dir is read-only to members.""" + return env("AUTOPROXY_SPOOL_DIR", f"{state_dir()}/autoproxy-requests") + + def _require_autoproxy(): require_enabled("AUTOPROXY_ENABLED", "proxy.autoProxy") @@ -3375,8 +3633,8 @@ def _require_autoproxy(): def _autoproxy_unreadable(path): """The path a refused read stops at, empty when the state is readable or simply not there yet. - The state dir is 0751, opened to 0771 for the autoProxy scope's group, and - state.json inside it stays 0640: a member gets past the directory and a + The state dir is root's, 0751, and group-owned by the autoProxy scope's group, + and state.json inside it stays 0640: a member gets past the directory and a stranger does not, so both are checked. """ if not os.path.isdir(path): @@ -3454,13 +3712,7 @@ def cmd_proxy_queue(top="20", *_): _require_autoproxy_readable(path) print("Requested with proxy-ctl proxy auto learn:") - requested = "" - for name in ("requests", "requests.taking"): - try: - requested += read_text(os.path.join(path, name)) - except OSError: - pass - for line in lines(requested) or ["(none)"]: + for line in [line for line in lines(_autoproxy_queued("requests")) if line] or ["(none)"]: print(f" {line}") backlog = _autoproxy_state(path).get("backlog") or {} @@ -3519,18 +3771,30 @@ def cmd_proxy_learned(*_): def _autoproxy_queue(name, line): - """Appends a line for the prober's own unit, which takes it under the same lock as a timer run.""" - path = os.path.join(_autoproxy_dir(), name) + """Queues a line for the prober's own unit, as a file of its own in the sticky spool, named + to sort by time: no other member can rewrite it, and it lands whole.""" + spool = _autoproxy_spool() try: - # Appended in place, as the prober takes it, but never through a symlink or into a - # FIFO a member left there: proxy-ctl may run as root. - fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o666) - with os.fdopen(fd, "a", encoding="utf-8") as f: - if not stat.S_ISREG(os.fstat(fd).st_mode): - raise OSError(f"{path} is not a regular file") - f.write(f"{line}\n") + _spool_write(os.path.join(spool, f"{name}.{time.time_ns()}.{os.getpid()}"), f"{line}\n") except OSError: - denied(path, "write") + denied(spool, "write to") + + +def _autoproxy_queued(name): + """The lines still queued as `name` in the spool, oldest first; empty where it cannot be read.""" + spool = _autoproxy_spool() + try: + names = sorted(n for n in os.listdir(spool) if n.startswith(f"{name}.")) + except OSError: + return "" + text = "" + for n in names: + try: + # Capped: a request is a line, and a member's file may be anything. + text += read_shared_text(os.path.join(spool, n), 64 * 1024).rstrip("\n") + "\n" + except OSError: + pass + return text def _autoproxy_run(what): @@ -3641,25 +3905,42 @@ def _zapret_auto_file(name): def _replace_lines(path, keep, extra=()): """Rewrites path with the lines keep() accepts, plus extra. - Via a temp file in the same directory, world-readable: unprivileged - proxy-ctl reads these lists too. + Via a temp file in the same directory, with the old file's owner and mode (a new one + world-readable: unprivileged proxy-ctl reads these lists too). Locked against another + proxy-ctl; what nfqws2 appended meanwhile, unlocked, is carried over before the rename. """ - try: - old = lines(read_text(path)) if os.path.exists(path) else [] - fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=os.path.dirname(path) or ".") - except OSError: - denied(path, "write") - try: - with os.fdopen(fd, "w", encoding="utf-8") as f: - f.writelines(f"{line}\n" for line in [*filter(keep, old), *extra]) - os.chmod(tmp, 0o644) - os.replace(tmp, path) - except OSError: + with _file_lock(path): try: - os.unlink(tmp) + old = os.lstat(path) if os.path.lexists(path) else None + text = read_shared_text(path) if old else "" + fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=os.path.dirname(path) or ".") except OSError: - pass - denied(path, "replace") + denied(path, "write") + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.writelines(f"{line}\n" for line in [*filter(keep, lines(text)), *extra]) + # By fd, not path: tmp's name could be swapped for a symlink in between. + os.fchmod(f.fileno(), stat.S_IMODE(old.st_mode) & 0o777 if old else 0o644) + if old and os.geteuid() == 0: + os.fchown(f.fileno(), old.st_uid, old.st_gid) + # Newer than anything this edit means to drop: kept as they came. + f.writelines(f"{line}\n" for line in _appended_since(path, text)) + os.replace(tmp, path) + except OSError: + try: + os.unlink(tmp) + except OSError: + pass + denied(path, "replace") + + +def _appended_since(path, text): + """The lines added to path since it read as text, if it only grew since; else none.""" + try: + now = read_shared_text(path) if os.path.lexists(path) else "" + except OSError: + return [] + return lines(now[len(text) :]) if len(now) > len(text) and now.startswith(text) else [] def _zapret_auto_edit(path, domain, action): @@ -3684,7 +3965,64 @@ def _zapret_strategy_drop(domain): key = fields[1] if len(fields) > 1 else "" return line.startswith("#") or (key != domain and not domain.endswith(f".{key}")) - _replace_lines(path, keep) + with _z2k_state_lock(path): + _replace_lines(path, keep) + + +Z2K_LOCK_STALE = 10 + + +@contextlib.contextmanager +def _z2k_state_lock(path): + """z2k-state-persist.lua's own lock on state.tsv (.lock, made O_EXCL, stale after 10 s): + nfqws2 rewrites the file whole, so an unlocked rename could undo a row it just wrote.""" + lock = f"{path}.lock" + deadline = time.monotonic() + LOCK_WAIT + while True: + try: + fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o644) + break + except FileExistsError: + if _z2k_lock_stale(lock): + with contextlib.suppress(OSError): + os.unlink(lock) + elif time.monotonic() >= deadline: + die(f"zapret2 is still writing {path} (it holds {lock}); try again.") + else: + time.sleep(0.05) + except OSError: + fd = None + break + if fd is None: + yield + return + try: + with os.fdopen(fd, "w", encoding="ascii") as f: + f.write(str(int(time.time()))) + yield + finally: + with contextlib.suppress(OSError): + os.unlink(lock) + + +def _z2k_lock_stale(lock): + now = time.time() + try: + fd = os.open(lock, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) + with os.fdopen(fd, "rb") as f: + made = os.fstat(f.fileno()).st_mtime + content = f.read(32).strip() + except FileNotFoundError: + return False # gone already: the next try takes it + except OSError: + return True # no lock z2k made (a symlink, say) + try: + taken = int(content) + except ValueError: + # Made but not written yet, or its writer died in between: only the latter lasts. + return now - made > 2 + # One from the future: the clock went back since. + return taken > now + Z2K_LOCK_STALE or now - taken > Z2K_LOCK_STALE def _zapret_strategy_rows(): @@ -3836,7 +4174,10 @@ def cmd_zapret_auto(verb="list", domain="", *_): if verb in ("add", "forget", "exclude", "unpin", "include", "retry") and not _zapret_auto_host(domain): usage(f"zapret auto {verb} ") if verb == "list": - hosts = [h for h in lines(read_text(auto)) if h] if os.path.isfile(auto) else [] + try: + hosts = [h for h in lines(read_shared_text(auto)) if h] if os.path.lexists(auto) else [] + except OSError: + denied(auto) if not hosts: print("No hostnames learned yet.") rows, strategies, verdicts = _zapret_strategy_rows(), _zapret_strategy_map(), _zapret_verdicts() @@ -3878,7 +4219,8 @@ def cmd_zapret_auto(verb="list", domain="", *_): _truncate(auto) for path in (_zapret_auto_file("circular/state.tsv"), _zapret_auto_file("verdicts.tsv")): if os.path.exists(path): - _truncate(path) + with _z2k_state_lock(path) if path.endswith("state.tsv") else contextlib.nullcontext(): + _truncate(path) print("Cleared learned hosts, remembered strategies and what zapret2 sent the proxy.") else: usage("zapret auto [list|add|forget|exclude|unpin|include|retry|clear]") @@ -3893,7 +4235,7 @@ def cmd_zapret_auto(verb="list", domain="", *_): def _tsv(path): try: - return [line.split("\t") for line in lines(read_text(path))] + return [line.split("\t") for line in lines(read_shared_text(path))] except OSError: return [] @@ -3962,7 +4304,7 @@ def _where_in_list(path, domain): if not readable(path): return "" try: - return _where_in(set(lines(read_text(path))), domain) + return _where_in(set(lines(read_shared_text(path))), domain) except OSError: return "" @@ -4259,7 +4601,7 @@ def _awg_free_port(): for name in names: if name.endswith(".port"): try: - taken.add(int(read_text(os.path.join(directory, name)).split()[0])) + taken.add(int(read_shared_text(os.path.join(directory, name), 64).split()[0])) except (OSError, ValueError, IndexError): pass port = next((p for p in _awg_tunnel_ports() if p not in taken), None) @@ -4283,7 +4625,7 @@ def _awg_free_iface_slot(): for name in names: if name.endswith(".iface"): try: - taken.add(int(read_text(os.path.join(directory, name)).split()[0])) + taken.add(int(read_shared_text(os.path.join(directory, name), 64).split()[0])) except (OSError, ValueError, IndexError): pass slot = next((n for n in _awg_iface_slots() if n not in taken), None) @@ -4307,20 +4649,22 @@ def _awg_outbound_add(tag, text, detour, container, kind=""): directory = _runtime_dir("outbound") if not os.access(directory, os.W_OK | os.X_OK): denied(directory, "write to") - # 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: - 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) + with _runtime_lock("outbound"): + _check_runtime_unused("outbound", tag) + # 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: + 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) _runtime_reload() _runtime_entry_verify("outbound", tag) @@ -4381,8 +4725,7 @@ def _awg_rm(name="", *_): if svc_active(unit) or svc_state(unit) == "failed": must("stop", unit) # As `awg off`: the kill switch would otherwise hold with no tunnel to guard. - if svc_exists(KILL_SWITCH): - systemctl("stop", KILL_SWITCH) + _lift_kill_switch() try: os.unlink(os.path.join(directory, f"{name}.conf")) except FileNotFoundError: @@ -4432,8 +4775,8 @@ def cmd_awg(verb="list", *args): for profile in targets: must("stop" if verb == "off" else "restart", _awg_service(profile)) # Also after a profile that already failed: off is how its kill switch is lifted. - if verb == "off" and svc_exists(KILL_SWITCH): - systemctl("stop", KILL_SWITCH) + if verb == "off": + _lift_kill_switch() else: usage("awg [list] | on | off [profile] | toggle [profile] | restart [profile] | add [name] | rm ") @@ -4458,10 +4801,10 @@ def _wl_link(name): """The call a creator made and keeps rejoining: the last line it wrote.""" path = _wl_path(name, ".link") try: - links = [line.strip() for line in lines(read_text(path)) if line.strip()] + links = [line.strip() for line in lines(read_shared_text(path)) if line.strip()] except FileNotFoundError: links = [] - except PermissionError: + except OSError: denied(path) if not links: die(f"{name} has no call yet: {journal_hint(_wl_unit({'role': 'creator', 'name': name}))}") @@ -4513,8 +4856,9 @@ def _wl_write(w, suffix, text): fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=os.path.dirname(path)) with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(text) - os.chown(tmp, st.st_uid if os.geteuid() == 0 else -1, st.st_gid) - os.chmod(tmp, 0o600 | (st.st_mode & 0o060)) + # By fd: the group may write here, so tmp's name could become a symlink first. + os.fchown(f.fileno(), st.st_uid if os.geteuid() == 0 else -1, st.st_gid) + os.fchmod(f.fileno(), 0o600 | (st.st_mode & 0o060)) os.replace(tmp, path) except OSError: if tmp: @@ -4595,6 +4939,16 @@ SLICE_ROUTES = { APP_NAME = re.compile(r"[a-z0-9][a-z0-9-]*") APP_ROUTES = ("direct", "proxychains", "tun", "tproxy", "zapret") +RUNTIME_APP_MAX_BYTES = 64 * 1024 + + +def _read_shared_json(path): + """The JSON object at path (read_shared_text), {} for anything else.""" + try: + value = json.loads(read_shared_text(path, RUNTIME_APP_MAX_BYTES)) + except (OSError, ValueError): + return {} + return value if isinstance(value, dict) else {} def _runtime_apps(): @@ -4607,7 +4961,7 @@ def _runtime_apps(): apps = [] for file in names: name = file.removesuffix(".json") - entry = read_json_or(os.path.join(directory, file), {}) if file.endswith(".json") else {} + entry = _read_shared_json(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 @@ -4683,77 +5037,93 @@ def _ensure_app_routing(): require_enabled("PER_APP_ROUTING_ENABLED", "perAppRouting") -def _active_global_proxy(): - """The global TUN or TProxy unit that is up, which the per-app backends would clash with.""" - return next((svc for svc in ("proxy-suite-tun", "proxy-suite-tproxy") if svc_active(f"{svc}.service")), "") +def _active_global_proxy(route=""): + """The global unit up that carries the app's traffic already (TUN, TProxy; for zapret an + AmneziaWG profile too): the per-app units refuse to start under it.""" + units = ["proxy-suite-tun", "proxy-suite-tproxy"] + if route == "zapret": + units += [_awg_service(profile) for profile in _awg_profiles()] + return next((svc for svc in units if svc_active(f"{svc}.service")), "") def _has_units(*args): return bool(re.search(".", systemctl(*args, capture=True)[1])) -def _units_active(*globs): - return _has_units("list-units", "--type=service", "--state=active", "--plain", "--no-legend", *globs) +def _slice_lock(slice_base): + """This user's shared lock on the slice, from before its units start until the app exits: + a run ending must not stop the marking under one whose scope is not registered yet. None if unavailable.""" + directory = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" + try: + fd = os.open( + os.path.join(directory, f"proxy-suite-{slice_base}.lock"), + os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + ) + except OSError: + return None + try: + fcntl.flock(fd, fcntl.LOCK_SH) + except OSError: + os.close(fd) + return None + return fd -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.""" +def _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, lock=None): + """Stops this user's marking once none of their apps runs in the slice (the shared backend + stops by itself). Only the last holder of _slice_lock's lock may stop anything.""" + if lock is not None: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + os.close(lock) + return + try: + _stop_slice_if_idle(slice_base, anchor_unit, user_svc) + finally: + if lock is not None: + os.close(lock) + + +def _stop_slice_if_idle(slice_base, anchor_unit, user_svc): + # Still the backstop for runs that were killed and never let go of the lock. 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) - 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"): - """The resolvers /etc/resolv.conf names, if every one of them is a local stub.""" - try: - found = [ - line.split()[1] - for line in lines(read_text(path)) - if line.split()[:1] == ["nameserver"] and len(line.split()) > 1 - ] - except OSError: - return [] - stub = [x for x in found if x.startswith("127.") or x in ("::1", "localhost")] - return stub if found and len(stub) == len(found) else [] +def _warn_nscd(route): + """nscd (NixOS's default) resolves from its own cgroup, outside the wrapped app's route; a + resolver the app asks itself goes through the route's DNS forwarder.""" + if os.path.exists(env("NSCD_SOCKET", "/run/nscd/socket")): + print( + "warning: nscd answers this host's lookups from outside the wrapped app's cgroup, so " + f"names resolve outside route={route}. Apps that ask a resolver themselves (Go " + "programs, a browser's own resolver or DNS-over-HTTPS) resolve through the route.", + file=sys.stderr, + ) -def _warn_stub_resolver(route): - """A wrapped app asking a local stub resolver leaks its names: the stub answers from - its own process, which is outside the app's cgroup and so outside the app's route.""" - stub = _stub_resolver_nameservers() - if not stub: - return - print( - f"warning: {stub[0]} is this host's only resolver, and it answers from outside the " - f"wrapped app's cgroup, so names resolve outside route={route}. Point the app at a " - "resolver of its own to keep its DNS in the tunnel.", - file=sys.stderr, - ) - - -def _wrap_slice(slice_base, profile, backend_svc, cmd, units=None, busy=(), then=None, before=()): +def _wrap_slice(slice_base, profile, cmd, units=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. + units: (anchor, this user's marking unit) when they are not named after the slice. + before: units to have up first, in order, that the marking unit does not bring up. """ uid = os.getuid() scope_unit = f"{slice_base}-{profile}-{os.getpid()}" - anchor_unit, user_svc, users_glob = units or (f"{slice_base}-anchor.service", f"{slice_base}-user@{uid}.service", "") + anchor_unit, user_svc = 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)) + lock = _slice_lock(slice_base) 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] + # A slice route's marking brings its backend up (Requires=): started alone first, + # the backend would go again at once, needed by nothing (StopWhenUnneeded=). status = status or systemctl("start", user_svc)[0] if not status: status = _run_foreground( @@ -4770,7 +5140,7 @@ def _wrap_slice(slice_base, profile, backend_svc, cmd, units=None, busy=(), then ] ) finally: - _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, backend_svc, users_glob, busy, then) + _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, lock) sys.exit(status) @@ -4802,12 +5172,6 @@ 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 @@ -4831,14 +5195,13 @@ def _run_via(tag, label, cmd, route=""): 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 + unit, global_units = f"proxy-suite-per-app-via@{key}.service", ("proxy-suite-tun",) 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), "") @@ -4856,26 +5219,24 @@ def _run_via(tag, label, cmd, route=""): 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) + print(f"warning: {active}.service is active and carries the app already; running it without --via {tag}.", file=sys.stderr) _exec(list(cmd)) uid = os.getuid() + # The via unit, which the marking unit cannot name; it goes after the last user's + # marking (per-app-routing/via.nix), with the profile brought up for it. _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, + before=(*before, unit), ) @@ -4945,16 +5306,16 @@ def cmd_apps_run(*args): slice_base, enabled, option = SLICE_ROUTES[route] # The global mode already carries the app's traffic, and wrapPerApp launchers must # still start the app: run it as it is rather than refuse. - global_svc = _active_global_proxy() + global_svc = _active_global_proxy(route) if global_svc: - print(f"note: {global_svc}.service is active; running without route={route}.", file=sys.stderr) + print(f"warning: {global_svc}.service is active and carries the app already; running it without route={route}.", file=sys.stderr) _exec(list(cmd)) if env(enabled) != "1": die(f"Profile '{profile}' uses route={route}, but {option} is false.") - _warn_stub_resolver(route) - # 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) + # zapret's route sends the app direct anyway: its lookups go the same way. + if route != "zapret": + _warn_nscd(route) + _wrap_slice(slice_base, profile, list(cmd)) else: die(f"Route backend '{route}' is not implemented.") @@ -5083,41 +5444,64 @@ def _inbound_stats(*args): AWG_ONLINE_SECONDS = 180 +# How old the collector's reading of who is online may be: two of its timer's runs. +ONLINE_READING_SECONDS = 600 def _inbound_presence(): """(user -> (state, addresses), links readable): "online", "seen