From 3b568bb54e505c6aece499711fe4a0c5907535cb Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Thu, 17 Sep 2026 13:27:08 +0500 Subject: [PATCH] feat: allow using suite on non-nixos systems --- README.md | 56 +- docs/options/amneziaWg.md | 22 +- docs/options/index.md | 1 + docs/options/warp.md | 4 +- flake.nix | 18 +- modules/proxy-suite/amnezia-wg.nix | 48 +- modules/proxy-suite/autoproxy-render.nix | 8 +- modules/proxy-suite/autoproxy.nix | 20 +- .../proxy-suite/config-templates/sing-box.nix | 6 +- modules/proxy-suite/config-templates/xray.nix | 5 +- modules/proxy-suite/core.nix | 173 +++ modules/proxy-suite/default.nix | 203 +-- modules/proxy-suite/derived.nix | 55 +- modules/proxy-suite/hosts/common.nix | 30 + modules/proxy-suite/hosts/home-manager.nix | 64 + modules/proxy-suite/hosts/nix-on-droid.nix | 123 ++ modules/proxy-suite/hosts/nixos.nix | 75 + modules/proxy-suite/hosts/system-manager.nix | 118 ++ modules/proxy-suite/hosts/user-units.nix | 217 +++ modules/proxy-suite/options/amnezia-wg.nix | 12 +- modules/proxy-suite/options/default.nix | 1 + modules/proxy-suite/options/host.nix | 74 + modules/proxy-suite/options/proxy.nix | 2 +- .../proxy-suite/options/types/amnezia-wg.nix | 6 + modules/proxy-suite/options/types/unit.nix | 84 ++ modules/proxy-suite/options/warp.nix | 3 + modules/proxy-suite/service-assertions.nix | 68 +- .../proxy-suite/service/control-scripts.nix | 2 +- modules/proxy-suite/service/control.nix | 3 + modules/proxy-suite/service/default.nix | 190 ++- .../proxy-suite/service/per-app-routing.nix | 1 + .../service/per-app-routing/profiles.nix | 3 +- .../service/proxy-inbounds-scripts.nix | 13 +- .../script-blocks/hybrid-runtime-helpers.nix | 4 +- .../service/script-blocks/outbounds.nix | 8 +- .../service/script-blocks/subscriptions.nix | 3 +- modules/proxy-suite/service/scripts.nix | 10 +- modules/proxy-suite/service/start-scripts.nix | 19 +- modules/proxy-suite/ssh-proxy.nix | 2 +- modules/proxy-suite/tg-ws-proxy.nix | 2 +- modules/proxy-suite/warp.nix | 14 +- modules/proxy-suite/wg-tunnel.nix | 127 +- modules/proxy-suite/zapret.nix | 72 +- modules/proxy-suite/zapret2.nix | 92 +- nix/checks.nix | 10 + nix/checks/hosts.nix | 224 +++ nix/checks/repo.nix | 8 + nix/checks/route-mode.nix | 1 + pkgs/amneziawg.nix | 1 + pkgs/default.nix | 6 + pkgs/patches/wireproxy-awg-fwmark.patch | 40 + pkgs/proxy-ctl.nix | 13 + pkgs/proxy-ctl/proxy_ctl.py | 79 +- pkgs/proxy-ctl/proxy_gui.py | 1 + pkgs/proxy-ctl/proxy_model.py | 7 +- pkgs/proxy-ctl/proxy_supervisor.py | 1264 +++++++++++++++++ pkgs/proxy-ctl/proxy_tui.py | 2 +- pkgs/proxy-ctl/test_proxy_ctl.py | 46 + pkgs/proxy-ctl/test_proxy_supervisor.py | 172 +++ pkgs/proxy-suite-supervisor.nix | 38 + pkgs/wireproxy-awg.nix | 41 + scripts/amneziawg_config.py | 59 +- scripts/test-amneziawg-config.py | 22 + 63 files changed, 3572 insertions(+), 523 deletions(-) create mode 100644 modules/proxy-suite/core.nix create mode 100644 modules/proxy-suite/hosts/common.nix create mode 100644 modules/proxy-suite/hosts/home-manager.nix create mode 100644 modules/proxy-suite/hosts/nix-on-droid.nix create mode 100644 modules/proxy-suite/hosts/nixos.nix create mode 100644 modules/proxy-suite/hosts/system-manager.nix create mode 100644 modules/proxy-suite/hosts/user-units.nix create mode 100644 modules/proxy-suite/options/host.nix create mode 100644 modules/proxy-suite/options/types/unit.nix create mode 100644 nix/checks/hosts.nix create mode 100644 pkgs/patches/wireproxy-awg-fwmark.patch create mode 100644 pkgs/proxy-ctl/proxy_supervisor.py create mode 100644 pkgs/proxy-ctl/test_proxy_supervisor.py create mode 100644 pkgs/proxy-suite-supervisor.nix create mode 100644 pkgs/wireproxy-awg.nix diff --git a/README.md b/README.md index fd1f34f..24466e1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # proxy-suite-flake -Declarative proxy stack for NixOS, on either side of the connection: as a client that routes this host's traffic through outbounds, as a server that accepts clients on its own inbounds, or both at once. Configure it in Nix, rebuild, and it runs as systemd services. +Declarative proxy stack for NixOS, on either side of the connection: as a client that routes this host's traffic through outbounds, as a server that accepts clients on its own inbounds, or both at once. Configure it in Nix, rebuild, and it runs as systemd services. It also runs on other Linux distributions (through system-manager or home-manager) and on Android (through Nix-on-Droid): see [Other hosts](#other-hosts). > [!IMPORTANT] > This project is for study and research purposes only: learning how proxies, tunnels and traffic routing work. It comes with no warranty, and the authors are not responsible for how it is used. @@ -85,7 +85,7 @@ services.proxy-suite = { profiles.work.vpnFile = "/run/secrets/work-amnezia.vpn"; # An outbound tagged "de" instead: the proxy binds to its interface, which gets no routes. profiles.de = { - asOutbound = "interface"; # or "singBox": plain WireGuard inside sing-box + asOutbound = "interface"; # or "userspace" (no root), or "singBox" (plain WireGuard) configFile = "/run/secrets/de-amneziawg.conf"; }; }; @@ -106,6 +106,58 @@ services.proxy-suite = { }; ``` +### Other hosts + +The same options work outside NixOS. Pick the module for the host; everything the host cannot do fails evaluation with a message naming the option. + +| | NixOS | system-manager | home-manager | Nix-on-Droid | +|---|:-:|:-:|:-:|:-:| +| Runs as | root, systemd | root, systemd | user, `systemd --user` | user, `proxy-suitectl` | +| Local SOCKS/HTTP proxy, subscriptions, selection, route modes | ✓ | ✓ | ✓ | ✓ | +| Per-app proxychains | ✓ | ✓ | ✓ | ✓ | +| Server inbounds, share links, stats | ✓ | ✓ | ports ≥ 1024 | ports ≥ 1024 | +| tg-ws-proxy, SSH proxy, WARP as a sing-box outbound | ✓ | ✓ | ✓ | ✓ | +| AmneziaWG `asOutbound = "userspace"` | ✓ | ✓ | ✓ | ✓ | +| Global TUN/TProxy, per-app TUN/TProxy/zapret, zapret, AmneziaWG interfaces | ✓ | ✓ | ✗ | ✗ | +| `userControl`, polkit | ✓ | ✓ | not needed | not needed | +| GUI | ✓ | ✓ | ✓ | ✗ (`proxy-ctl`, `proxy-tui`) | + +Rootless hosts get the local proxy only: nothing captures the rest of the host's traffic, so point applications at `127.0.0.1:1080` (or run them through `proxy-ctl apps run`). + +#### system-manager (other distributions, as root) + +```nix +# with github:numtide/system-manager +modules = [ inputs.proxy-suite.systemManagerModules.default ]; +``` + +- Units, service users and the polkit rules (`/etc/polkit-1/rules.d/50-proxy-suite.rules`) are installed like on NixOS; the GUI's user unit goes to `/etc/systemd/user`. The service users come from `users.users`, so system-manager needs its user management. +- The host's firewall is left alone: open the inbound ports yourself. TUN, TProxy and zapret load their own nftables tables, which needs `nf_tables`, `nfnetlink_queue` and `tun` in the host kernel. +- AmneziaWG runs on its userspace implementation (`amneziaWg.kernelModulePackage` must stay `null`). DNS pushed by a VPN profile goes through `resolvectl` under systemd-resolved, `openresolv` otherwise. + +#### home-manager (any Linux, no root) + +```nix +# homeConfigurations. = home-manager.lib.homeManagerConfiguration { ... } +modules = [ inputs.proxy-suite.homeManagerModules.default ]; +``` + +- Units run in the user's systemd manager: `systemctl --user status proxy-suite-socks`. They stop at logout unless lingering is on: `loginctl enable-linger $USER`. +- State lives in `$XDG_STATE_HOME/proxy-suite`, runtime files in `$XDG_CACHE_HOME/proxy-suite/run`. + +#### Nix-on-Droid (Android, no root) + +```nix +# nixOnDroidConfigurations.default = nix-on-droid.lib.nixOnDroidConfiguration { ... } +modules = [ inputs.proxy-suite.nixOnDroidModules.default ]; +``` + +- Android has no systemd, so `nix-on-droid switch` hands the units to `proxy-suitectl`, a small supervisor that understands the parts of systemd units proxy-suite uses (restarts, dependencies, timers, path watches). `proxy-ctl` talks to it for you; directly, `proxy-suitectl status`, `proxy-suitectl restart proxy-suite-socks` and `proxy-suitectl journal -u 'proxy-suite-*' -f` work much like `systemctl` and `journalctl`. +- Android gives the app no boot hook. The services start on `nix-on-droid switch`, and, with `services.proxy-suite.nixOnDroid.startWithSession` (on by default), whenever a Nix-on-Droid shell opens; `proxy-suitectl boot` starts them by hand. +- Android stops background apps: acquire Nix-on-Droid's wake lock from its notification and exempt the app from battery optimisation, or the services die with the terminal. +- Inbounds are reachable from the local network on ports from 1024 up; zapret is not available (on Android it needs a VPN app). +- An AmneziaWG `userspace` outbound resolves an `Endpoint` hostname through the system resolver; give it as an IP address where that resolver is itself blocked. + --- ## Options diff --git a/docs/options/amneziaWg.md b/docs/options/amneziaWg.md index 30d29e2..abe8319 100644 --- a/docs/options/amneziaWg.md +++ b/docs/options/amneziaWg.md @@ -64,6 +64,7 @@ Part of the [proxy-suite options reference](./index.md). - [vpnFile](#services-proxy-suite-amneziawg-profiles-name-vpnfile) - [toolsPackage](#services-proxy-suite-amneziawg-toolspackage) - [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage) + - [wireproxyPackage](#services-proxy-suite-amneziawg-wireproxypackage) ## services\.proxy-suite\.amneziaWg\.enable @@ -141,13 +142,18 @@ always runs, leaves the host’s routes and resolver alone, and is not listed by - “singBox”: a WireGuard endpoint in its own sing-box process, reached as a loopback SOCKS hop\. sing-box speaks plain WireGuard: AmneziaWG obfuscation is dropped with a warning\. + - “userspace”: the same hop served by wireproxy on AmneziaWG’s userspace implementation, so + obfuscation works\. It needs no interface or root: the only AmneziaWG mode on + home-manager and nix-on-droid\. A declared or profile ListenPort is used as is\. An + Endpoint hostname resolves through the system resolver: give an address where that + resolver cannot reach the name\. - “interface”: the AmneziaWG interface comes up without routes (Table = off), and the outbound binds to it, so obfuscation works\. With the sing-box backend its DNS goes through the interface too (proxy\.dns\.remote); XRay resolves as usual\. Either way the tunnel itself reaches the peer over the uplink, past TUN and TProxy\. *Type:* -null or one of “singBox”, “interface” +null or one of “singBox”, “userspace”, “interface” *Default:* @@ -912,3 +918,17 @@ package ```nix ``` + + +## services\.proxy-suite\.amneziaWg\.wireproxyPackage + +wireproxy build with AWG 3\.1 and FwMark, which runs profiles with asOutbound = “userspace”\. + +*Type:* +package + +*Default:* + +```nix + +``` diff --git a/docs/options/index.md b/docs/options/index.md index b3ca583..7cd1d49 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -29,6 +29,7 @@ services.proxy-suite = { profiles = { }; toolsPackage = pkgs.amneziawg-tools; userspacePackage = pkgs.amneziawg-go; + wireproxyPackage = pkgs.wireproxy-awg; }; enable = false; geodata = { diff --git a/docs/options/warp.md b/docs/options/warp.md index f131666..5be6bc9 100644 --- a/docs/options/warp.md +++ b/docs/options/warp.md @@ -55,11 +55,13 @@ Add WARP as an outbound tagged “warp”\. endpoint on 127\.0\.0\.1:18538, as the proxy-suite-daemon user\. The tunnel starts again on a new source port when WARP does not answer within 15 seconds of a start, or misses three probes later on, unless the uplink itself is down\. + - “userspace”: an AmneziaWG profile named “warp” with asOutbound = “userspace”, which honours + the AmneziaWG lines of the profile without an interface or root\. Requires amneziaWg\.enable\. - “interface”: an AmneziaWG profile named “warp” with asOutbound = “interface”, which honours the AmneziaWG lines of the profile\. Requires amneziaWg\.enable\. *Type:* -null or one of “singBox”, “interface” +null or one of “singBox”, “userspace”, “interface” *Default:* diff --git a/flake.nix b/flake.nix index 13d60c5..23792cd 100644 --- a/flake.nix +++ b/flake.nix @@ -32,7 +32,7 @@ ]; forAll = nixpkgs.lib.genAttrs systems; pkgsFor = system: import nixpkgs { inherit system; }; - proxySuiteModule = import ./modules/proxy-suite { + proxySuiteModules = import ./modules/proxy-suite { inherit zapret nixpkgs @@ -40,6 +40,7 @@ z2k ; }; + proxySuiteModule = proxySuiteModules.nixos; mkOptionsDoc = import ./nix/options-doc.nix { inherit nixpkgs pkgsFor proxySuiteModule; }; @@ -59,6 +60,18 @@ # A single-user VPS: VLESS REALITY, TLS and WS inbounds, ACME and SSH. Includes default. nixosModules.server = import ./deploy/server-module.nix { inherit proxySuiteModule; }; + # Rootless, in the user's systemd manager: the local proxy, inbounds on ports from 1024 + # up, and what else needs no root. + homeManagerModules.default = proxySuiteModules.homeManager; + + # For numtide/system-manager on other distributions: everything NixOS has, with the + # firewall and kernel modules left to the host. + systemManagerModules.default = proxySuiteModules.systemManager; + + # nix-on-droid, where proxy-suitectl supervises the services: what home-manager gets, + # without the GUI. + nixOnDroidModules.default = proxySuiteModules.nixOnDroid; + # Re-export zapret standalone for users who want just that. nixosModules.zapret = zapret.nixosModules.default; @@ -72,6 +85,7 @@ mkProxyCtl mkTgWsProxy tg-ws-proxy + wireproxy-awg zapret2 ; # Replaced by Proxy Suite GUI, which mkProxyCtl builds as `.gui`. @@ -119,6 +133,7 @@ amneziawg-tools amneziawg-go tg-ws-proxy + wireproxy-awg zapret2 ; xray = import ./pkgs/xray.nix { inherit pkgs; }; @@ -166,6 +181,7 @@ system nixpkgs proxySuiteModule + proxySuiteModules zapret ; generatedOptionsDoc = mkOptionsDoc system; diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index 4f49b1c..d1f6069 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -1,6 +1,5 @@ # Native AmneziaWG client profile services. { - config, lib, pkgs, cfg, @@ -12,7 +11,15 @@ let profiles = awgCfg.profiles; profileNames = builtins.attrNames profiles; globalProfileNames = builtins.attrNames derived.awgGlobalProfiles; - singBoxOutbounds = builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds; + # Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick. + tunnelOutbounds = derived.awgTunnelOutbounds; + interfaceProfiles = lib.filterAttrs ( + _: profile: + !builtins.elem profile.asOutbound [ + "singBox" + "userspace" + ] + ) profiles; serviceName = name: "proxy-suite-awg-${name}"; globalServiceNames = map serviceName globalProfileNames; allProfileConflicts = @@ -172,7 +179,7 @@ let | ${pkgs.gnugrep}/bin/grep -F " wg-quick-${profile.interfaceName}" \ | while read -r _ family table; do nft delete table "$family" "$table" 2>/dev/null || true; done fi - ${config.networking.resolvconf.package}/bin/resolvconf -d "${profile.interfaceName}" -f 2>/dev/null || true + ${cfg.host.resolvconfPackage}/bin/resolvconf -d "${profile.interfaceName}" -f 2>/dev/null || true ${pkgs.iproute2}/bin/ip link delete dev ${lib.escapeShellArg profile.interfaceName} 2>/dev/null || true } trap cleanup ERR @@ -255,8 +262,8 @@ let pkgs.iproute2 pkgs.iputils pkgs.kmod - config.networking.firewall.package - config.networking.resolvconf.package + cfg.host.firewallPackage + cfg.host.resolvconfPackage ]; serviceConfig = { Type = "oneshot"; @@ -286,7 +293,7 @@ let }; }; - mkSingBoxService = + mkTunnelService = ob: let profile = profiles.${ob.name}; @@ -294,8 +301,16 @@ let mkTunnel { description = "proxy-suite AmneziaWG tunnel behind the ${ob.name} outbound"; unit = serviceName ob.name; + engine = ob.kind; inherit (ob) tag tunnelPort directPort; profile = '' + ${lib.optionalString (profile.configFile != null) '' + # It may not exist yet: WARP's appears once proxy-suite-warp has registered. + if [ ! -s ${lib.escapeShellArg profile.configFile} ]; then + echo "proxy-suite: waiting for the AmneziaWG profile at ${profile.configFile}" >&2 + until [ -s ${lib.escapeShellArg profile.configFile} ]; do sleep 5; done + fi + ''} profile="$RUNTIME_DIRECTORY/profile.conf" ${prepareCommand profile ''"$profile"''} ''; @@ -424,28 +439,29 @@ let globalAutostartCount = builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0); in { - environment.systemPackages = [ + services.proxy-suite.internal.packages = [ awgCfg.toolsPackage awgCfg.userspacePackage - ]; + ] + ++ lib.optional (builtins.any (ob: ob.kind == "userspace") tunnelOutbounds) awgCfg.wireproxyPackage; - boot.extraModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [ + services.proxy-suite.internal.kernelModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [ awgCfg.kernelModulePackage ]; # Replies to the proxy's sockets come in on an interface the host has no route through. - networking.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: '' + services.proxy-suite.internal.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: '' iifname "${ob.interface}" accept '') derived.awgInterfaceOutbounds; - systemd.services = lib.mkMerge [ - (lib.mapAttrs' (name: profile: lib.nameValuePair (serviceName name) (mkService name profile)) ( - lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles - )) + services.proxy-suite.internal.services = lib.mkMerge [ + (lib.mapAttrs' ( + name: profile: lib.nameValuePair (serviceName name) (mkService name profile) + ) interfaceProfiles) (lib.mapAttrs' ( name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile) - ) (lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles)) - (lib.listToAttrs (map (ob: lib.nameValuePair (serviceName ob.name) (mkSingBoxService ob)) singBoxOutbounds)) + ) interfaceProfiles) + (lib.listToAttrs (map (ob: lib.nameValuePair (serviceName ob.name) (mkTunnelService ob)) tunnelOutbounds)) (lib.mkIf cfg.proxy.tun.enable { proxy-suite-tun.conflicts = map (name: "${name}.service") globalServiceNames; }) diff --git a/modules/proxy-suite/autoproxy-render.nix b/modules/proxy-suite/autoproxy-render.nix index 753fc50..265cbce 100644 --- a/modules/proxy-suite/autoproxy-render.nix +++ b/modules/proxy-suite/autoproxy-render.nix @@ -4,7 +4,11 @@ # because sing-box refuses to start when a local rule-set path is missing, so # every file it will be told about must exist first; the prober needs it to # publish what it learns, which sing-box then picks up without a restart. -{ pkgs, serviceUser }: +{ + pkgs, + serviceUser, + ifPrivileged, +}: pkgs.writeShellScript "proxy-suite-autoproxy" '' set -euo pipefail @@ -21,7 +25,7 @@ pkgs.writeShellScript "proxy-suite-autoproxy" '' # files: that takes read on it, not just the search the state dir grants. # Asserted on every render, since StateDirectory= re-owns the tree when the # units' Group= changes. - install -d -m 0750 -g ${serviceUser} "$(dirname "$path")" + install -d -m 0750 ${ifPrivileged "-g ${serviceUser} "}"$(dirname "$path")" # Written aside and renamed into place: sing-box reloads on rename (as well # as on in-place writes), and it never reads a half-written file. jq -c --arg t "$tag" ' diff --git a/modules/proxy-suite/autoproxy.nix b/modules/proxy-suite/autoproxy.nix index 55bcf0a..5522eb0 100644 --- a/modules/proxy-suite/autoproxy.nix +++ b/modules/proxy-suite/autoproxy.nix @@ -7,6 +7,8 @@ cfg, proxyCtl, autoProxyStateDir, + runtimeDir, + journalctl, userControlAllows, }: @@ -16,7 +18,7 @@ let stateDirMode = if userControlAllows "autoProxy" then "0771" else "0751"; render = import ./autoproxy-render.nix { inherit pkgs; - inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser; + inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser ifPrivileged; }; jqFile = path: @@ -52,7 +54,7 @@ let set -euo pipefail export PATH=${bin} state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}} - index=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json} + index=''${PROBE_EXITS_FILE:-${runtimeDir}/proxy-suite-socks/probe-exits.json} ${clashApiBlock} if [ -z "$clash_api" ]; then echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample" @@ -81,7 +83,7 @@ let # Overridable to rehearse a run against a scratch copy; the units never set them. state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}} - export PROBE_EXITS_FILE=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json} + 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" @@ -273,7 +275,7 @@ let last=$(jq -r '.lastRun // 0' "$state") if [ "$last" -gt 0 ]; then since="@$last"; else since="-${apCfg.interval}"; fi dialled=$( - journalctl -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null | + ${journalctl} -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null | sed -n 's/.* accepted tcp:\([a-zA-Z0-9._-]*\):[0-9]*.*/\1/p' | grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' | ${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |"} @@ -442,13 +444,13 @@ let }; in { - systemd.services.proxy-suite-autoproxy = + services.proxy-suite.internal.services.proxy-suite-autoproxy = mkUnit "proxy-suite - find the exit that reaches each destination, and remember it" ""; - systemd.services.proxy-suite-autoproxy-learn = + services.proxy-suite.internal.services.proxy-suite-autoproxy-learn = mkUnit "proxy-suite - probe the destinations asked for with proxy-ctl proxy auto learn" " --requests-only"; - systemd.services.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) { + services.proxy-suite.internal.services.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) { description = "proxy-suite - watch live transfers for destinations that crawl directly"; after = [ "proxy-suite-socks.service" ]; serviceConfig = { @@ -458,7 +460,7 @@ in // stateDirConfig; }; - systemd.timers.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) { + services.proxy-suite.internal.timers.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) { description = "proxy-suite autoProxy transfer sampling"; wantedBy = [ "timers.target" ]; timerConfig = { @@ -468,7 +470,7 @@ in }; }; - systemd.timers.proxy-suite-autoproxy = { + services.proxy-suite.internal.timers.proxy-suite-autoproxy = { description = "proxy-suite autoProxy probe schedule"; wantedBy = [ "timers.target" ]; timerConfig = { diff --git a/modules/proxy-suite/config-templates/sing-box.nix b/modules/proxy-suite/config-templates/sing-box.nix index ab36cd8..44428b2 100644 --- a/modules/proxy-suite/config-templates/sing-box.nix +++ b/modules/proxy-suite/config-templates/sing-box.nix @@ -212,10 +212,12 @@ let }); in { + # The local proxy, ready for TProxy. A rootless host can neither take transparent + # connections nor mark sockets: there it is the SOCKS/HTTP listener alone. tproxy = mkConfig { enableMixed = true; - enableTProxy = true; - useOutboundRoutingMark = true; + enableTProxy = constants.privileged; + useOutboundRoutingMark = constants.privileged; xrayDnsBridgePort = xrayDnsBridgePorts.socks; }; diff --git a/modules/proxy-suite/config-templates/xray.nix b/modules/proxy-suite/config-templates/xray.nix index 2782bb7..ff1dc85 100644 --- a/modules/proxy-suite/config-templates/xray.nix +++ b/modules/proxy-suite/config-templates/xray.nix @@ -264,10 +264,11 @@ in # shape out of the same backend primitives. inherit mkDnsServer; + # As sing-box's: without TProxy and marks on a rootless host. tproxy = mkConfig { enableMixed = true; - enableTProxy = true; - useOutboundRoutingMark = true; + enableTProxy = constants.privileged; + useOutboundRoutingMark = constants.privileged; }; tun = mkConfig { diff --git a/modules/proxy-suite/core.nix b/modules/proxy-suite/core.nix new file mode 100644 index 0000000..d9542fc --- /dev/null +++ b/modules/proxy-suite/core.nix @@ -0,0 +1,173 @@ +# The host-neutral part of proxy-suite: options, generated configs and scripts, and +# the services to run, declared under services.proxy-suite.internal for a host adapter +# (./hosts) to install. +{ + zapret, + nixpkgs, + nfqws2-keenetic, + z2k, +}: + +{ + config, + lib, + pkgs, + ... +}: + +let + cfg = config.services.proxy-suite; + packages = import ../../pkgs/default.nix { inherit pkgs; }; + nftr = import ./nftables.nix { inherit lib pkgs cfg; }; + derived = import ./derived.nix { inherit lib cfg; }; +in +{ + imports = [ + ./options + ]; + + config = lib.mkMerge [ + { + # xray and sing-box default to this flake's own nixpkgs (redirect it + # with inputs.nixpkgs.follows), not the system's: a stable release lags + # both by months, and current xray needs a newer Go than stable ships. + _module.args.proxySuiteUpstream = + let + upstream = nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system}; + in + { + xray = import ../../pkgs/xray.nix { pkgs = upstream; }; + # AWG 3.1 userspace; its kernel module has to match the system's kernel instead. + amneziaWg = import ../../pkgs/amneziawg.nix { pkgs = upstream; }; + inherit (upstream) sing-box; + }; + } + + (lib.mkIf cfg.enable ( + let + rules = import ./rules.nix { + inherit + lib + pkgs + cfg + zapret + ; + }; + configs = import ./config.nix { + inherit + lib + pkgs + cfg + rules + ; + }; + in + lib.mkMerge [ + (import ./service { + inherit + lib + pkgs + packages + cfg + ; + inherit (configs) + tproxyFile + tunFile + perAppTunFile + routeModeRulesFile + proxyInboundsFile + proxyInboundsSpecFile + ; + inherit (nftr) + nftablesRulesFile + perAppTproxyRulesFile + perAppZapretRulesFile + perAppTunChainFile + ip + nft + ; + }) + + (lib.mkIf + ( + cfg.zapret.engine == "zapret-discord-youtube" + && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable) + ) + ( + import ./zapret.nix { + inherit + lib + pkgs + cfg + zapret + ; + inherit (nftr) perAppZapretRulesFile nft; + } + ) + ) + + (lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) + ( + import ./zapret2.nix { + inherit + lib + pkgs + cfg + packages + ; + inherit (nftr) perAppZapretRulesFile nft; + zapret2Sources = { inherit nfqws2-keenetic z2k; }; + } + ) + ) + + (lib.mkIf cfg.tgWsProxy.enable ( + (import ./tg-ws-proxy.nix { + inherit + lib + pkgs + packages + cfg + derived + ; + }).config + )) + + # SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH + # outbound, and a standalone tunnel has no backend at all, so both keep it. + (lib.mkIf derived.sshProxyUnitEnabled ( + import ./ssh-proxy.nix { + inherit + lib + pkgs + cfg + derived + ; + } + )) + + (lib.mkIf cfg.warp.enable ( + import ./warp.nix { + inherit + lib + pkgs + cfg + derived + ; + } + )) + + (lib.mkIf cfg.amneziaWg.enable ( + import ./amnezia-wg.nix { + inherit + lib + pkgs + cfg + derived + ; + } + )) + ] + )) + ]; +} diff --git a/modules/proxy-suite/default.nix b/modules/proxy-suite/default.nix index b20982c..a07a522 100644 --- a/modules/proxy-suite/default.nix +++ b/modules/proxy-suite/default.nix @@ -1,195 +1,20 @@ -# Factory function – receives the zapret flake and this flake's own nixpkgs, -# returns a NixOS module. This lets consumers add a single flake input and get -# everything transitively. -{ - zapret, - nixpkgs, - nfqws2-keenetic, - z2k, -}: - -{ - config, - options, - lib, - pkgs, - ... -}: +# Factory: receives the zapret flake and this flake's own nixpkgs, and returns the +# proxy-suite module for each supported host. Consumers add a single flake input and +# get everything transitively. +inputs: let - cfg = config.services.proxy-suite; - packages = import ../../pkgs/default.nix { inherit pkgs; }; - nftr = import ./nftables.nix { inherit lib pkgs cfg; }; - derived = import ./derived.nix { inherit lib cfg; }; - - # Scripts share one store name per block, and journald names a unit's output - # after its ExecStart basename; tag each unit with its own name instead. - unitsWithOwnSyslogIdentifier = lib.mkOption { - type = lib.types.attrsOf ( - lib.types.submodule ( - { name, ... }: - { - config.serviceConfig.SyslogIdentifier = lib.mkIf (lib.hasPrefix "proxy-suite-" name) ( - lib.mkDefault (lib.removeSuffix "@" name) - ); - } - ) - ); + core = import ./core.nix inputs; + forHost = adapter: { + imports = [ + core + adapter + ]; }; in { - imports = [ - ./options - ]; - - options.systemd.services = unitsWithOwnSyslogIdentifier; - options.systemd.user.services = unitsWithOwnSyslogIdentifier; - - config = lib.mkMerge [ - { - # xray and sing-box default to this flake's own nixpkgs (redirect it - # with inputs.nixpkgs.follows), not the system's: a stable release lags - # both by months, and current xray needs a newer Go than stable ships. - _module.args.proxySuiteUpstream = - let - upstream = nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system}; - in - { - xray = import ../../pkgs/xray.nix { pkgs = upstream; }; - # AWG 3.1 userspace; its kernel module has to match the system's kernel instead. - amneziaWg = import ../../pkgs/amneziawg.nix { pkgs = upstream; }; - inherit (upstream) sing-box; - }; - } - - (lib.mkIf cfg.enable ( - let - rules = import ./rules.nix { - inherit - lib - pkgs - cfg - zapret - ; - }; - configs = import ./config.nix { - inherit - lib - pkgs - cfg - rules - ; - }; - in - lib.mkMerge [ - (import ./service { - inherit - config - options - lib - pkgs - packages - cfg - ; - inherit (configs) - tproxyFile - tunFile - perAppTunFile - routeModeRulesFile - proxyInboundsFile - proxyInboundsSpecFile - ; - inherit (nftr) - nftablesRulesFile - perAppTproxyRulesFile - perAppZapretRulesFile - perAppTunChainFile - ip - nft - ; - }) - - (lib.mkIf - ( - cfg.zapret.engine == "zapret-discord-youtube" - && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable) - ) - ( - import ./zapret.nix { - inherit - lib - pkgs - cfg - zapret - ; - inherit (nftr) perAppZapretRulesFile nft; - } - ) - ) - - (lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) - ( - import ./zapret2.nix { - inherit - lib - pkgs - cfg - packages - ; - inherit (nftr) perAppZapretRulesFile nft; - zapret2Sources = { inherit nfqws2-keenetic z2k; }; - } - ) - ) - - (lib.mkIf cfg.tgWsProxy.enable ( - (import ./tg-ws-proxy.nix { - inherit - lib - pkgs - packages - cfg - derived - ; - }).config - )) - - # SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH - # outbound, and a standalone tunnel has no backend at all, so both keep it. - (lib.mkIf derived.sshProxyUnitEnabled ( - import ./ssh-proxy.nix { - inherit - lib - pkgs - cfg - derived - ; - } - )) - - (lib.mkIf cfg.warp.enable ( - import ./warp.nix { - inherit - lib - pkgs - cfg - derived - ; - } - )) - - (lib.mkIf cfg.amneziaWg.enable ( - import ./amnezia-wg.nix { - inherit - config - lib - pkgs - cfg - derived - ; - } - )) - ] - )) - ]; + nixos = forHost ./hosts/nixos.nix; + homeManager = forHost ./hosts/home-manager.nix; + systemManager = forHost ./hosts/system-manager.nix; + nixOnDroid = forHost ./hosts/nix-on-droid.nix; } diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 9cc66f9..9791aca 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -5,6 +5,8 @@ let proxyCfg = cfg.proxy; + # Host paths: /var/lib/proxy-suite and /run on a system install. + inherit (cfg.host) stateDir runtimeDir; singBoxCfg = proxyCfg // { enable = singBoxEnabled; package = proxyCfg.singBox.package; @@ -38,20 +40,17 @@ let # Without a configFile, proxy-suite-warp registers with wgcf into its state dir. autoRegister = cfg.warp.enable && cfg.warp.configFile == null; profilePath = - if cfg.warp.configFile != null then - cfg.warp.configFile - else - "/var/lib/proxy-suite/warp/wgcf-profile.conf"; + if cfg.warp.configFile != null then cfg.warp.configFile else "${stateDir}/warp/wgcf-profile.conf"; # Loopback SOCKS listener of proxy-suite-warp-tunnel, which the "warp" outbound dials. tunnelPort = 18538; # Its "direct-in" listener, which tells a blocked WARP from a dead uplink. directPort = 18539; }; warpOutboundTag = "warp"; - # The sing-box tunnel; asOutbound = "interface" comes in through the AmneziaWG profile list. + # The sing-box tunnel; "userspace" and "interface" come in through the AmneziaWG profile list. warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound == "singBox"; - # Two ports per "singBox" AmneziaWG outbound, above the autoProxy prober's own + # Two ports per "singBox" or "userspace" AmneziaWG outbound, above the autoProxy prober's own # listeners (proxy.autoProxy.probeBasePort, 18540 by default, one per exit): # both bind loopback, so an overlap leaves whichever unit starts second dead. awgTunnelBasePort = 18600; @@ -69,12 +68,15 @@ let tag = name; kind = profile.asOutbound; interface = profile.interfaceName; - # Loopback listeners of a "singBox" tunnel, as warpCfg.tunnelPort/directPort. + # Loopback listeners of a "singBox" or "userspace" tunnel, as warpCfg.tunnelPort/directPort + # (only sing-box listens on directPort). tunnelPort = awgTunnelBasePort + 2 * index; directPort = awgTunnelBasePort + 1 + 2 * index; } ) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles)); awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds; + # Profiles run behind a loopback SOCKS hop rather than an interface. + awgTunnelOutbounds = builtins.filter (ob: ob.kind != "interface") awgOutbounds; proxyInboundsCfg = cfg.inbounds; proxyInboundsEnabled = proxyInboundsCfg.enable; @@ -202,19 +204,33 @@ let userControlAllows = scope: userControlEnabled && (userControlCfg.scopes == [ ] || builtins.elem scope userControlCfg.scopes); + managerFlag = lib.optionalString (cfg.host.serviceManager == "systemd-user") " --user"; constants = { + inherit stateDir runtimeDir; + inherit (cfg.host) privileged serviceManager; + # 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 # runAsServiceUser with only the capabilities it needs. + # 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"; + # 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 + # user's manager on a home-manager host, and in proxy-suitectl on nix-on-droid. + systemctl = cfg.host.systemctl + managerFlag; + journalctl = cfg.host.journalctl + managerFlag; runAsServiceUser = pkgs: caps: let keep = lib.concatMapStrings (cap: ",+${cap}") caps; in - "${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 --"; + lib.optionalString cfg.host.privileged ( + "${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 --" + ); # The same for a unit that needs no root at all; "+" ExecStartPre/ExecStopPost # commands still run privileged. unprivilegedServiceConfig = @@ -222,7 +238,7 @@ let let systemdCaps = map (cap: "CAP_${lib.toUpper cap}") caps; in - { + lib.optionalAttrs cfg.host.privileged { User = "proxy-suite-daemon"; Group = "proxy-suite-daemon"; AmbientCapabilities = systemdCaps; @@ -244,8 +260,8 @@ let "net_raw" ]; - zapret2StateDir = "/var/lib/proxy-suite/zapret2"; - zapret2CutoffDir = "/var/lib/proxy-suite/zapret2/cutoff"; + zapret2StateDir = "${stateDir}/zapret2"; + zapret2CutoffDir = "${stateDir}/zapret2/cutoff"; # Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone. zapret2CutoffProbeCtMark = 33554432; # 0x2000000 @@ -257,23 +273,23 @@ let zapret2 = 300; }; - autoProxyStateDir = "/var/lib/proxy-suite/autoproxy"; + autoProxyStateDir = "${stateDir}/autoproxy"; # 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; # the pin outlives a reboot, unlike the per-boot route-mode override. - pinnedOutboundFile = "/var/lib/proxy-suite/pinned-outbound"; - runtimeOutboundsDir = "/var/lib/proxy-suite/outbounds.d"; - runtimeSubscriptionsDir = "/var/lib/proxy-suite/subscriptions.d"; + pinnedOutboundFile = "${stateDir}/pinned-outbound"; + runtimeOutboundsDir = "${stateDir}/outbounds.d"; + runtimeSubscriptionsDir = "${stateDir}/subscriptions.d"; # Written by every backend start script; proxy-ctl reads the socks copy. - outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json"; + outboundInventoryFile = "${runtimeDir}/proxy-suite-socks/outbounds.json"; inboundStatsApiPort = 18536; # sing-box's fake IP caches, one per TUN config; the start script hands it to the backend. - fakeIpCacheDir = "/var/lib/proxy-suite/fakeip"; + fakeIpCacheDir = "${stateDir}/fakeip"; # Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches. outboundTestPort = 18537; - inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json"; + inboundStatsFile = "${stateDir}/inbound-stats.json"; # sing-box DNS server resolving through an "interface" AmneziaWG outbound. awgDnsServerTag = tag: "awg-dns-${tag}"; @@ -360,6 +376,7 @@ in awgGlobalProfiles awgOutbounds awgInterfaceOutbounds + awgTunnelOutbounds proxyInboundsCfg proxyInboundsEnabled proxyInbounds diff --git a/modules/proxy-suite/hosts/common.nix b/modules/proxy-suite/hosts/common.nix new file mode 100644 index 0000000..8d1a0d8 --- /dev/null +++ b/modules/proxy-suite/hosts/common.nix @@ -0,0 +1,30 @@ +# Shared by the adapters whose host runs NixOS's own systemd unit options (NixOS, +# system-manager). +{ lib }: + +rec { + # Only what the core set: an internal option's default would add a definition of its + # own. Definitions are forwarded rather than values, so priorities nested inside them + # (mkDefault in a unit, say) still meet the rest of the host's. + forwardWith = + wrap: option: + lib.mkIf (option.highestPrio < (lib.mkOptionDefault null).priority) ( + lib.mkMerge (map wrap option.definitions) + ); + forward = forwardWith lib.id; + + # Scripts share one store name per block, and journald names a unit's output + # after its ExecStart basename; tag each unit with its own name instead. + unitsWithOwnSyslogIdentifier = lib.mkOption { + type = lib.types.attrsOf ( + lib.types.submodule ( + { name, ... }: + { + config.serviceConfig.SyslogIdentifier = lib.mkIf (lib.hasPrefix "proxy-suite-" name) ( + lib.mkDefault (lib.removeSuffix "@" name) + ); + } + ) + ); + }; +} diff --git a/modules/proxy-suite/hosts/home-manager.nix b/modules/proxy-suite/hosts/home-manager.nix new file mode 100644 index 0000000..9be2ea3 --- /dev/null +++ b/modules/proxy-suite/hosts/home-manager.nix @@ -0,0 +1,64 @@ +# home-manager: the services run rootless in the user's systemd manager, rendered into +# home-manager's INI form by ./user-units.nix. +{ + config, + options, + lib, + pkgs, + ... +}: + +let + cfg = config.services.proxy-suite; + host = cfg.host; + internal = cfg.internal; + + inherit + (import ./user-units.nix { + inherit lib pkgs; + inherit (host) runtimeDir; + stateDir = dirOf host.stateDir; + }) + toService + toTimer + toPath + ; + + enabled = lib.filterAttrs (_: unit: unit.enable); +in +{ + config = lib.mkMerge [ + { + services.proxy-suite.host = { + kind = "home-manager"; + privileged = false; + serviceManager = "systemd-user"; + stateDir = lib.mkDefault "${config.xdg.stateHome}/proxy-suite"; + # A literal path the scripts and proxy-ctl can share: the user's runtime + # directory is only known once the manager runs. Point it at /run/user/UID to + # have it cleared on reboot. + runtimeDir = lib.mkDefault "${config.xdg.cacheHome}/proxy-suite/run"; + }; + } + + (lib.mkIf cfg.enable ( + lib.mkMerge [ + { + systemd.user.services = lib.mapAttrs toService ( + enabled (internal.services // internal.userServices) + ); + systemd.user.timers = lib.mapAttrs toTimer (enabled internal.timers); + systemd.user.paths = lib.mapAttrs toPath (enabled internal.paths); + + home.packages = lib.mkMerge [ + (lib.mkBefore internal.earlyPackages) + internal.packages + ]; + } + (lib.optionalAttrs (options.systemd.user ? tmpfiles) { + systemd.user.tmpfiles.rules = internal.tmpfiles; + }) + ] + )) + ]; +} diff --git a/modules/proxy-suite/hosts/nix-on-droid.nix b/modules/proxy-suite/hosts/nix-on-droid.nix new file mode 100644 index 0000000..ca821b6 --- /dev/null +++ b/modules/proxy-suite/hosts/nix-on-droid.nix @@ -0,0 +1,123 @@ +# nix-on-droid: no systemd and no root. The units run under proxy-suitectl, a small +# supervisor that reads them, rendered as for a user manager, from a manifest the +# activation links into place; proxy-ctl and the scripts talk to it in systemctl's words. +{ + config, + lib, + pkgs, + ... +}: + +let + cfg = config.services.proxy-suite; + host = cfg.host; + internal = cfg.internal; + home = config.user.home; + + inherit + (import ./user-units.nix { + inherit lib pkgs; + inherit (host) runtimeDir; + stateDir = dirOf host.stateDir; + hostPath = "${home}/.nix-profile/bin"; + }) + toService + toTimer + toPath + ; + + enabled = lib.filterAttrs (_: unit: unit.enable); + + supervisorDir = "${host.runtimeDir}/proxy-suite-supervisor"; + # Outside the store, so proxy-suitectl stays the same from one generation to the next. + manifestLink = "${host.stateDir}/supervisor/manifest.json"; + manifest = pkgs.writeText "proxy-suite-units.json" ( + builtins.toJSON { + services = lib.mapAttrs toService (enabled (internal.services // internal.userServices)); + timers = lib.mapAttrs toTimer (enabled internal.timers); + paths = lib.mapAttrs toPath (enabled internal.paths); + inherit (internal) tmpfiles; + } + ); + + suitectl = import ../../../pkgs/proxy-suite-supervisor.nix { inherit lib pkgs; } { + inherit supervisorDir; + manifest = manifestLink; + inherit (host) runtimeDir; + stateDir = dirOf host.stateDir; + }; + suitectlBin = "${suitectl}/bin/proxy-suitectl"; + + # Once per session tree: nested shells find it exported. + sessionStart = '' + if [ -z "''${__PROXY_SUITE_SESSION:-}" ]; then + export __PROXY_SUITE_SESSION=1 + ( ${suitectlBin} ensure >/dev/null 2>&1 & ) + fi + ''; +in +{ + options.services.proxy-suite.nixOnDroid.startWithSession = lib.mkOption { + type = lib.types.bool; + default = true; + description = '' + Start the services when a Nix-on-Droid shell opens, if they are not running yet. + Android offers the app no boot hook, so without this they only start on + `nix-on-droid switch` or `proxy-suitectl boot`. Android may still stop them in + the background: keep the app's wake lock on and exempt it from battery optimisation. + ''; + }; + + config = lib.mkMerge [ + { + services.proxy-suite.host = { + kind = "nix-on-droid"; + privileged = false; + serviceManager = "supervisor"; + stateDir = lib.mkDefault "${home}/.local/state/proxy-suite"; + runtimeDir = lib.mkDefault "${home}/.cache/proxy-suite/run"; + systemctl = suitectlBin; + journalctl = "${suitectlBin} journal"; + enableIPv6 = true; + # Android's kernel, resolver and firewall are not the app's to change. + kernelPackages = null; + firewallPackage = null; + resolvconfPackage = null; + }; + } + + (lib.mkIf cfg.enable { + assertions = [ + { + assertion = !cfg.gui.enable; + message = "proxy-suite: the GUI needs a desktop session, which a nix-on-droid host does not have; use proxy-ctl or proxy-tui"; + } + ]; + + environment.packages = internal.earlyPackages ++ internal.packages ++ [ suitectl ]; + + build.activationAfter.proxySuite = '' + $DRY_RUN_CMD mkdir -p ${lib.escapeShellArg (dirOf manifestLink)} + $DRY_RUN_CMD ln -sfn ${manifest} ${lib.escapeShellArg manifestLink} + # Starts the supervisor, or restarts what changed under a running one. + if ! $DRY_RUN_CMD ${suitectlBin} boot; then + warnEcho "proxy-suite: some units did not start; see proxy-ctl status" + fi + ''; + + environment.etc = lib.mkIf cfg.nixOnDroid.startWithSession { + "profile".text = lib.mkAfter sessionStart; + "zshenv".text = lib.mkAfter sessionStart; + }; + }) + + (lib.mkIf (!cfg.enable) { + # Disabled since the last generation: nothing should keep running. + build.activationAfter.proxySuite = '' + if [ -S ${lib.escapeShellArg "${supervisorDir}/control.sock"} ]; then + $DRY_RUN_CMD ${suitectlBin} shutdown || true + fi + ''; + }) + ]; +} diff --git a/modules/proxy-suite/hosts/nixos.nix b/modules/proxy-suite/hosts/nixos.nix new file mode 100644 index 0000000..06a8022 --- /dev/null +++ b/modules/proxy-suite/hosts/nixos.nix @@ -0,0 +1,75 @@ +# NixOS: the core's declarations become NixOS settings as they are. +{ + config, + options, + lib, + ... +}: + +let + cfg = config.services.proxy-suite; + internal = options.services.proxy-suite.internal; + inherit (import ./common.nix { inherit lib; }) + forwardWith + forward + unitsWithOwnSyslogIdentifier + ; +in +{ + options.systemd.services = unitsWithOwnSyslogIdentifier; + options.systemd.user.services = unitsWithOwnSyslogIdentifier; + + config = lib.mkMerge [ + { + services.proxy-suite.host = { + kind = "nixos"; + privileged = true; + serviceManager = "systemd"; + inherit (config.networking) enableIPv6; + inherit (config.boot) kernelPackages; + firewallPackage = config.networking.firewall.package; + resolvconfPackage = config.networking.resolvconf.package; + }; + } + + (lib.mkIf cfg.enable { + systemd.services = forward internal.services; + systemd.user.services = forward internal.userServices; + systemd.timers = forward internal.timers; + systemd.paths = forward internal.paths; + systemd.tmpfiles.rules = forward internal.tmpfiles; + + environment.systemPackages = lib.mkMerge [ + (forwardWith lib.mkBefore internal.earlyPackages) + (forward internal.packages) + ]; + + 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) (_: { }); + + security.polkit.enable = lib.mkIf cfg.internal.polkit.enable true; + security.polkit.extraConfig = forwardWith lib.mkAfter internal.polkit.rules; + + networking.nftables.enable = lib.mkIf cfg.internal.nftables (lib.mkDefault true); + networking.firewall = { + allowedTCPPorts = forward internal.firewall.allowedTCPPorts; + allowedUDPPorts = forward internal.firewall.allowedUDPPorts; + extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules; + }; + + boot.extraModulePackages = forward internal.kernelModulePackages; + }) + + # Off by default since nixpkgs 26.11, and always there before, where the option does + # not exist. + (lib.optionalAttrs (options.security.polkit ? enablePkexecWrapper) { + security.polkit.enablePkexecWrapper = lib.mkIf ( + cfg.enable && cfg.internal.polkit.pkexecWrapper + ) true; + }) + ]; +} diff --git a/modules/proxy-suite/hosts/system-manager.nix b/modules/proxy-suite/hosts/system-manager.nix new file mode 100644 index 0000000..4dd96a6 --- /dev/null +++ b/modules/proxy-suite/hosts/system-manager.nix @@ -0,0 +1,118 @@ +# system-manager (numtide/system-manager): root services on another distribution. Its +# systemd options are NixOS's own, so units are forwarded as on NixOS; what it lacks +# (user units, polkit, nftables, the firewall, kernel modules) is written to /etc or +# left to the host. +{ + config, + options, + lib, + pkgs, + ... +}: + +let + cfg = config.services.proxy-suite; + internal = options.services.proxy-suite.internal; + inherit (import ./common.nix { inherit lib; }) + forwardWith + forward + unitsWithOwnSyslogIdentifier + ; + + # For the user manager each session runs: units go to /etc/systemd/user, which it reads + # alongside the distribution's own. + userUnits = import ./user-units.nix { + inherit lib pkgs; + runtimeDir = "%t"; + stateDir = "%S"; + # The GUI escalates through the distribution's setuid pkexec. + hostPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; + }; + toINI = lib.generators.toINI { listsAsDuplicateKeys = true; }; + userServiceFiles = lib.concatMapAttrs ( + name: unit: + let + fileName = "${name}.service"; + rendered = userUnits.toService name unit; + file = pkgs.writeText fileName (toINI rendered); + link = target: lib.nameValuePair "systemd/user/${target}/${fileName}" { source = file; }; + in + { + "systemd/user/${fileName}".source = file; + } + // lib.listToAttrs ( + map (target: link "${target}.wants") (rendered.Install.WantedBy or [ ]) + ++ map (target: link "${target}.requires") (rendered.Install.RequiredBy or [ ]) + ) + ) (lib.filterAttrs (_: unit: unit.enable) cfg.internal.userServices); + + # awg-quick pushes DNS through resolvconf: resolvectl stands in for it where + # systemd-resolved owns resolv.conf, openresolv everywhere else. + resolvconf = pkgs.writeShellScriptBin "resolvconf" '' + if [ -d /run/systemd/resolve ]; then + exec -a resolvconf ${pkgs.systemd}/bin/resolvectl "$@" + fi + exec ${pkgs.openresolv}/bin/resolvconf "$@" + ''; +in +{ + options.systemd.services = unitsWithOwnSyslogIdentifier; + + config = lib.mkMerge [ + { + services.proxy-suite.host = { + kind = "system-manager"; + privileged = true; + serviceManager = "systemd"; + inherit (config.networking) enableIPv6; + # The host's kernel is not Nix's to extend: AmneziaWG runs in userspace. + kernelPackages = null; + firewallPackage = pkgs.nftables; + resolvconfPackage = resolvconf; + }; + } + + (lib.mkIf cfg.enable { + assertions = [ + { + assertion = cfg.internal.kernelModulePackages == [ ]; + message = "proxy-suite: system-manager cannot load kernel modules from Nix; leave amneziaWg.kernelModulePackage at null"; + } + ]; + + systemd.services = forward internal.services; + systemd.timers = forward internal.timers; + systemd.paths = forward internal.paths; + systemd.tmpfiles.rules = forward internal.tmpfiles; + + environment.systemPackages = lib.mkMerge [ + (forwardWith lib.mkBefore internal.earlyPackages) + (forward internal.packages) + ]; + + environment.etc = lib.mkMerge [ + userServiceFiles + # Read by polkit 0.106 and later; the distribution runs the daemon. The rules + # go through the host's setuid pkexec: nothing here needs a wrapper. + (lib.mkIf cfg.internal.polkit.enable { + "polkit-1/rules.d/50-proxy-suite.rules".text = cfg.internal.polkit.rules; + }) + ]; + + 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) (_: { }); + + # Only reported: system-manager leaves the host firewall alone. The routing modes + # load their own nftables tables, and the distribution's loose reverse-path filter + # already lets AmneziaWG replies in. + networking.firewall = { + allowedTCPPorts = forward internal.firewall.allowedTCPPorts; + allowedUDPPorts = forward internal.firewall.allowedUDPPorts; + }; + }) + ]; +} diff --git a/modules/proxy-suite/hosts/user-units.nix b/modules/proxy-suite/hosts/user-units.nix new file mode 100644 index 0000000..ec89f3f --- /dev/null +++ b/modules/proxy-suite/hosts/user-units.nix @@ -0,0 +1,217 @@ +# Renders the core's systemd-shaped units into a user manager's INI sections +# ({ Unit, Service, Install }), with what only NixOS's unit options provide spelled out: +# the directories systemd would create and the PATH NixOS would set. runtimeDir and +# stateDir are the bases of RuntimeDirectory= and StateDirectory= (specifiers allowed); +# hostPath ends every PATH, for the host's own setuid binaries. +{ + lib, + pkgs, + runtimeDir, + stateDir, + hostPath ? null, +}: + +let + # The user manager has none of the system targets; the default target stands in for + # multi-user.target. + systemTargets = [ + "network.target" + "network-online.target" + "nss-lookup.target" + "sysinit.target" + ]; + userTargets = { + "multi-user.target" = "default.target"; + }; + toUserUnits = + units: lib.unique (map (unit: userTargets.${unit} or unit) (lib.subtractLists systemTargets units)); + + # Identity, capabilities and sandboxing: a user manager can apply them only partly + # (and ProtectHome would hide the state directory), and the core sets none of them + # for a rootless host itself. + systemOnlyKeys = [ + "User" + "Group" + "DynamicUser" + "SupplementaryGroups" + "AmbientCapabilities" + "CapabilityBoundingSet" + "PrivateTmp" + "PrivateDevices" + "ProtectSystem" + "ProtectHome" + "ProtectClock" + "ProtectHostname" + "ProtectKernelModules" + "ProtectKernelLogs" + "ProtectKernelTunables" + "ProtectControlGroups" + "RestrictSUIDSGID" + "RestrictRealtime" + "LockPersonality" + "ReadWritePaths" + "ReadOnlyPaths" + # Rendered below against runtimeDir and stateDir: a user manager resolves them + # against XDG directories, which need not be where the core looks. + "RuntimeDirectory" + "RuntimeDirectoryMode" + "StateDirectory" + "StateDirectoryMode" + ]; + + # home-manager takes plain values only. + iniValue = + value: + if lib.isList value then + map iniValue value + else if lib.isBool value || lib.isInt value then + value + else + toString value; + 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 + ]; + + # As NixOS: "@" is not allowed in a store path name. + jobScript = + name: text: pkgs.writeShellScript (lib.replaceStrings [ "@" ] [ "_" ] name) "set -e\n${text}"; + + dirsScript = pkgs.writeShellScript "proxy-suite-dirs" '' + while (( $# )); do + ${pkgs.coreutils}/bin/install -d -m "$1" -- "$2" + shift 2 + done + ''; + removeDirsScript = pkgs.writeShellScript "proxy-suite-remove-dirs" '' + ${pkgs.coreutils}/bin/rm -rf -- "$@" + ''; + + directories = + serviceConfig: key: base: + map (dir: { + path = "${base}/${dir}"; + mode = serviceConfig."${key}Mode" or "0755"; + }) (lib.concatMap (lib.splitString " ") (lib.toList (serviceConfig.${key} or [ ]))); + + unitSection = + unit: + iniSection ( + { + Description = unit.description; + } + // lib.filterAttrs (_: v: v != [ ]) { + After = toUserUnits unit.after; + Before = toUserUnits unit.before; + Wants = toUserUnits unit.wants; + Requires = toUserUnits unit.requires; + BindsTo = toUserUnits unit.bindsTo; + PartOf = toUserUnits unit.partOf; + Conflicts = toUserUnits unit.conflicts; + } + // lib.optionalAttrs (unit.startLimitIntervalSec != null) { + StartLimitIntervalSec = unit.startLimitIntervalSec; + } + // unit.unitConfig + ); + + installSection = + unit: + lib.filterAttrs (_: v: v != [ ]) { + WantedBy = toUserUnits unit.wantedBy; + RequiredBy = toUserUnits unit.requiredBy; + }; + + withInstall = + unit: attrs: + attrs + // lib.optionalAttrs (installSection unit != { }) { + Install = installSection unit; + }; + + toService = + name: unit: + let + sc = unit.serviceConfig; + runtimeDirs = directories sc "RuntimeDirectory" runtimeDir; + stateDirs = directories sc "StateDirectory" stateDir; + dirs = runtimeDirs ++ stateDirs; + joinPaths = ds: lib.concatMapStringsSep ":" (d: d.path) ds; + + # Paths go on the command line, where systemd expands specifiers such as %t. + commandLine = + script: args: lib.concatStringsSep " " ([ "${script}" ] ++ map (arg: ''"${arg}"'') args); + makeDirs = commandLine dirsScript ( + lib.concatMap (d: [ + d.mode + d.path + ]) dirs + ); + removeRuntimeDirs = commandLine removeDirsScript (map (d: d.path) runtimeDirs); + + path = unit.path ++ defaultPath; + environment = { + PATH = lib.concatStringsSep ":" ( + [ + (lib.makeBinPath path) + (lib.makeSearchPathOutput "bin" "sbin" path) + ] + ++ lib.optional (hostPath != null) hostPath + ); + } + // lib.optionalAttrs (runtimeDirs != [ ]) { RUNTIME_DIRECTORY = joinPaths runtimeDirs; } + // lib.optionalAttrs (stateDirs != [ ]) { STATE_DIRECTORY = joinPaths stateDirs; } + // lib.filterAttrs (_: v: v != null) unit.environment; + + optionalScript = suffix: text: lib.optional (text != "") (jobScript "${name}-${suffix}" text); + in + withInstall unit { + Unit = unitSection unit; + Service = iniSection ( + builtins.removeAttrs sc systemOnlyKeys + // lib.optionalAttrs (sc ? WorkingDirectory && !lib.hasPrefix "-" sc.WorkingDirectory) { + # Created by the first ExecStartPre, which already runs in it. + WorkingDirectory = "-${sc.WorkingDirectory}"; + } + // lib.filterAttrs (_: v: v != [ ]) { + Environment = + lib.mapAttrsToList (n: v: builtins.toJSON "${n}=${toString v}") environment + ++ lib.toList (sc.Environment or [ ]); + ExecStartPre = + lib.optional (dirs != [ ]) makeDirs + ++ optionalScript "pre-start" unit.preStart + ++ lib.toList (sc.ExecStartPre or [ ]); + ExecStart = optionalScript "start" unit.script ++ lib.toList (sc.ExecStart or [ ]); + ExecStartPost = optionalScript "post-start" unit.postStart ++ lib.toList (sc.ExecStartPost or [ ]); + ExecStop = optionalScript "pre-stop" unit.preStop ++ lib.toList (sc.ExecStop or [ ]); + ExecStopPost = + optionalScript "post-stop" unit.postStop + ++ lib.toList (sc.ExecStopPost or [ ]) + ++ lib.optional (runtimeDirs != [ ]) removeRuntimeDirs; + } + ); + }; + + toTimer = + _: unit: + withInstall unit { + Unit = unitSection unit; + Timer = iniSection unit.timerConfig; + }; + + toPath = + _: unit: + withInstall unit { + Unit = unitSection unit; + Path = iniSection unit.pathConfig; + }; +in +{ + inherit toService toTimer toPath; +} diff --git a/modules/proxy-suite/options/amnezia-wg.nix b/modules/proxy-suite/options/amnezia-wg.nix index e5d32b1..f617e83 100644 --- a/modules/proxy-suite/options/amnezia-wg.nix +++ b/modules/proxy-suite/options/amnezia-wg.nix @@ -30,9 +30,19 @@ in description = "AWG 3.1 userspace implementation used when the kernel interface is unavailable."; }; + wireproxyPackage = mkOption { + type = types.package; + default = awgPackages.wireproxy; + description = "wireproxy build with AWG 3.1 and FwMark, which runs profiles with asOutbound = \"userspace\"."; + }; + kernelModulePackage = mkOption { type = types.nullOr types.package; - default = awgPackages.kernelModule config.boot.kernelPackages; + default = + let + kernelPackages = config.services.proxy-suite.host.kernelPackages; + in + if kernelPackages == null then null else awgPackages.kernelModule kernelPackages; description = "AWG 3.1 kernel module package. Set null to use userspace-only fallback."; }; diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index 6fdd2b4..5389043 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -21,6 +21,7 @@ ./tray.nix ./tui.nix ./user-control.nix + ./host.nix ]; options.services.proxy-suite.enable = lib.mkEnableOption "proxy-suite"; diff --git a/modules/proxy-suite/options/host.nix b/modules/proxy-suite/options/host.nix new file mode 100644 index 0000000..6bedb6c --- /dev/null +++ b/modules/proxy-suite/options/host.nix @@ -0,0 +1,74 @@ +# What the host adapter (modules/proxy-suite/hosts/*.nix) tells the core about the +# host, and what the core hands back for the adapter to turn into host settings. +# Nothing here is user-facing. +{ lib, pkgs, ... }: + +let + inherit (lib) mkOption types; + unitType = import ./types/unit.nix { inherit lib; }; + + internalOption = + type: default: + mkOption { + inherit type default; + internal = true; + visible = false; + }; + units = internalOption (types.attrsOf unitType) { }; +in +{ + options.services.proxy-suite.host = { + kind = internalOption (types.enum [ + "nixos" + "system-manager" + "home-manager" + "nix-on-droid" + ]) "nixos"; + # Whether the services run as root and may program routing, firewalls and interfaces. + privileged = internalOption types.bool true; + # Persistent state; units name the proxy-suite subdirectory of their host's state dir. + stateDir = internalOption types.str "/var/lib/proxy-suite"; + # Parent of the per-unit runtime directories (proxy-suite-socks, …). + runtimeDir = internalOption types.str "/run"; + # Which manager runs the units: proxy-ctl and the control scripts talk to it. + serviceManager = internalOption (types.enum [ + "systemd" + "systemd-user" + "supervisor" + ]) "systemd"; + # The commands that manage the units and show their logs, without a --user of their own. + systemctl = internalOption types.str "${pkgs.systemd}/bin/systemctl"; + journalctl = internalOption types.str "journalctl"; + # Host facts a few option defaults read. + enableIPv6 = internalOption types.bool true; + kernelPackages = internalOption (types.nullOr types.raw) null; + firewallPackage = internalOption (types.nullOr types.package) null; + resolvconfPackage = internalOption (types.nullOr types.package) null; + }; + + options.services.proxy-suite.internal = { + # systemd-shaped unit declarations; the adapter installs or converts them. + services = units; + userServices = units; + timers = units; + paths = units; + tmpfiles = internalOption (types.listOf types.str) [ ]; + packages = internalOption (types.listOf types.package) [ ]; + # Ahead of the host's own packages (zapret's binaries shadow same-named ones). + earlyPackages = internalOption (types.listOf types.package) [ ]; + systemUsers = internalOption (types.listOf types.str) [ ]; + groups = internalOption (types.listOf types.str) [ ]; + polkit = { + enable = internalOption types.bool false; + pkexecWrapper = internalOption types.bool false; + rules = internalOption types.lines ""; + }; + nftables = internalOption types.bool false; + firewall = { + allowedTCPPorts = internalOption (types.listOf types.port) [ ]; + allowedUDPPorts = internalOption (types.listOf types.port) [ ]; + extraReversePathFilterRules = internalOption types.lines ""; + }; + kernelModulePackages = internalOption (types.listOf types.package) [ ]; + }; +} diff --git a/modules/proxy-suite/options/proxy.nix b/modules/proxy-suite/options/proxy.nix index 0d0cc17..66012b1 100644 --- a/modules/proxy-suite/options/proxy.nix +++ b/modules/proxy-suite/options/proxy.nix @@ -49,7 +49,7 @@ in ipv6 = mkOption { type = types.bool; - default = config.networking.enableIPv6; + default = config.services.proxy-suite.host.enableIPv6; defaultText = literalExpression "config.networking.enableIPv6"; description = '' Carry IPv6 in the transparent modes: TProxy through a second listener on ::1, the TUNs diff --git a/modules/proxy-suite/options/types/amnezia-wg.nix b/modules/proxy-suite/options/types/amnezia-wg.nix index a5e5592..3a5a265 100644 --- a/modules/proxy-suite/options/types/amnezia-wg.nix +++ b/modules/proxy-suite/options/types/amnezia-wg.nix @@ -273,6 +273,7 @@ let type = types.nullOr ( types.enum [ "singBox" + "userspace" "interface" ] ); @@ -283,6 +284,11 @@ let `proxy-ctl awg`. Requires proxy.enable. - "singBox": a WireGuard endpoint in its own sing-box process, reached as a loopback SOCKS hop. sing-box speaks plain WireGuard: AmneziaWG obfuscation is dropped with a warning. + - "userspace": the same hop served by wireproxy on AmneziaWG's userspace implementation, so + obfuscation works. It needs no interface or root: the only AmneziaWG mode on + home-manager and nix-on-droid. A declared or profile ListenPort is used as is. An + Endpoint hostname resolves through the system resolver: give an address where that + resolver cannot reach the name. - "interface": the AmneziaWG interface comes up without routes (Table = off), and the outbound binds to it, so obfuscation works. With the sing-box backend its DNS goes through the interface too (proxy.dns.remote); XRay resolves as usual. diff --git a/modules/proxy-suite/options/types/unit.nix b/modules/proxy-suite/options/types/unit.nix new file mode 100644 index 0000000..abece06 --- /dev/null +++ b/modules/proxy-suite/options/types/unit.nix @@ -0,0 +1,84 @@ +# The subset of NixOS's systemd unit options proxy-suite declares units with, merged +# the same way, so hosts without NixOS's systemd module can read them back. +{ lib }: + +let + inherit (lib) mkOption types; + + # As nixos/lib/systemd-lib.nix: lists concatenate, anything else must agree. + unitOption = lib.mkOptionType { + name = "systemd option"; + merge = + loc: defs: + let + defs' = lib.filterOverrides defs; + in + if lib.any (def: lib.isList def.value) defs' then + lib.concatMap (def: lib.toList def.value) defs' + else + lib.mergeEqualOption loc defs'; + }; + + list = mkOption { + type = types.listOf types.str; + default = [ ]; + }; + lines = mkOption { + type = types.lines; + default = ""; + }; + section = mkOption { + type = types.attrsOf unitOption; + default = { }; + }; +in +types.submodule { + options = { + enable = mkOption { + type = types.bool; + default = true; + }; + description = mkOption { + type = types.str; + default = ""; + }; + after = list; + before = list; + wants = list; + requires = list; + bindsTo = list; + partOf = list; + conflicts = list; + wantedBy = list; + requiredBy = list; + path = mkOption { + type = types.listOf (types.either types.package types.str); + default = [ ]; + }; + environment = mkOption { + type = types.attrsOf ( + types.nullOr ( + types.oneOf [ + types.str + types.path + types.package + ] + ) + ); + default = { }; + }; + script = lines; + preStart = lines; + postStart = lines; + preStop = lines; + postStop = lines; + startLimitIntervalSec = mkOption { + type = types.nullOr types.int; + default = null; + }; + unitConfig = section; + serviceConfig = section; + timerConfig = section; + pathConfig = section; + }; +} diff --git a/modules/proxy-suite/options/warp.nix b/modules/proxy-suite/options/warp.nix index 5b6f71c..ec389ef 100644 --- a/modules/proxy-suite/options/warp.nix +++ b/modules/proxy-suite/options/warp.nix @@ -39,6 +39,7 @@ in type = types.nullOr ( types.enum [ "singBox" + "userspace" "interface" ] ); @@ -49,6 +50,8 @@ in endpoint on 127.0.0.1:18538, as the proxy-suite-daemon user. The tunnel starts again on a new source port when WARP does not answer within 15 seconds of a start, or misses three probes later on, unless the uplink itself is down. + - "userspace": an AmneziaWG profile named "warp" with asOutbound = "userspace", which honours + the AmneziaWG lines of the profile without an interface or root. Requires amneziaWg.enable. - "interface": an AmneziaWG profile named "warp" with asOutbound = "interface", which honours the AmneziaWG lines of the profile. Requires amneziaWg.enable. ''; diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index c079d9b..6bc9a63 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -71,7 +71,66 @@ let ++ lib.concatMap (ob: [ ob.tunnelPort ob.directPort - ]) (builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds); + ]) derived.awgTunnelOutbounds; + + # A rootless host (home-manager, nix-on-droid) runs everything as the user: nothing + # that programs routing, firewalls or interfaces, and no privileged ports. + rootless = !constants.privileged; + hostKind = cfg.host.kind; + rootlessForbids = + used: feature: + mkAssertion ( + !(rootless && used) + ) "proxy-suite: ${feature} needs root, which services on a ${hostKind} host do not have"; + rootlessPorts = + lib.optional proxyEnabled { + name = "proxy.listener.port"; + port = proxyCfg.listener.port; + } + ++ lib.optional tgWsProxyCfg.enable { + name = "tgWsProxy.listener.port"; + port = tgWsProxyCfg.listener.port; + } + ++ lib.optional cfg.sshProxy.enable { + name = "sshProxy.listener.port"; + port = cfg.sshProxy.listener.port; + } + ++ lib.optionals cfg.inbounds.enable ( + lib.mapAttrsToList (name: listener: { + name = "inbounds.listeners.${name}.port"; + inherit (listener) port; + }) cfg.inbounds.listeners + ); + rootlessAssertions = [ + (rootlessForbids (proxyEnabled && globalTun.enable) "proxy.tun") + (rootlessForbids (proxyEnabled && globalTproxy.enable) "proxy.tproxy") + (rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTun.enable) "perAppRouting.tun") + (rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTproxy.enable) "perAppRouting.tproxy") + (rootlessForbids perAppZapretCfg.enable "perAppRouting.zapret") + (rootlessForbids zapretCfg.enable "zapret") + (rootlessForbids ( + derived.awgGlobalProfiles != { } || derived.awgInterfaceOutbounds != [ ] + ) ''an AmneziaWG interface (a global profile, or asOutbound = "interface"; use "userspace")'') + (mkAssertion (!(rootless && cfg.userControl.enable)) + "proxy-suite: userControl has nothing to grant on a ${hostKind} host, whose services already belong to the user" + ) + (mkAssertion + ( + !( + rootless + && cfg.sshProxy.enable + && cfg.sshProxy.serviceUser != null + && cfg.sshProxy.serviceUser != constants.serviceUser + ) + ) + "proxy-suite: sshProxy.serviceUser cannot switch users on a ${hostKind} host; leave it at its default" + ) + ] + ++ map ( + item: + mkAssertion (!(rootless && item.port < 1024)) + "proxy-suite: ${item.name} = ${toString item.port} is a privileged port, which services on a ${hostKind} host cannot bind; pick one from 1024 up" + ) rootlessPorts; featureAssertions = [ # Declaring no outbound at all is legal: they can be added at runtime with @@ -108,8 +167,8 @@ let "proxy-suite: warp.asOutbound requires proxy.enable = true" ) (requireEnabled ( - cfg.warp.enable && cfg.warp.asOutbound == "interface" - ) cfg.amneziaWg.enable ''proxy-suite: warp.asOutbound = "interface" requires amneziaWg.enable = true'') + cfg.warp.enable && builtins.elem cfg.warp.asOutbound [ "userspace" "interface" ] + ) cfg.amneziaWg.enable ''proxy-suite: warp.asOutbound = "${toString cfg.warp.asOutbound}" requires amneziaWg.enable = true'') (requireEnabled ( cfg.warp.enable && cfg.warp.asAmneziaWg ) cfg.amneziaWg.enable "proxy-suite: warp.asAmneziaWg requires amneziaWg.enable = true") @@ -730,7 +789,8 @@ let } ]; in -featureAssertions +rootlessAssertions +++ featureAssertions ++ perAppRoutingAssertions ++ localProxyAuthAssertions ++ secretAssertions diff --git a/modules/proxy-suite/service/control-scripts.nix b/modules/proxy-suite/service/control-scripts.nix index 469c5e0..00872a4 100644 --- a/modules/proxy-suite/service/control-scripts.nix +++ b/modules/proxy-suite/service/control-scripts.nix @@ -12,10 +12,10 @@ mkSubscriptionFetchBlock, runtimeSubscriptionsFetchBlock, jq, + systemctl, }: let - systemctl = "${pkgs.systemd}/bin/systemctl"; curl = "${pkgs.curl}/bin/curl"; restartActiveBlock = lib.concatMapStrings (svc: '' diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 82cc3e4..5e1cda1 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -63,6 +63,9 @@ if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl; autoProxyEnabled = if proxyCfg.autoProxy.enable then "1" else "0"; autoProxyStateDir = constants.autoProxyStateDir; + inherit (constants) stateDir runtimeDir serviceManager; + privileged = if constants.privileged then "1" else "0"; + supervisorCtl = if constants.serviceManager == "supervisor" then constants.systemctl else ""; singBox = "${singBoxCfg.package}/bin/sing-box"; localProxyUrl = "http://${ if proxyCfg.listener.address == "0.0.0.0" then "127.0.0.1" else proxyCfg.listener.address diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 6606767..c0fef14 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -1,7 +1,6 @@ -# Assembles proxy-suite systemd services from the sub-modules. +# Assembles proxy-suite services from the sub-modules, as host-neutral declarations +# under services.proxy-suite.internal (see ../hosts). { - config, - options, lib, pkgs, packages, @@ -130,60 +129,51 @@ let import ../autoproxy.nix { inherit lib pkgs cfg; inherit (control) proxyCtl; - inherit (constants) autoProxyStateDir; + inherit (constants) autoProxyStateDir runtimeDir journalctl; inherit userControlAllows; } ); in lib.mkMerge [ autoProxyUnits - # The GUI's pkexec needs its setuid wrapper, off by default since nixpkgs 26.11 (and - # always there before, where the option does not exist). - (lib.optionalAttrs (options.security.polkit ? enablePkexecWrapper) { - security.polkit.enablePkexecWrapper = lib.mkIf (cfg.enable && cfg.gui.enable) true; - }) { - # See constants.serviceUser. - users.users.${constants.serviceUser} = { - isSystemUser = true; - group = constants.serviceUser; - description = "proxy-suite daemons"; - }; - users.groups.${constants.serviceUser} = { }; - } - { - environment.systemPackages = [ - control.proxyCtl - ] - ++ lib.optional cfg.tui.enable control.proxyCtl.tui - ++ lib.optional cfg.gui.enable control.proxyCtl.gui; + 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 ]; - # nftables must be on for transparent routing backends. Global TUN uses - # SingBox auto_redirect programs an `inet sing-box` nftables table. - networking.nftables.enable = lib.mkIf ( - globalTun.enable - || globalTproxy.enable - || perAppRoutingTun.enable - || perAppRoutingTproxy.enable - || perAppZapretEnabled - ) (lib.mkDefault true); + packages = [ + control.proxyCtl + ] + ++ lib.optional cfg.tui.enable control.proxyCtl.tui + ++ lib.optional cfg.gui.enable control.proxyCtl.gui; - # Inbound listeners are reached from outside, so their ports have to be open. - networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) { - allowedTCPPorts = proxyInboundFirewallPorts; - allowedUDPPorts = proxyInboundFirewallUdpPorts; - }; + # nftables must be on for transparent routing backends. Global TUN uses + # SingBox auto_redirect programs an `inet sing-box` nftables table. + nftables = lib.mkIf ( + globalTun.enable + || globalTproxy.enable + || perAppRoutingTun.enable + || perAppRoutingTproxy.enable + || perAppZapretEnabled + ) true; - users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) { - "${userControlCfg.group}" = { }; - }; + # Inbound listeners are reached from outside, so their ports have to be open. + firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) { + allowedTCPPorts = proxyInboundFirewallPorts; + allowedUDPPorts = proxyInboundFirewallUdpPorts; + }; - security.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. - security.polkit.extraConfig = lib.mkMerge [ - (lib.mkIf (cfg.enable && cfg.gui.enable) ( - lib.mkAfter '' + groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) [ + userControlCfg.group + ]; + + 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. + 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") { @@ -191,10 +181,8 @@ lib.mkMerge [ } return null; }); - '' - )) - (lib.mkIf (cfg.enable && userControlEnabled) ( - lib.mkAfter '' + '') + (lib.mkIf (cfg.enable && userControlEnabled) '' polkit.addRule(function(action, subject) { if (!subject.isInGroup("${userControlCfg.group}")) { return null; @@ -209,50 +197,60 @@ lib.mkMerge [ return null; }); - '' - )) - ]; + '') + ]; - # Spool dirs for outbounds and subscriptions added at runtime. Setgid so the - # files proxy-ctl drops here inherit the group; without the outbounds scope - # only root writes them. tmpfiles rather than the start scripts, so the group can add an - # outbound before the proxy has ever run. - systemd.tmpfiles.rules = lib.mkIf (cfg.enable && proxyEnabled) ( - map - ( - dir: - "d ${dir} ${ - if userControlAllows "outbounds" then "2770 root ${userControlCfg.group}" else "0700 root root" - } -" - ) - [ - constants.runtimeOutboundsDir - constants.runtimeSubscriptionsDir - ] - ); + # Spool dirs for outbounds and subscriptions added at runtime. Setgid so the + # files proxy-ctl drops here inherit the group; without the outbounds scope + # only root writes them. tmpfiles rather than the start scripts, so the group can add an + # outbound before the proxy has ever run. + tmpfiles = lib.mkIf (cfg.enable && proxyEnabled) ( + map + ( + dir: + "d ${dir} ${ + if userControlAllows "outbounds" then + "2770 root ${userControlCfg.group}" + else if constants.privileged then + "0700 root root" + else + "0700 - -" + } -" + ) + [ + constants.runtimeOutboundsDir + constants.runtimeSubscriptionsDir + ] + ); - systemd.user.services = lib.mkMerge [ - (mkNamedUnits userServiceEntries) - (lib.mkIf (cfg.gui.enable && cfg.gui.autostart) { - # Starts hidden in the tray with every graphical session. - proxy-suite-gui = { - description = "Proxy Suite GUI (tray icon)"; - wantedBy = [ "graphical-session.target" ]; - partOf = [ "graphical-session.target" ]; - after = [ "graphical-session.target" ]; - unitConfig.ConditionEnvironment = [ - "|WAYLAND_DISPLAY" - "|DISPLAY" - ]; - serviceConfig = { - ExecStart = "${control.proxyCtl.gui}/bin/proxy-suite-gui --hidden"; - Restart = "on-failure"; - RestartSec = 3; + userServices = lib.mkMerge [ + (mkNamedUnits userServiceEntries) + (lib.mkIf (cfg.gui.enable && cfg.gui.autostart) { + # Starts hidden in the tray with every graphical session. + proxy-suite-gui = { + description = "Proxy Suite GUI (tray icon)"; + wantedBy = [ "graphical-session.target" ]; + partOf = [ "graphical-session.target" ]; + after = [ "graphical-session.target" ]; + unitConfig.ConditionEnvironment = [ + "|WAYLAND_DISPLAY" + "|DISPLAY" + ]; + serviceConfig = { + ExecStart = "${control.proxyCtl.gui}/bin/proxy-suite-gui --hidden"; + Restart = "on-failure"; + RestartSec = 3; + }; }; - }; - }) - ]; + }) + ]; + services = mkNamedUnits systemServiceEntries; + + timers = mkNamedUnits timerEntries; + }; + } + { assertions = import ../service-assertions.nix { inherit lib cfg derived; tgWsProxyCfg = cfg.tgWsProxy; @@ -276,10 +274,6 @@ 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`" ); - - systemd.services = mkNamedUnits systemServiceEntries; - - systemd.timers = mkNamedUnits timerEntries; } # A certificate or key XRay cannot read is copied in at start (proxy-inbounds-scripts.nix), @@ -298,20 +292,20 @@ lib.mkMerge [ ); in lib.mkIf (cfg.enable && proxyInboundsEnabled && certFiles != [ ]) { - systemd.paths.proxy-suite-inbounds-certs = { + services.proxy-suite.internal.paths.proxy-suite-inbounds-certs = { description = "proxy-suite - watch the inbounds' TLS certificates for renewals"; wantedBy = [ "paths.target" ]; pathConfig.PathChanged = certFiles; }; - systemd.services.proxy-suite-inbounds-certs = { + services.proxy-suite.internal.services.proxy-suite-inbounds-certs = { description = "proxy-suite - restart the inbounds onto a renewed certificate"; serviceConfig.Type = "oneshot"; script = '' # XRay reloads the files it reads itself; only copies go stale. - [ -d /run/proxy-suite-inbounds/tls ] || exit 0 + [ -d ${constants.runtimeDir}/proxy-suite-inbounds/tls ] || exit 0 # A renewal writes the chain and the key one after the other. sleep 10 - ${pkgs.systemd}/bin/systemctl try-restart proxy-suite-inbounds.service + ${constants.systemctl} try-restart proxy-suite-inbounds.service ''; }; } diff --git a/modules/proxy-suite/service/per-app-routing.nix b/modules/proxy-suite/service/per-app-routing.nix index c34043c..0929179 100644 --- a/modules/proxy-suite/service/per-app-routing.nix +++ b/modules/proxy-suite/service/per-app-routing.nix @@ -32,6 +32,7 @@ let perAppZapretSliceName = "proxy-suite-per-app-zapret.slice"; profiles = import ./per-app-routing/profiles.nix { + inherit (constants) runtimeDir; inherit lib pkgs diff --git a/modules/proxy-suite/service/per-app-routing/profiles.nix b/modules/proxy-suite/service/per-app-routing/profiles.nix index b0a27da..af72d63 100644 --- a/modules/proxy-suite/service/per-app-routing/profiles.nix +++ b/modules/proxy-suite/service/per-app-routing/profiles.nix @@ -7,6 +7,7 @@ perAppRoutingTun, perAppRoutingTproxy, perAppZapretCfg, + runtimeDir, }: let @@ -55,7 +56,7 @@ let proxychainsConfigFile = if localProxyAuthEnabled then - "/run/proxy-suite-socks/proxychains.conf" + "${runtimeDir}/proxy-suite-socks/proxychains.conf" else pkgs.writeText "proxy-suite-per-app" '' strict_chain diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index f86af6d..64b1453 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -24,7 +24,7 @@ }: let - runtimeDir = "/run/proxy-suite-inbounds"; + runtimeDir = "${constants.runtimeDir}/proxy-suite-inbounds"; linksFile = "${runtimeDir}/links.json"; subscriptionsFile = "${runtimeDir}/subscriptions.json"; subsCfg = proxyInboundsCfg.subscriptions; @@ -108,8 +108,9 @@ let printf '%s' "$body" > "$SUB_DIR.new/$token" done chmod -R u=rwX,g=rX,o= "$SUB_DIR.new" - ${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 + ${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''} rm -rf "$SUB_DIR" mv "$SUB_DIR.new" "$SUB_DIR" ${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}" @@ -163,10 +164,10 @@ let while IFS= read -r source; do [ -n "$source" ] || continue if ! ${runXray} ${pkgs.coreutils}/bin/test -r "$source"; then - [ -d "$CERT_DIR" ] || install -d -m 0750 -g ${constants.serviceUser} "$CERT_DIR" + [ -d "$CERT_DIR" ] || install -d -m 0750 ${constants.ifPrivileged "-g ${constants.serviceUser} "}"$CERT_DIR" index=$((index + 1)) copy="$CERT_DIR/$index-$(basename "$source")" - install -m 0640 -g ${constants.serviceUser} "$source" "$copy" + install -m 0640 ${constants.ifPrivileged "-g ${constants.serviceUser} "}"$source" "$copy" echo "proxy-suite: ${constants.serviceUser} cannot read $source; XRay uses a copy until the next restart" >&2 ${jq} --arg from "$source" --arg to "$copy" ' (.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile) @@ -187,7 +188,7 @@ let '' else '' - ${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp" + ${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"''} chmod 640 "$RUNTIME_DIR/config.json.tmp" '' } diff --git a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix index af87f16..29e2366 100644 --- a/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix +++ b/modules/proxy-suite/service/script-blocks/hybrid-runtime-helpers.nix @@ -25,13 +25,13 @@ lib.optionalString hybridEnabled '' local batch batch=$(${jq} -c \ --argjson base "$XRAY_SIDECAR_NEXT_PORT" \ - --argjson mark ${toString xraySidecarRoutingMark} ' + --argjson mark ${if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark} ' to_entries | map( ($base + .key) as $port | ("proxy-suite-xray-" + ($port | tostring)) as $auth | .value.tag as $tag | {outbound: (.value - | .streamSettings.sockopt.mark = $mark + ${lib.optionalString (xraySidecarRoutingMark != null) "| .streamSettings.sockopt.mark = $mark"} | .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")), inbound: {tag: ($tag + "-inbound"), listen: "127.0.0.1", port: $port, protocol: "socks", settings: {auth: "password", udp: true, accounts: [{user: $auth, pass: $auth}]}}, diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index 9c35753..81ac6a7 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -160,7 +160,9 @@ let } _proxy_suite_parse_xray_url() { - ${parse "--backend xray" " --routing-mark ${toString xraySidecarRoutingMark}"} + ${parse "--backend xray" ( + lib.optionalString (xraySidecarRoutingMark != null) " --routing-mark ${toString xraySidecarRoutingMark}" + )} } '' else @@ -331,7 +333,7 @@ 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 -g ${constants.serviceUser} ${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY" + install -m 0640 ${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} @@ -357,7 +359,7 @@ let _proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source} ''; - # WARP and "singBox" AmneziaWG profiles run in a tunnel unit, which restarts them when the + # 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. mkTunnelOutboundBlock = unit: source: tag: port: diff --git a/modules/proxy-suite/service/script-blocks/subscriptions.nix b/modules/proxy-suite/service/script-blocks/subscriptions.nix index 247a48d..51129a0 100644 --- a/modules/proxy-suite/service/script-blocks/subscriptions.nix +++ b/modules/proxy-suite/service/script-blocks/subscriptions.nix @@ -10,6 +10,7 @@ hybridEnabled, mainBackend, backend, + stateDir, runtimeSubscriptionsDir, jq, python3, @@ -21,7 +22,7 @@ let subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend; subscriptionBackendArg = "--backend ${subscriptionBackend}"; - subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}"; + subscriptionCacheDir = "${stateDir}/subscriptions/${backend}"; mkSubscriptionUrlSource = sub: diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 2dc35f2..2f5e251 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -56,7 +56,7 @@ let pkgs.writeText "proxy-suite-core" localProxyAuth.password else null; - routeModeStateFile = "/run/proxy-suite/route-mode"; + routeModeStateFile = "${constants.runtimeDir}/proxy-suite/route-mode"; inherit (constants) pinnedOutboundFile runtimeOutboundsDir @@ -64,9 +64,9 @@ let outboundInventoryFile ; clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}"; - xrayLoglevelFile = "/run/proxy-suite/xray-loglevel"; - runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf"; - xraySidecarRoutingMark = globalTproxy.proxyMark; + xrayLoglevelFile = "${constants.runtimeDir}/proxy-suite/xray-loglevel"; + runtimeProxychainsConfig = "${constants.runtimeDir}/proxy-suite-socks/proxychains.conf"; + xraySidecarRoutingMark = if constants.privileged then globalTproxy.proxyMark else null; routingMarkJq = routingMark: @@ -78,6 +78,7 @@ let " | .routing_mark = ${toString routingMark}"; subscriptionScripts = import ./script-blocks/subscriptions.nix { + inherit (constants) stateDir; inherit lib pkgs @@ -220,6 +221,7 @@ let proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile; controlScripts = import ./control-scripts.nix { + inherit (constants) systemctl; inherit lib pkgs diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index 973f485..a529445 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -42,7 +42,7 @@ let autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; - inherit (constants) serviceUser; + inherit (constants) serviceUser ifPrivileged; }; runBackend = constants.runAsServiceUser pkgs constants.backendCaps; userControlGroup = lib.escapeShellArg userControlCfg.group; @@ -136,7 +136,7 @@ let ${lib.escapeShellArg localProxyAuth.username} \ "$LOCAL_PROXY_PASSWORD" } > "${runtimeProxychainsConfig}" - ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}" + ${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"''} chmod 640 "${runtimeProxychainsConfig}" ''; @@ -258,7 +258,7 @@ let ${ if userControlCfg.enable || localProxyAuthEnabled then '' - ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP" + ${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP"''} chmod 640 "$ENDPOINTS_TMP" '' else @@ -358,14 +358,14 @@ let '' else '' - ${chgrp} ${constants.serviceUser} "$backend_config" + ${constants.ifPrivileged ''${chgrp} ${constants.serviceUser} "$backend_config"''} chmod 640 "$backend_config" '' } done FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json") if [ -n "$FAKE_IP_CACHE" ]; then - install -d -m 0700 -o ${constants.serviceUser} -g ${constants.serviceUser} "$(dirname "$FAKE_IP_CACHE")" + install -d -m 0700 ${constants.ifPrivileged "-o ${constants.serviceUser} -g ${constants.serviceUser} "}"$(dirname "$FAKE_IP_CACHE")" fi ${ @@ -409,9 +409,10 @@ let ''; startSocks = mkStartScript { - runtimeDir = "/run/proxy-suite-socks"; + runtimeDir = "${constants.runtimeDir}/proxy-suite-socks"; configFile = tproxyFile; - routingMark = globalTproxy.proxyMark; + # Rootless hosts cannot set SO_MARK, and have no TProxy rules to escape anyway. + routingMark = if constants.privileged then globalTproxy.proxyMark else null; enableLocalProxyAuth = localProxyAuthEnabled; # TProxy takes the system resolver's own upstream queries too, so a proxy server's name # has to resolve inside XRay, as under the TUN. @@ -425,7 +426,7 @@ let }; startTun = mkStartScript { - runtimeDir = "/run/proxy-suite-tun"; + runtimeDir = "${constants.runtimeDir}/proxy-suite-tun"; configFile = tunFile; routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null; xrayTunDnsRuntime = pureXrayEnabled; @@ -436,7 +437,7 @@ let }; startPerAppTun = mkStartScript { - runtimeDir = "/run/proxy-suite-per-app-tun"; + runtimeDir = "${constants.runtimeDir}/proxy-suite-per-app-tun"; configFile = perAppTunFile; routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null; xrayTunDnsRuntime = pureXrayEnabled; diff --git a/modules/proxy-suite/ssh-proxy.nix b/modules/proxy-suite/ssh-proxy.nix index 4be1eeb..9ab766b 100644 --- a/modules/proxy-suite/ssh-proxy.nix +++ b/modules/proxy-suite/ssh-proxy.nix @@ -40,7 +40,7 @@ let ''; in { - systemd.services.proxy-suite-ssh-proxy = { + services.proxy-suite.internal.services.proxy-suite-ssh-proxy = { description = "SSH dynamic SOCKS5 proxy"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; diff --git a/modules/proxy-suite/tg-ws-proxy.nix b/modules/proxy-suite/tg-ws-proxy.nix index dd2ad6a..a673583 100644 --- a/modules/proxy-suite/tg-ws-proxy.nix +++ b/modules/proxy-suite/tg-ws-proxy.nix @@ -88,7 +88,7 @@ in # For the checks: ExecStartPre/ExecStopPost carry these behind "+". inherit bypassUpScript bypassDownScript; - config.systemd.services.proxy-suite-tg-ws-proxy = { + config.services.proxy-suite.internal.services.proxy-suite-tg-ws-proxy = { description = "Telegram MTProto WebSocket proxy"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; diff --git a/modules/proxy-suite/warp.nix b/modules/proxy-suite/warp.nix index 4f2decd..663ad31 100644 --- a/modules/proxy-suite/warp.nix +++ b/modules/proxy-suite/warp.nix @@ -86,16 +86,20 @@ let ''; inherit (import ./wg-tunnel.nix { inherit lib pkgs cfg derived; }) mkTunnel; + viaAmneziaWg = builtins.elem w.asOutbound [ + "userspace" + "interface" + ]; in { - services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") { + services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) { warp = { configFile = w.profilePath; - asOutbound = lib.mkIf (w.asOutbound == "interface") "interface"; + asOutbound = lib.mkIf viaAmneziaWg w.asOutbound; }; }; - systemd.services = lib.mkMerge [ + services.proxy-suite.internal.services = lib.mkMerge [ (lib.mkIf (w.asOutbound == "singBox") { proxy-suite-warp-tunnel = mkTunnel { description = "proxy-suite - Cloudflare WARP tunnel behind the warp outbound"; @@ -129,7 +133,7 @@ in RestartSec = 30; StateDirectory = "proxy-suite/warp"; StateDirectoryMode = "0700"; - WorkingDirectory = "/var/lib/proxy-suite/warp"; + WorkingDirectory = "${derived.constants.stateDir}/warp"; UMask = "0077"; LoadCredential = lib.optional (cfg.proxy.enable && withProxyAuth) "proxy-password:${passwordSource}"; ExecStart = registerScript; @@ -137,7 +141,7 @@ in }; # Only pulls registration in: a simple unit gives the profile no ordering guarantee. - proxy-suite-awg-warp = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") { + proxy-suite-awg-warp = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) { wants = [ "proxy-suite-warp.service" ]; }; }) diff --git a/modules/proxy-suite/wg-tunnel.nix b/modules/proxy-suite/wg-tunnel.nix index 28ed4d3..025d900 100644 --- a/modules/proxy-suite/wg-tunnel.nix +++ b/modules/proxy-suite/wg-tunnel.nix @@ -1,6 +1,6 @@ -# A WireGuard profile as a sing-box endpoint in its own process, behind a loopback SOCKS -# listener the proxy outbound dials: the WARP tunnel and AmneziaWG profiles with -# asOutbound = "singBox". +# A WireGuard profile in its own process, behind a loopback SOCKS listener the proxy +# outbound dials: the WARP tunnel and AmneziaWG profiles with asOutbound = "singBox" +# (a sing-box endpoint) or "userspace" (wireproxy, which keeps AmneziaWG's obfuscation). { lib, pkgs, @@ -9,7 +9,7 @@ }: let - inherit (derived.constants) serviceUser runAsServiceUser; + inherit (derived.constants) serviceUser runAsServiceUser ifPrivileged; scriptsDir = builtins.path { name = "proxy-suite-scripts"; path = ../../scripts; @@ -24,74 +24,75 @@ let server = upstream.address; server_port = upstream.port; }; - mark = cfg.proxy.tproxy.proxyMark; + # 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; probe = port: url: '' ${pkgs.curl}/bin/curl -s --noproxy "" -x socks5h://127.0.0.1:${toString port} -m "$timeout" \ -o /dev/null ${url}''; - # Some lines drop a share of fresh handshakes for good, and sing-box retries on the same - # source port forever. A new process binds a new port, so the watchdog exits when the peer - # stops answering and systemd starts the tunnel again. A healthy handshake takes a fraction - # of a second, so a start gets 15 seconds; a running tunnel gets three misses. The - # "direct-in" listener reaches Cloudflare through the uplink with the backend's mark (not - # urlTest.url, which is picked to be blocked here): when that fails too, the tunnel could - # not work from a new port either. + # 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 + # the peer stops answering and the service manager starts the tunnel again. A healthy + # handshake takes a fraction of a second, so a start gets 15 seconds; a running tunnel + # gets three misses. 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. mkWatchdog = { tag, + command, tunnelPort, directPort, }: pkgs.writeShellScript "proxy-suite-wg-tunnel" '' set -uo pipefail - ${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json" & - singbox=$! + ${command} & + tunnel=$! healthy=0 failures=0 uplink_down=0 since=0 while sleep $(( healthy ? 10 : 2 )); do - kill -0 "$singbox" 2>/dev/null || { wait "$singbox"; exit 1; } + 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=1 failures=0 uplink_down=0 continue fi - if ! ${probe directPort "https://1.1.1.1/cdn-cgi/trace"}; then - (( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging ${tag}" >&2 - uplink_down=1 failures=0 since=$SECONDS - continue - fi + ${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 + uplink_down=1 failures=0 since=$SECONDS + continue + fi + ''} uplink_down=0 if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then echo "proxy-suite: ${tag} is not answering; restarting the tunnel on a new source port" >&2 - kill "$singbox" - wait "$singbox" + kill "$tunnel" + wait "$tunnel" exit 1 fi done ''; - # `profile` is a shell snippet, run as root, that sets $profile to the WireGuard .conf. - mkTunnel = + markArg = flag: lib.optionalString (mark != null) " ${flag} ${toString mark}"; + + # The profile is a secret, so it is converted at start, by root on a privileged host, + # rather than baked into the store; the engine itself runs as ${serviceUser}. + singBoxEngine = { - description, - unit, tag, - profile, tunnelPort, directPort, }: - let - tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" '' - set -euo pipefail - ${profile} - - # The profile is a secret, so it is converted here, as root, rather than baked into - # the store; sing-box itself runs as ${serviceUser}. - endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag} --routing-mark ${toString mark} < "$profile") + { + convert = '' + endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag}${markArg "--routing-mark"} < "$profile") (umask 027 && ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{ log: {level: "warn"}, dns: {servers: [ @@ -107,12 +108,62 @@ let {type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString tunnelPort}}, {type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString directPort}} ], - outbounds: [{type: "direct", tag: "direct", routing_mark: ${toString mark}}], + outbounds: [{type: "direct", tag: "direct"${ + lib.optionalString (mark != null) ", routing_mark: ${toString mark}" + }}], endpoints: [$ep + {domain_resolver: "local"}] }' > "$RUNTIME_DIRECTORY/config.json") - ${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/config.json" + ''; + config = "config.json"; + command = ''${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json"''; + inherit directPort; + }; - exec ${runAsServiceUser pkgs [ "net_admin" ]} ${mkWatchdog { inherit tag tunnelPort directPort; }} + wireproxyEngine = + { tunnelPort, ... }: + { + convert = '' + ${pkgs.python3}/bin/python3 ${scriptsDir}/amneziawg_config.py --config "$profile" \ + --output "$RUNTIME_DIRECTORY/wireproxy.conf" \ + --wireproxy 127.0.0.1:${toString tunnelPort}${markArg "--outbound-fwmark"} + ''; + config = "wireproxy.conf"; + command = ''${cfg.amneziaWg.wireproxyPackage}/bin/wireproxy -c "$RUNTIME_DIRECTORY/wireproxy.conf"''; + directPort = null; + }; + + # `profile` is a shell snippet, run as root on a privileged host, that sets $profile to + # the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort. + mkTunnel = + { + description, + unit, + tag, + profile, + tunnelPort, + directPort ? null, + engine ? "singBox", + }: + let + chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) { + inherit tag tunnelPort directPort; + }; + tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" '' + set -euo pipefail + ${profile} + + ${chosen.convert} + ${ifPrivileged '' + ${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/${chosen.config}" + ${pkgs.coreutils}/bin/chmod g+r "$RUNTIME_DIRECTORY/${chosen.config}" + ''} + + exec ${runAsServiceUser pkgs [ "net_admin" ]} ${ + mkWatchdog { + inherit tag tunnelPort; + inherit (chosen) command directPort; + } + } ''; in { diff --git a/modules/proxy-suite/zapret.nix b/modules/proxy-suite/zapret.nix index 1ebbe64..620436a 100644 --- a/modules/proxy-suite/zapret.nix +++ b/modules/proxy-suite/zapret.nix @@ -79,46 +79,50 @@ in { assertions = zapretPackages.assertions; - environment.systemPackages = lib.mkBefore ( + services.proxy-suite.internal.earlyPackages = ( lib.optionals zapretCfg.enable [ globalZapretPackage ] ++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ] ); - systemd.services.proxy-suite-zapret = lib.mkIf zapretCfg.enable (mkOneshotService { - description = "zapret DPI bypass"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - conflicts = awgServiceNames; - wantedBy = [ "multi-user.target" ]; - preStart = zapretCommonPreStart globalZapretPackage; - runtimeDirectory = "proxy-suite-zapret"; - execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start"; - execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop"; - extraServiceConfig = { - ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart"; - Environment = globalZapretEnv; - }; - }); + services.proxy-suite.internal.services.proxy-suite-zapret = + lib.mkIf zapretCfg.enable + (mkOneshotService { + description = "zapret DPI bypass"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + conflicts = awgServiceNames; + wantedBy = [ "multi-user.target" ]; + preStart = zapretCommonPreStart globalZapretPackage; + runtimeDirectory = "proxy-suite-zapret"; + execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start"; + execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop"; + extraServiceConfig = { + ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart"; + Environment = globalZapretEnv; + }; + }); - systemd.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 = [ - "proxy-suite-tproxy.service" - "proxy-suite-tun.service" - ] - ++ 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; - }); + 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 = [ + "proxy-suite-tproxy.service" + "proxy-suite-tun.service" + ] + ++ 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; + }); - systemd.services.proxy-suite-zapret-vm-exempt = + services.proxy-suite.internal.services.proxy-suite-zapret-vm-exempt = lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable) ( mkOneshotService { diff --git a/modules/proxy-suite/zapret2.nix b/modules/proxy-suite/zapret2.nix index 1bac874..e784aa0 100644 --- a/modules/proxy-suite/zapret2.nix +++ b/modules/proxy-suite/zapret2.nix @@ -103,50 +103,56 @@ let ''; in { - environment.systemPackages = lib.mkBefore [ runtime.package ]; + services.proxy-suite.internal.earlyPackages = [ runtime.package ]; - systemd.services.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.service; - systemd.timers.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.timer; + services.proxy-suite.internal.services.proxy-suite-zapret2-cutoff = + lib.mkIf cutoffCfg.enable cutoff.service; + services.proxy-suite.internal.timers.proxy-suite-zapret2-cutoff = + lib.mkIf cutoffCfg.enable cutoff.timer; - systemd.services.proxy-suite-zapret = lib.mkIf zapretCfg.enable (mkOneshotService { - description = "zapret2 DPI bypass"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - conflicts = awgServiceNames; - wantedBy = [ "multi-user.target" ]; - preStart = mkPreStart; - runtimeDirectory = "proxy-suite-zapret"; - stateDirectory = "proxy-suite"; - execStart = "${runtime.initScript} start"; - execStop = "${runtime.initScript} stop"; - extraServiceConfig = { - ExecReload = "${runtime.initScript} restart"; - Environment = runtime.mkEnv { - runtime = globalRuntime; - pidDir = "/run/proxy-suite-zapret"; - }; - }; - }); + services.proxy-suite.internal.services.proxy-suite-zapret = + lib.mkIf zapretCfg.enable + (mkOneshotService { + description = "zapret2 DPI bypass"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + conflicts = awgServiceNames; + wantedBy = [ "multi-user.target" ]; + preStart = mkPreStart; + runtimeDirectory = "proxy-suite-zapret"; + stateDirectory = "proxy-suite"; + execStart = "${runtime.initScript} start"; + execStop = "${runtime.initScript} stop"; + extraServiceConfig = { + ExecReload = "${runtime.initScript} restart"; + Environment = runtime.mkEnv { + runtime = globalRuntime; + pidDir = "/run/proxy-suite-zapret"; + }; + }; + }); - systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService { - description = "proxy-suite per-app-routing zapret2 backend"; - after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; - conflicts = [ - "proxy-suite-tproxy.service" - "proxy-suite-tun.service" - ] - ++ awgServiceNames; - preStart = mkPreStart; - runtimeDirectory = "proxy-suite-per-app-zapret"; - stateDirectory = "proxy-suite"; - execStart = "${runtime.initScript} start"; - execStop = "${runtime.initScript} stop"; - execStartPre = "${perAppZapretMarkUpScript}"; - execStopPost = "${perAppZapretMarkDownScript}"; - extraServiceConfig.Environment = runtime.mkEnv { - runtime = perAppRuntime; - pidDir = "/run/proxy-suite-per-app-zapret"; - }; - }); + services.proxy-suite.internal.services.proxy-suite-per-app-zapret = + lib.mkIf perAppZapretCfg.enable + (mkOneshotService { + description = "proxy-suite per-app-routing zapret2 backend"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + conflicts = [ + "proxy-suite-tproxy.service" + "proxy-suite-tun.service" + ] + ++ awgServiceNames; + preStart = mkPreStart; + runtimeDirectory = "proxy-suite-per-app-zapret"; + stateDirectory = "proxy-suite"; + execStart = "${runtime.initScript} start"; + execStop = "${runtime.initScript} stop"; + execStartPre = "${perAppZapretMarkUpScript}"; + execStopPost = "${perAppZapretMarkDownScript}"; + extraServiceConfig.Environment = runtime.mkEnv { + runtime = perAppRuntime; + pidDir = "/run/proxy-suite-per-app-zapret"; + }; + }); } diff --git a/nix/checks.nix b/nix/checks.nix index d030f4e..10d3a85 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -2,6 +2,7 @@ system, nixpkgs, proxySuiteModule, + proxySuiteModules, generatedOptionsDoc, generatedReadmeDoc, zapret, @@ -44,11 +45,20 @@ let amneziaWgRuntime = import ./checks/amnezia-wg-runtime.nix { inherit pkgs nixpkgs proxySuiteModule; }; + hostChecks = import ./checks/hosts.nix { + inherit pkgs proxySuiteModules; + inherit (checkLib) mkTProxyConfig mkInboundsConfig; + }; proxyInboundsRuntime = import ./checks/proxy-inbounds-runtime.nix { inherit pkgs proxySuiteModule; }; in moduleSuiteChecks +// { + proxy-suite-hosts = builtins.seq (builtins.deepSeq hostChecks.assertions true) ( + pkgs.writeText "proxy-suite-hosts-check" "ok" + ); +} // pkgs.lib.optionalAttrs (system == "x86_64-linux") { amneziawg-runtime = amneziaWgRuntime; proxy-inbounds-runtime = proxyInboundsRuntime; diff --git a/nix/checks/hosts.nix b/nix/checks/hosts.nix new file mode 100644 index 0000000..6f6d697 --- /dev/null +++ b/nix/checks/hosts.nix @@ -0,0 +1,224 @@ +# The home-manager, system-manager and nix-on-droid adapters, evaluated against stubs of +# the options each host framework declares: the frameworks stay out of the flake lock, +# and the adapters only use option names they share with these stubs. +{ + pkgs, + proxySuiteModules, + mkTProxyConfig, + mkInboundsConfig, +}: + +let + lib = pkgs.lib; + inherit (lib) mkOption types; + + stub = type: default: mkOption { inherit type default; }; + anyAttrs = stub (types.attrsOf types.anything) { }; + packages = stub (types.listOf types.package) [ ]; + strings = stub (types.listOf types.str) [ ]; + etc = stub (types.attrsOf ( + types.submodule { + freeformType = types.attrsOf types.anything; + options.text = stub (types.nullOr types.lines) null; + } + )) { }; + + common = { + options = { + assertions = stub (types.listOf types.unspecified) [ ]; + warnings = strings; + }; + config._module.args.pkgs = pkgs; + }; + + hostStubs = { + homeManager.options = { + home.packages = packages; + xdg.stateHome = stub types.str "/home/u/.local/state"; + xdg.cacheHome = stub types.str "/home/u/.cache"; + systemd.user = { + services = anyAttrs; + timers = anyAttrs; + paths = anyAttrs; + tmpfiles.rules = strings; + }; + }; + + systemManager.options = { + systemd = + let + units = stub (types.attrsOf (types.submodule { freeformType = types.attrsOf types.anything; })) { }; + in + { + services = units; + timers = units; + paths = units; + tmpfiles.rules = strings; + }; + environment.systemPackages = packages; + environment.etc = etc; + users.users = anyAttrs; + users.groups = anyAttrs; + networking.enableIPv6 = stub types.bool true; + networking.firewall.allowedTCPPorts = stub (types.listOf types.port) [ ]; + networking.firewall.allowedUDPPorts = stub (types.listOf types.port) [ ]; + }; + + nixOnDroid.options = { + user.home = stub types.str "/data/data/com.termux.nix/files/home"; + environment.packages = packages; + environment.etc = etc; + build.activationAfter = stub (types.attrsOf types.str) { }; + }; + }; + + evalHost = + host: modules: + lib.evalModules { + modules = [ + common + hostStubs.${host} + proxySuiteModules.${host} + ] + ++ modules; + }; + failedAssertions = + 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); + + proxy = { + enable = true; + listener.port = 1080; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + + # What a rootless host can run. + rootlessSettings = { + services.proxy-suite = { + enable = true; + inherit proxy; + tgWsProxy = { + enable = true; + secretFile = "/run/secrets/tg"; + }; + warp = { + enable = true; + asOutbound = "singBox"; + }; + perAppRouting = { + enable = true; + proxychains.enable = true; + }; + inbounds = { + enable = true; + listeners.vless = { + type = "vless"; + port = 8443; + users = [ { uuidFile = "/run/secrets/uuid"; } ]; + tls.certificateFile = "/c"; + tls.keyFile = "/k"; + }; + }; + }; + }; + + homeManager = evalHost "homeManager" [ rootlessSettings ]; + hmCfg = homeManager.config; + hmSocksConfig = mkTProxyConfig homeManager; + hmInboundsConfig = mkInboundsConfig homeManager; + + systemManager = evalHost "systemManager" [ + { + services.proxy-suite = { + enable = true; + proxy = proxy // { + tproxy.enable = true; + }; + gui.enable = true; + userControl.enable = true; + }; + } + ]; + smCfg = systemManager.config; + + nixOnDroid = evalHost "nixOnDroid" [ rootlessSettings ]; + nodCfg = nixOnDroid.config; + + rejects = + host: settings: message: + lib.any (lib.hasInfix message) ( + failedAssertions ( + evalHost host [ + rootlessSettings + { services.proxy-suite = settings; } + ] + ) + ); +in +{ + assertions = [ + ( + assert failedAssertions homeManager == [ ]; + assert hmCfg.services.proxy-suite.host.serviceManager == "systemd-user"; + assert lib.hasPrefix "/home/u/.local/state/" hmCfg.services.proxy-suite.host.stateDir; + assert hmCfg.systemd.user.services ? proxy-suite-socks; + assert hmCfg.systemd.user.services ? proxy-suite-inbounds; + assert forced hmCfg.systemd.user.services; + # No setpriv on a user manager: nothing to drop to. + assert + !(lib.hasInfix "setpriv" ( + toString hmCfg.systemd.user.services.proxy-suite-socks.Service.ExecStart + )); + true + ) + ( + # Rootless, the socks unit only listens: no TProxy inbound, no SO_MARK. + assert lib.any (inbound: inbound.type == "mixed") hmSocksConfig.inbounds; + assert !(lib.any (inbound: inbound.type == "tproxy") hmSocksConfig.inbounds); + assert !(lib.any (outbound: outbound ? routing_mark) hmSocksConfig.outbounds); + assert !(lib.any (outbound: outbound ? routing_mark) (hmInboundsConfig.outbounds or [ ])); + true + ) + ( + assert failedAssertions systemManager == [ ]; + assert smCfg.services.proxy-suite.host.privileged; + assert + smCfg.systemd.services.proxy-suite-socks.serviceConfig.SyslogIdentifier == "proxy-suite-socks"; + assert smCfg.systemd.services ? proxy-suite-tproxy; + assert smCfg.environment.etc ? "polkit-1/rules.d/50-proxy-suite.rules"; + assert smCfg.environment.etc ? "systemd/user/proxy-suite-gui.service"; + assert forced smCfg.systemd.services; + true + ) + ( + assert failedAssertions nixOnDroid == [ ]; + assert nodCfg.services.proxy-suite.host.serviceManager == "supervisor"; + assert lib.hasSuffix "/bin/proxy-suitectl" nodCfg.services.proxy-suite.host.systemctl; + assert lib.any (p: lib.getName p == "proxy-suitectl") nodCfg.environment.packages; + assert lib.hasInfix "proxy-suitectl boot" nodCfg.build.activationAfter.proxySuite; + assert lib.hasInfix "proxy-suitectl ensure" nodCfg.environment.etc.profile.text; + assert forced nodCfg.build.activationAfter.proxySuite; + true + ) + ( + assert rejects "homeManager" { proxy.tproxy.enable = true; } "proxy.tproxy needs root"; + assert rejects "homeManager" { proxy.tun.enable = true; } "proxy.tun needs root"; + assert rejects "homeManager" { userControl.enable = true; } "userControl has nothing to grant"; + assert rejects "nixOnDroid" { zapret.enable = true; } "zapret needs root"; + assert rejects "nixOnDroid" { + perAppRouting.zapret.enable = true; + } "perAppRouting.zapret needs root"; + assert rejects "nixOnDroid" { gui.enable = true; } "the GUI needs a desktop session"; + assert rejects "nixOnDroid" { + inbounds.listeners.vless.port = lib.mkForce 443; + } "inbounds.listeners.vless.port = 443 is a privileged port"; + true + ) + ]; +} diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index 3e25d5d..d5bfcdb 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -444,6 +444,14 @@ touch "$out" ''; + # proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped. + proxy-suite-supervisor-unit = + pkgs.runCommand "proxy-suite-supervisor-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } '' + export PYTHONDONTWRITEBYTECODE=1 HOME="$TMPDIR" + python ${../../pkgs/proxy-ctl}/test_proxy_supervisor.py + touch "$out" + ''; + # proxy_export: the running config made portable, and sing-box still accepts it. proxy-export-unit = pkgs.runCommand "proxy-suite-proxy-export-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } '' diff --git a/nix/checks/route-mode.nix b/nix/checks/route-mode.nix index c745a41..3faea31 100644 --- a/nix/checks/route-mode.nix +++ b/nix/checks/route-mode.nix @@ -62,6 +62,7 @@ let mkSubscriptionFetchBlock = _: ""; runtimeSubscriptionsFetchBlock = ""; jq = "${pkgs.jq}/bin/jq"; + systemctl = "${pkgs.systemd}/bin/systemctl"; }; routeModeSetterScript = generated.readDerivation routeModeControlScripts.setRouteModeScript; pinSetterScript = generated.readDerivation routeModeControlScripts.pinOutboundScript; diff --git a/pkgs/amneziawg.nix b/pkgs/amneziawg.nix index 38a7618..729a5ec 100644 --- a/pkgs/amneziawg.nix +++ b/pkgs/amneziawg.nix @@ -9,4 +9,5 @@ patches = (old.patches or [ ]) ++ [ ./patches/amneziawg-go-random-trailers-transport.patch ]; }); kernelModule = kernelPackages: kernelPackages.amneziawg; + wireproxy = import ./wireproxy-awg.nix { inherit pkgs; }; } diff --git a/pkgs/default.nix b/pkgs/default.nix index 76690eb..87aa78d 100644 --- a/pkgs/default.nix +++ b/pkgs/default.nix @@ -3,6 +3,10 @@ let amneziaWg = import ./amneziawg.nix { inherit pkgs; }; mkTgWsProxy = _args: import ./tg-ws-proxy.nix { inherit pkgs; }; zapret2 = import ./zapret2.nix { inherit pkgs; }; + mkProxySuiteSupervisor = import ./proxy-suite-supervisor.nix { + lib = pkgs.lib; + inherit pkgs; + }; mkProxyCtl = import ./proxy-ctl.nix { lib = pkgs.lib; inherit pkgs; @@ -12,9 +16,11 @@ in inherit amneziaWg; amneziawg-tools = amneziaWg.tools; amneziawg-go = amneziaWg.userspace; + wireproxy-awg = amneziaWg.wireproxy; inherit mkTgWsProxy mkProxyCtl + mkProxySuiteSupervisor zapret2 ; tg-ws-proxy = mkTgWsProxy { }; diff --git a/pkgs/patches/wireproxy-awg-fwmark.patch b/pkgs/patches/wireproxy-awg-fwmark.patch new file mode 100644 index 0000000..8e85eba --- /dev/null +++ b/pkgs/patches/wireproxy-awg-fwmark.patch @@ -0,0 +1,40 @@ +diff --git a/config.go b/config.go +--- a/config.go ++++ b/config.go +@@ -32,6 +32,7 @@ + DNS []netip.Addr + MTU int + ListenPort *int ++ FwMark *int + CheckAlive []netip.Addr + CheckAliveInterval int + ASecConfig *ASecConfigType +@@ -296,6 +297,14 @@ + device.ListenPort = &value + } + ++ if sectionKey, err := section.GetKey("FwMark"); err == nil { ++ value, err := sectionKey.Int() ++ if err != nil { ++ return err ++ } ++ device.FwMark = &value ++ } ++ + checkAlive, err := parseNetIP(section, "CheckAlive") + if err != nil { + return err +diff --git a/wireguard.go b/wireguard.go +--- a/wireguard.go ++++ b/wireguard.go +@@ -54,6 +54,10 @@ + fmt.Fprintf(&request, "listen_port=%d\n", *conf.ListenPort) + } + ++ if conf.FwMark != nil { ++ fmt.Fprintf(&request, "fwmark=%d\n", *conf.FwMark) ++ } ++ + if conf.ASecConfig != nil { + aSecConfig := conf.ASecConfig + diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 46766da..9fb88e2 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -37,6 +37,12 @@ autoProxyEnabled, autoProxyStateDir, singBox, + stateDir ? "/var/lib/proxy-suite", + runtimeDir ? "/run", + serviceManager ? "systemd", + privileged ? "1", + # proxy-suitectl, when serviceManager is "supervisor". + supervisorCtl ? "", guiRefreshInterval ? 3, }: @@ -79,6 +85,13 @@ let AUTOPROXY_ENABLED = autoProxyEnabled; AUTOPROXY_STATE_DIR = autoProxyStateDir; SING_BOX = singBox; + STATE_DIR = stateDir; + RUNTIME_DIR = runtimeDir; + SERVICE_MANAGER = serviceManager; + PRIVILEGED = privileged; + } + // lib.optionalAttrs (supervisorCtl != "") { + SUPERVISOR_CTL = supervisorCtl; }; envFlags = lib.concatStringsSep " " ( lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 5f9a7ec..5ab4e93 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -165,8 +165,29 @@ def readable(path): return bool(path) and os.access(path, os.R_OK) +def privileged(): + """Whether the services run as root: off on rootless hosts (home-manager, nix-on-droid).""" + return env("PRIVILEGED", "1") == "1" + + +def service_manager(): + """What runs the units: systemd, systemd-user (home-manager), or supervisor (nix-on-droid).""" + return env("SERVICE_MANAGER", "systemd") + + +def state_dir(): + return env("STATE_DIR", "/var/lib/proxy-suite") + + +def runtime_dir(): + """The parent of the units' runtime directories (proxy-suite-socks, ...).""" + return env("RUNTIME_DIR", "/run") + + def ask_group(): """What lets a refused user in: root, or userControl's group with the scope for it.""" + if not privileged(): + return "check its owner and permissions" return f"join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo" @@ -212,8 +233,28 @@ def _exec(argv): die(f"proxy-ctl: {argv[0]}: {e.strerror}", 126 if isinstance(e, PermissionError) else 127) +def _manager_argv(tool, args): + """tool (systemctl, journalctl) with args, aimed at the manager that runs the units. + + Under systemd-user every unit is a user unit, so a --user of the caller's is redundant. + Without systemd (nix-on-droid), proxy-suitectl answers both. + """ + if service_manager() == "systemd-user": + return [tool, "--user", *(a for a in args if a != "--user")] + if service_manager() == "supervisor": + ctl = env("SUPERVISOR_CTL", "proxy-suitectl") + rest = [a for a in args if a != "--user"] + return [ctl, "journal", *rest] if tool == "journalctl" else [ctl, *rest] + return [tool, *args] + + def systemctl(*args, capture=False, quiet=False): - return _run(["systemctl", *args], capture=capture, quiet=quiet) + return _run(_manager_argv("systemctl", args), capture=capture, quiet=quiet) + + +def journal_hint(unit, count=None): + """The command that shows unit's log, for messages.""" + return " ".join(_manager_argv("journalctl", ["-u", unit, *(["-n", str(count)] if count else [])])) def must(*args): @@ -522,7 +563,7 @@ def _unit_states(units): """unit -> ActiveState for the units that exist, in one systemctl call.""" if not units: return {} - _, out = _run(["systemctl", "show", "--property=Id,LoadState,ActiveState", "--", *units], capture=True, quiet=True) + _, out = systemctl("show", "--property=Id,LoadState,ActiveState", "--", *units, capture=True, quiet=True) states = {} for unit, block in zip(units, out.strip().split("\n\n")): props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line) @@ -874,7 +915,7 @@ TEST_DOWNLOAD_SECONDS = 10 def _runtime_file(name): - return os.path.join(os.path.dirname(env("OUTBOUND_INVENTORY_FILE", "/run/proxy-suite-socks/outbounds.json")), name) + return os.path.join(os.path.dirname(env("OUTBOUND_INVENTORY_FILE", f"{runtime_dir()}/proxy-suite-socks/outbounds.json")), name) def _test_ping(endpoint, timeout=3): @@ -1156,8 +1197,8 @@ def cmd_unpin(*_): def _runtime_dir(kind): if kind == "outbound": - return env("RUNTIME_OUTBOUNDS_DIR", "/var/lib/proxy-suite/outbounds.d") - return env("RUNTIME_SUBS_DIR", "/var/lib/proxy-suite/subscriptions.d") + return env("RUNTIME_OUTBOUNDS_DIR", f"{state_dir()}/outbounds.d") + return env("RUNTIME_SUBS_DIR", f"{state_dir()}/subscriptions.d") def _runtime_hidden(kind): @@ -1275,7 +1316,7 @@ def _runtime_reload(): def _subscription_cache(tag): - return os.path.join(env("SUB_CACHE_DIR", "/var/lib/proxy-suite/subscriptions"), f"{tag}.json") + return os.path.join(env("SUB_CACHE_DIR", f"{state_dir()}/subscriptions"), f"{tag}.json") def _runtime_entry_verify(kind, tag): @@ -1413,7 +1454,7 @@ def _probe_paths(): def _probe_exits_file(): - return env("PROBE_EXITS_FILE", "/run/proxy-suite-socks/probe-exits.json") + return env("PROBE_EXITS_FILE", f"{runtime_dir()}/proxy-suite-socks/probe-exits.json") def _probe_site(url): @@ -1756,7 +1797,7 @@ def _reputation_by_tag(): def _autoproxy_dir(): - return env("AUTOPROXY_STATE_DIR", "/var/lib/proxy-suite/autoproxy") + return env("AUTOPROXY_STATE_DIR", f"{state_dir()}/autoproxy") def _require_autoproxy(): @@ -1924,10 +1965,10 @@ def cmd_proxy_learn(host="", *_): if systemctl("start", "proxy-suite-autoproxy-learn.service", quiet=True)[0]: sys.stdout.flush() print(f"The probe run failed. {host} is still queued and will be tried again at the next run.", file=sys.stderr) - die("Details: journalctl -u proxy-suite-autoproxy-learn -n 20") + die(f"Details: {journal_hint('proxy-suite-autoproxy-learn', 20)}") h = (_autoproxy_state(path).get("hosts") or {}).get(host) if h is None: - print("No verdict recorded; see: journalctl -u proxy-suite-autoproxy-learn") + print(f"No verdict recorded; see: {journal_hint('proxy-suite-autoproxy-learn')}") elif h.get("exit"): print(f"{_s(h.get('domain'))}: {_s(h.get('verdict'))} - routed via {_s(h['exit'])} from now on, no restart needed") else: @@ -1947,7 +1988,7 @@ def cmd_zapret(*args): def _zapret_state_dir(): - return env("ZAPRET_STATE_DIR", "/var/lib/proxy-suite/zapret2") + return env("ZAPRET_STATE_DIR", f"{state_dir()}/zapret2") def _zapret_auto_file(name): @@ -2074,7 +2115,7 @@ def cmd_zapret_cutoff(verb="status", *_): denied(path, "write") print("Probing this line; this takes a few minutes...") if systemctl("start", "proxy-suite-zapret2-cutoff.service")[0]: - die("The probe failed. Details: journalctl -u proxy-suite-zapret2-cutoff -n 30") + die(f"The probe failed. Details: {journal_hint('proxy-suite-zapret2-cutoff', 30)}") elif verb != "status": usage("zapret cutoff [status|probe]") @@ -2253,7 +2294,7 @@ def cmd_where(domain="", *_): local = " and ".join(sorted(live)) if env("INBOUNDS_ENABLED") == "1": - inbounds_path = "/run/proxy-suite-inbounds/config.json" + inbounds_path = f"{runtime_dir()}/proxy-suite-inbounds/config.json" if not readable(inbounds_path): _where_row("inbounds", f"routing is not readable - {ask_group()}") else: @@ -2474,7 +2515,7 @@ def _inbound_links(): def _inbound_server_json(tag): """The XRay inbound as the server runs it, secrets and all.""" - path = os.path.join(os.path.dirname(env("INBOUNDS_LINKS_FILE", "/run/proxy-suite-inbounds/links.json")), "config.json") + path = os.path.join(os.path.dirname(env("INBOUNDS_LINKS_FILE", f"{runtime_dir()}/proxy-suite-inbounds/links.json")), "config.json") if not os.path.isfile(path): die("No inbound config yet - is proxy-suite-inbounds running?") if not readable(path): @@ -2530,7 +2571,7 @@ def _inbound_stats(*args): days = rest.pop(0) if rest or kind not in STATS_KINDS or not re.fullmatch(r"[1-9][0-9]*", days): usage("inbounds stats [days] [--by user|inbound|outbound]") - path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json") + path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json") # Collect what XRay counted since the last run first; root and userControl # members may, anyone else reads what the timer last wrote. systemctl("--no-ask-password", "start", "proxy-suite-inbound-stats.service", quiet=True) @@ -2581,7 +2622,7 @@ def _inbound_presence(): except (ValueError, AttributeError): die("Unexpected answer from the inbounds' stats API.") # As the timer last wrote it: the API already told who is online now. - path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json") + path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json") seen = (read_json(path).get("seen") or {}) if readable(path) else {} # Users nobody has seen yet, when the links say who exists. path = env("INBOUNDS_LINKS_FILE") @@ -2626,7 +2667,7 @@ def _inbound_subscriptions(*args): qr = True else: user = arg - path = env("INBOUNDS_SUBS_FILE", "/run/proxy-suite-inbounds/subscriptions.json") + path = env("INBOUNDS_SUBS_FILE", f"{runtime_dir()}/proxy-suite-inbounds/subscriptions.json") base = env("INBOUNDS_SUB_BASE_URL") if not os.path.isfile(path): die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?") @@ -2699,9 +2740,9 @@ ALIASES = { def cmd_logs(*units): if units: # One -u per unit: a bare second name would be taken as a journal match. - _exec(["journalctl", "-f", *(f"--unit={u}" for u in units)]) + _exec(_manager_argv("journalctl", ["-f", *(f"--unit={u}" for u in units)])) # journalctl takes unit globs, so the default needs no unit list of its own. - _exec(["journalctl", "-f", "-u", "proxy-suite-*"]) + _exec(_manager_argv("journalctl", ["-f", "-u", "proxy-suite-*"])) COMMANDS = { diff --git a/pkgs/proxy-ctl/proxy_gui.py b/pkgs/proxy-ctl/proxy_gui.py index a0f94b4..eab499a 100644 --- a/pkgs/proxy-ctl/proxy_gui.py +++ b/pkgs/proxy-ctl/proxy_gui.py @@ -1044,6 +1044,7 @@ class ProxySuiteGui(Adw.Application): action.connect("activate", callback) self.add_action(action) elevated = Gio.SimpleAction.new_stateful("elevated", None, GLib.Variant.new_boolean(False)) + elevated.set_enabled(ctl.privileged()) elevated.connect("change-state", self.on_elevated) self.add_action(elevated) retry = Gio.SimpleAction.new("retry-root", GLib.VariantType.new("as")) diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index d1d0bf2..862c14d 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -94,9 +94,14 @@ def is_root(): return os.geteuid() == 0 +def can_elevate(): + """Whether running as root would get further: not on a rootless host, where the user owns everything.""" + return ctl.privileged() and not is_root() + + def needs_root(out, status): """A failed run that root could do: the front ends offer to retry it elevated.""" - return bool(status) and status > 0 and not is_root() and any(ROOT_HINT.search(line) for line in out) + return bool(status) and status > 0 and can_elevate() and any(ROOT_HINT.search(line) for line in out) STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐", "reloading": "◐"} diff --git a/pkgs/proxy-ctl/proxy_supervisor.py b/pkgs/proxy-ctl/proxy_supervisor.py new file mode 100644 index 0000000..0f78129 --- /dev/null +++ b/pkgs/proxy-ctl/proxy_supervisor.py @@ -0,0 +1,1264 @@ +#!/usr/bin/env python3 +"""proxy-suitectl: a service supervisor for hosts without systemd (nix-on-droid). + +It runs the units the Nix module renders for a user manager, read from a JSON manifest +({"services": {name: {"Unit", "Service", "Install"}}, "timers": ..., "paths": ..., +"tmpfiles": [...]}), and answers the subset of systemctl and journalctl that proxy-ctl +and the suite's own scripts use, so both only swap the binary: + + proxy-suitectl ensure | boot | reload | shutdown | daemon + proxy-suitectl start|stop|restart|try-restart|is-active|show|cat|status|list-timers ... + proxy-suitectl journal [-u UNIT]... [-f] [-n N] [--since TIME] [-o cat] + +One daemon per user owns the processes: it starts on the first command that needs it, +restarts services after Restart=, fires timers and path units, and writes each unit's +output to its own log. Nothing here needs root. +""" + +import datetime +import fcntl +import fnmatch +import json +import os +import random +import re +import resource +import shlex +import signal +import socket +import socketserver +import subprocess +import sys +import threading +import time + +SUPERVISOR_DIR = os.environ.get("PROXY_SUITE_SUPERVISOR_DIR") or os.path.join( + os.environ.get("XDG_RUNTIME_DIR") or os.path.expanduser("~/.cache"), "proxy-suite-supervisor" +) +MANIFEST = os.environ.get("PROXY_SUITE_MANIFEST", "") +SOCKET = os.path.join(SUPERVISOR_DIR, "control.sock") +LOCK = os.path.join(SUPERVISOR_DIR, "daemon.lock") +LOG_DIR = os.path.join(SUPERVISOR_DIR, "logs") +CREDENTIALS_DIR = os.path.join(SUPERVISOR_DIR, "credentials") +LOG_LIMIT = 1024 * 1024 +STOP_TIMEOUT = 15 +# Stand-ins for the targets a user manager reaches at login. +BOOT_TARGETS = {"default.target", "multi-user.target", "timers.target", "paths.target"} +ACTIVE, ACTIVATING, DEACTIVATING, INACTIVE, FAILED = "active", "activating", "deactivating", "inactive", "failed" +AUTO_RESTART = "auto-restart" + + +# --- manifest ------------------------------------------------------------------- + + +def load_manifest(path=None): + path = path or MANIFEST + with open(path, encoding="utf-8") as f: + data = json.load(f) + return { + "services": data.get("services") or {}, + "timers": data.get("timers") or {}, + "paths": data.get("paths") or {}, + "tmpfiles": data.get("tmpfiles") or [], + } + + +def as_list(value): + if value is None: + return [] + return value if isinstance(value, list) else [value] + + +def split_name(name): + """(kind, base, instance): 'x@a.service' -> ('service', 'x@', 'a').""" + kind = "service" + for suffix in ("service", "timer", "path", "target"): + if name.endswith("." + suffix): + kind, name = suffix, name[: -len(suffix) - 1] + break + if "@" in name and not name.endswith("@"): + base, instance = name.split("@", 1) + return kind, base + "@", instance + return kind, name, None + + +def full_name(name, kind="service"): + _, base, instance = split_name(name) + return f"{base}{instance or ''}.{kind}" + + +def unescape(text): + """systemd-escape --unescape: '-' is '/', \\xNN a byte.""" + raw = text.replace("-", "/").encode() + return re.sub(rb"\\x([0-9a-fA-F]{2})", lambda m: bytes([int(m.group(1), 16)]), raw).decode(errors="replace") + + +TIMESPAN_UNITS = { + "us": 1e-6, "usec": 1e-6, "ms": 1e-3, "msec": 1e-3, + "s": 1, "sec": 1, "second": 1, "seconds": 1, + "m": 60, "min": 60, "minute": 60, "minutes": 60, + "h": 3600, "hr": 3600, "hour": 3600, "hours": 3600, + "d": 86400, "day": 86400, "days": 86400, + "w": 604800, "week": 604800, "weeks": 604800, + "M": 2629800, "month": 2629800, "months": 2629800, + "y": 31557600, "year": 31557600, "years": 31557600, +} + + +def timespan(value): + """Seconds in a systemd time span ("5m", "1h 30min", 90).""" + if isinstance(value, (int, float)): + return float(value) + total, matched = 0.0, False + for number, unit in re.findall(r"(\d+(?:\.\d+)?)\s*([a-zA-Z]*)", str(value)): + total += float(number) * TIMESPAN_UNITS.get(unit or "s", 1) + matched = True + if not matched: + raise ValueError(f"not a time span: {value}") + return total + + +# --- logs ----------------------------------------------------------------------- + +_log_locks = {} +_log_locks_guard = threading.Lock() + + +def log_path(unit): + """A unit's log; services go by their bare name, as journalctl -u takes it.""" + if unit.endswith(".service"): + unit = unit[: -len(".service")] + return os.path.join(LOG_DIR, f"{unit}.log") + + +def append_log(unit, text): + with _log_locks_guard: + lock = _log_locks.setdefault(unit, threading.Lock()) + path = log_path(unit) + with lock: + try: + if os.path.getsize(path) > LOG_LIMIT: + os.replace(path, path + ".1") + except OSError: + pass + with open(path, "a", encoding="utf-8") as f: + for line in text.splitlines() or [""]: + f.write(f"{time.time():.6f}\t{line}\n") + + +def pump(unit, stream): + for raw in iter(stream.readline, b""): + append_log(unit, raw.decode(errors="replace").rstrip("\n")) + stream.close() + + +# --- units ---------------------------------------------------------------------- + + +class Unit: + """One service instance and what the daemon knows of it.""" + + def __init__(self, name, definition): + self.name = name # full name: x.service, x@a.service + self.definition = definition + self.state = INACTIVE + self.result = "success" + self.main = None + self.current = None + self.stopping = False + self.cancel = threading.Event() + self.job = threading.RLock() + self.done = threading.Condition() + self.last_activated = None + + @property + def unit(self): + return self.definition.get("Unit") or {} + + @property + def service(self): + return self.definition.get("Service") or {} + + def public_state(self): + return ACTIVATING if self.state == AUTO_RESTART else self.state + + def set_state(self, state): + with self.done: + self.state = state + self.done.notify_all() + + +class Timer: + def __init__(self, name, definition): + self.name = name + self.definition = definition + self.active = False + self.activated = None + self.fired = set() + self.last = None + self.jitter = 0.0 + + @property + def config(self): + return self.definition.get("Timer") or {} + + def target(self): + return (self.definition.get("Timer") or {}).get("Unit") or self.name.replace(".timer", ".service") + + +class PathWatch: + def __init__(self, name, definition): + self.name = name + self.definition = definition + self.active = False + self.seen = {} + + @property + def config(self): + return self.definition.get("Path") or {} + + def target(self): + return self.config.get("Unit") or self.name.replace(".path", ".service") + + +def signature(path): + try: + st = os.stat(path) + except OSError: + return None + return (st.st_ino, st.st_size, st.st_mtime_ns) + + +class Supervisor: + def __init__(self, manifest_path=None): + self.manifest_path = manifest_path or MANIFEST + self.manifest = load_manifest(self.manifest_path) + self.units = {} + self.timers = {} + self.paths = {} + self.guard = threading.RLock() + self.started_at = time.time() + self.booted = False + self.quit = threading.Event() + + # lookups + + def definition(self, name): + kind, base, _ = split_name(name) + return self.manifest[kind + "s"].get(base) if kind in ("service", "timer", "path") else None + + def instance(self, name): + """The Unit for a service name, created on first use; None when the manifest lacks it.""" + name = full_name(name) + with self.guard: + unit = self.units.get(name) + if unit is None: + definition = self.definition(name) + if definition is None: + return None + unit = self.units[name] = Unit(name, definition) + return unit + + # specifiers and commands + + def specifiers(self, unit, text): + _, base, instance = split_name(unit.name) + prefix = base.rstrip("@") + table = { + "i": instance or "", + "I": unescape(instance or ""), + "n": unit.name, + "N": unit.name.rsplit(".", 1)[0], + "p": prefix, + "P": unescape(prefix), + "h": os.path.expanduser("~"), + "u": os.environ.get("USER", ""), + "t": os.environ.get("PROXY_SUITE_RUNTIME_BASE", SUPERVISOR_DIR), + "S": os.environ.get("PROXY_SUITE_STATE_BASE", os.path.expanduser("~/.local/state")), + "%": "%", + } + return re.sub(r"%(.)", lambda m: table.get(m.group(1), m.group(0)), text) + + def environment(self, unit): + env = dict(os.environ) + for key in ("PROXY_SUITE_SUPERVISOR_DIR", "PROXY_SUITE_MANIFEST", "NOTIFY_SOCKET"): + env.pop(key, None) + for entry in as_list(unit.service.get("Environment")): + for item in shlex.split(str(entry)): + if "=" in item: + key, value = item.split("=", 1) + env[key] = self.specifiers(unit, value) + if as_list(unit.service.get("LoadCredential")): + env["CREDENTIALS_DIRECTORY"] = self.credentials_dir(unit) + return env + + def credentials_dir(self, unit): + return os.path.join(CREDENTIALS_DIR, unit.name) + + def load_credentials(self, unit): + entries = as_list(unit.service.get("LoadCredential")) + if not entries: + return + target = self.credentials_dir(unit) + os.makedirs(target, mode=0o700, exist_ok=True) + for entry in entries: + ident, _, source = str(entry).partition(":") + source = self.specifiers(unit, source or ident) + with open(source, "rb") as f: + data = f.read() + path = os.path.join(target, ident) + if os.path.exists(path): + os.chmod(path, 0o600) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o400) + with os.fdopen(fd, "wb") as f: + f.write(data) + os.chmod(path, 0o400) + + def drop_credentials(self, unit): + target = self.credentials_dir(unit) + if not os.path.isdir(target): + return + for entry in os.listdir(target): + try: + os.chmod(os.path.join(target, entry), 0o600) + os.unlink(os.path.join(target, entry)) + except OSError: + pass + try: + os.rmdir(target) + except OSError: + pass + + def spawn(self, unit, command, extra_env=None): + """Popen for one Exec line, or (None, ignore_failure) when it is empty.""" + argv = [self.specifiers(unit, arg) for arg in shlex.split(str(command))] + ignore = False + while argv and argv[0][:1] in "-+!:@|" and argv[0]: + ignore = ignore or argv[0][0] == "-" + argv[0] = argv[0][1:] + if not argv[0]: + argv.pop(0) + if not argv: + return None, ignore + env = self.environment(unit) + env.update(extra_env or {}) + workdir = unit.service.get("WorkingDirectory") + cwd = os.path.expanduser("~") + if workdir: + workdir = self.specifiers(unit, str(workdir)) + optional = workdir.startswith("-") + workdir = workdir.lstrip("-") + if os.path.isdir(workdir): + cwd = workdir + elif not optional: + raise OSError(f"WorkingDirectory {workdir} does not exist") + umask = unit.service.get("UMask") + proc = subprocess.Popen( + argv, + env=env, + cwd=cwd, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + umask=int(str(umask), 8) if umask is not None else -1, + ) + threading.Thread(target=pump, args=(unit.name, proc.stdout), daemon=True).start() + return proc, ignore + + def run_commands(self, unit, key, extra_env=None): + """Runs a unit's Exec lines in order; False when one fails (and does not ignore it).""" + for command in as_list(unit.service.get(key)): + try: + proc, ignore = self.spawn(unit, command, extra_env) + except OSError as e: + append_log(unit.name, f"proxy-suitectl: {key}: {e}") + return False + if proc is None: + continue + unit.current = proc + status = proc.wait() + unit.current = None + if status and not ignore: + append_log(unit.name, f"proxy-suitectl: {key} exited with status {status}") + return False + return True + + @staticmethod + def kill_group(proc, sig): + try: + os.killpg(proc.pid, sig) + except (ProcessLookupError, PermissionError): + pass + + def terminate(self, proc): + if proc is None: + return + self.kill_group(proc, signal.SIGTERM) + try: + proc.wait(STOP_TIMEOUT) + except subprocess.TimeoutExpired: + self.kill_group(proc, signal.SIGKILL) + proc.wait() + # What the main process left behind in its group. + self.kill_group(proc, signal.SIGKILL) + + # jobs + + def deps(self, unit, *keys): + return [d for key in keys for d in as_list(unit.unit.get(key)) if self.definition(d) is not None] + + def start(self, name, seen=None): + """Starts a service (or timer/path unit) and what it pulls in: 0, or a systemctl status.""" + kind, _, _ = split_name(name) + if kind == "timer": + return self.start_timer(name) + if kind == "path": + return self.start_path(name) + unit = self.instance(name) + if unit is None: + return 5 + seen = seen if seen is not None else set() + if unit.name in seen: + return 0 + seen.add(unit.name) + for other in as_list(unit.unit.get("Conflicts")): + if self.definition(other) is not None: + self.stop(other) + for dep in self.deps(unit, "Requires", "BindsTo"): + if self.start(dep, seen): + unit.result = "dependency" + unit.set_state(FAILED) + return 1 + for dep in self.deps(unit, "Wants"): + self.start(dep, seen) + return self.activate(unit) + + def activate(self, unit, restarting=False): + with unit.job: + if restarting and (unit.state != AUTO_RESTART or unit.cancel.is_set()): + return 0 + if unit.state in (ACTIVE, ACTIVATING) or (unit.state == AUTO_RESTART and not restarting): + return 0 if unit.state != ACTIVATING else self.wait_settled(unit) + unit.stopping = False + unit.cancel.clear() + unit.last_activated = time.time() + unit.set_state(ACTIVATING) + service = unit.service + kind = service.get("Type", "simple") + try: + self.load_credentials(unit) + except OSError as e: + append_log(unit.name, f"proxy-suitectl: LoadCredential: {e}") + return self.fail(unit, "resources") + if not self.run_commands(unit, "ExecStartPre"): + return self.fail(unit, "exit-code") + if kind in ("oneshot", "forking"): + if not self.run_commands(unit, "ExecStart"): + return self.fail(unit, "exit-code") + if unit.stopping: + return 0 + if not self.run_commands(unit, "ExecStartPost"): + return self.fail(unit, "exit-code") + unit.result = "success" + if service.get("RemainAfterExit") or kind == "forking": + unit.set_state(ACTIVE) + else: + self.run_commands(unit, "ExecStopPost") + self.drop_credentials(unit) + unit.set_state(INACTIVE) + return 0 + commands = as_list(service.get("ExecStart")) + try: + proc, _ = self.spawn(unit, commands[0]) if commands else (None, False) + except OSError as e: + append_log(unit.name, f"proxy-suitectl: ExecStart: {e}") + return self.fail(unit, "exit-code") + if proc is None: + return self.fail(unit, "resources") + unit.main = proc + threading.Thread(target=self.watch, args=(unit, proc), daemon=True).start() + if not self.run_commands(unit, "ExecStartPost", {"MAINPID": str(proc.pid)}): + self.terminate(proc) + return self.fail(unit, "exit-code") + unit.result = "success" + unit.set_state(ACTIVE) + return 0 + + def wait_settled(self, unit): + with unit.done: + unit.done.wait_for(lambda: unit.state != ACTIVATING) + return 0 if unit.state == ACTIVE or unit.result == "success" else 1 + + def fail(self, unit, result): + unit.result = result + self.run_commands(unit, "ExecStopPost", {"SERVICE_RESULT": result}) + self.drop_credentials(unit) + unit.set_state(FAILED) + return 1 + + def watch(self, unit, proc): + """After the main process exits on its own: stop commands, then Restart=.""" + status = proc.wait() + with unit.job: + if unit.stopping or unit.main is not proc: + return + service = unit.service + unit.main = None + if status == 0 and service.get("RemainAfterExit"): + return + env = {"SERVICE_RESULT": "success" if status == 0 else "exit-code", "EXIT_STATUS": str(status)} + self.run_commands(unit, "ExecStop", env) + self.kill_group(proc, signal.SIGKILL) + self.run_commands(unit, "ExecStopPost", env) + restart = service.get("Restart", "no") + again = restart == "always" or (restart in ("on-failure", "on-abnormal", "on-abort") and status != 0) + unit.result = "success" if status == 0 else "exit-code" + if not again: + self.drop_credentials(unit) + unit.set_state(INACTIVE if status == 0 else FAILED) + return + append_log(unit.name, f"proxy-suitectl: exited with status {status}; restarting") + unit.set_state(AUTO_RESTART) + if unit.cancel.wait(timespan(service.get("RestartSec", 0.1))): + return + self.activate(unit, restarting=True) + + def stop(self, name): + kind, _, _ = split_name(name) + if kind == "timer": + return self.stop_timer(name) + if kind == "path": + return self.stop_path(name) + unit = self.units.get(full_name(name)) + if unit is None: + return 0 if self.definition(name) is not None else 5 + unit.stopping = True + unit.cancel.set() + # Bound to this one: they go first. + for other in list(self.units.values()): + if other is not unit and other.state != INACTIVE: + if unit.name in map(full_name, as_list(other.unit.get("PartOf")) + as_list(other.unit.get("BindsTo"))): + self.stop(other.name) + if unit.current is not None: + self.kill_group(unit.current, signal.SIGTERM) + with unit.job: + unit.stopping = True + if unit.state in (INACTIVE, FAILED, AUTO_RESTART): + unit.set_state(INACTIVE) + return 0 + unit.set_state(DEACTIVATING) + main, unit.main = unit.main, None + env = {"MAINPID": str(main.pid)} if main else {} + self.run_commands(unit, "ExecStop", env) + self.terminate(main) + self.run_commands(unit, "ExecStopPost", {"SERVICE_RESULT": "success"}) + self.drop_credentials(unit) + unit.set_state(INACTIVE) + unit.stopping = False + return 0 + + def restart(self, name, only_if_active=False): + kind, _, _ = split_name(name) + if kind != "service": + return self.stop(name) or self.start(name) + unit = self.units.get(full_name(name)) + if only_if_active and (unit is None or unit.state not in (ACTIVE, ACTIVATING, AUTO_RESTART)): + return 0 if self.definition(name) is not None else 5 + status = self.stop(name) + return status or self.start(name) + + # timers and paths + + def start_timer(self, name): + name = full_name(name, "timer") + definition = self.definition(name) + if definition is None: + return 5 + with self.guard: + timer = self.timers.get(name) + if timer is None or timer.definition is not definition: + timer = self.timers[name] = Timer(name, definition) + if not timer.active: + timer.active, timer.activated, timer.fired = True, time.time(), set() + timer.jitter = self.jitter(timer) + return 0 + + def stop_timer(self, name): + timer = self.timers.get(full_name(name, "timer")) + if timer: + timer.active = False + return 0 + + @staticmethod + def jitter(timer): + spread = timer.config.get("RandomizedDelaySec") + return random.uniform(0, timespan(spread)) if spread else 0.0 + + def next_elapse(self, timer): + config, candidates = timer.config, [] + if config.get("OnActiveSec") is not None and "active" not in timer.fired: + candidates.append(("active", timer.activated + timespan(config["OnActiveSec"]))) + for key in ("OnBootSec", "OnStartupSec"): + if config.get(key) is not None and "boot" not in timer.fired: + candidates.append(("boot", self.started_at + timespan(config[key]))) + unit = self.units.get(full_name(timer.target())) + if config.get("OnUnitActiveSec") is not None and unit and unit.last_activated: + candidates.append(("unit", unit.last_activated + timespan(config["OnUnitActiveSec"]))) + if not candidates: + return None, set() + at = min(when for _, when in candidates) + return at + timer.jitter, {base for base, when in candidates if when <= at} + + def start_path(self, name): + name = full_name(name, "path") + definition = self.definition(name) + if definition is None: + return 5 + with self.guard: + watch = self.paths.get(name) + if watch is None or watch.definition is not definition: + watch = self.paths[name] = PathWatch(name, definition) + if not watch.active: + watch.active = True + watch.seen = {p: signature(p) for key in ("PathChanged", "PathModified") for p in as_list(watch.config.get(key))} + return 0 + + def stop_path(self, name): + watch = self.paths.get(full_name(name, "path")) + if watch: + watch.active = False + return 0 + + def in_background(self, fn, *args): + threading.Thread(target=fn, args=args, daemon=True).start() + + def tick(self): + now = time.time() + for timer in list(self.timers.values()): + if not timer.active: + continue + at, bases = self.next_elapse(timer) + if at is None or at > now: + continue + timer.fired |= bases + timer.last = now + timer.jitter = self.jitter(timer) + target = self.instance(timer.target()) + if target is not None: + target.last_activated = now + if target.state not in (ACTIVATING, AUTO_RESTART): + self.in_background(self.activate_fresh, target) + for watch in list(self.paths.values()): + if not watch.active: + continue + changed = False + for path, before in list(watch.seen.items()): + after = signature(path) + if after != before: + watch.seen[path] = after + changed = True + exists = any(os.path.exists(p) for p in as_list(watch.config.get("PathExists"))) + target = self.instance(watch.target()) + if target is not None and (changed or (exists and target.state == INACTIVE)): + self.in_background(self.start, target.name) + + def activate_fresh(self, unit): + """A timer's run: a oneshot left active by RemainAfterExit runs again.""" + if unit.state == ACTIVE and unit.service.get("Type") == "oneshot": + self.stop(unit.name) + self.start(unit.name) + + # boot, reload, shutdown + + def make_tmpfiles(self): + for line in self.manifest["tmpfiles"]: + fields = str(line).split() + if len(fields) >= 2 and fields[0] in ("d", "D"): + mode = int(fields[2], 8) if len(fields) > 2 and fields[2] != "-" else 0o755 + try: + os.makedirs(fields[1], exist_ok=True) + os.chmod(fields[1], mode) + except OSError as e: + print(f"proxy-suitectl: tmpfiles: {fields[1]}: {e}", file=sys.stderr) + + def boot_units(self): + """The units a login would start, services ordered by After=.""" + wanted = [] + for kind in ("services", "timers", "paths"): + for base, definition in self.manifest[kind].items(): + if base.endswith("@"): + continue + if BOOT_TARGETS & set(as_list((definition.get("Install") or {}).get("WantedBy"))): + wanted.append(f"{base}.{kind[:-1]}") + order, visiting = [], set() + + def visit(name): + if name in order or name in visiting: + return + visiting.add(name) + definition = self.definition(name) or {} + for dep in as_list((definition.get("Unit") or {}).get("After")): + if full_name(dep) in wanted: + visit(full_name(dep)) + order.append(name) + + for name in wanted: + visit(name) + return order + + def boot(self): + self.make_tmpfiles() + self.booted = True + return max([self.start(name) for name in self.boot_units()] or [0]) + + def reload(self, restart_changed=False): + old = self.manifest + self.manifest = load_manifest(self.manifest_path) + if not restart_changed: + for unit in self.units.values(): + unit.definition = self.definition(unit.name) or unit.definition + return 0 + self.make_tmpfiles() + status = 0 + for unit in list(self.units.values()): + new = self.definition(unit.name) + running = unit.state not in (INACTIVE, FAILED) + if new is None: + if running: + self.stop(unit.name) + del self.units[unit.name] + elif new != unit.definition: + unit.definition = new + if running: + status = self.restart(unit.name) or status + for table, kind in ((self.timers, "timers"), (self.paths, "paths")): + for name, item in list(table.items()): + base = split_name(name)[1] + if base not in self.manifest[kind]: + del table[name] + elif self.manifest[kind][base] != old[kind].get(base) and item.active: + table[name].active = False + self.start(name) + if self.booted: + for name in self.boot_units(): + kind = split_name(name)[0] + if kind == "service": + unit = self.instance(name) + if unit.state == INACTIVE and unit.last_activated is None: + status = self.start(name) or status + else: + status = self.start(name) or status + return status + + def shutdown(self): + for timer in self.timers.values(): + timer.active = False + for watch in self.paths.values(): + watch.active = False + active = [u for u in self.units.values() if u.state not in (INACTIVE, FAILED)] + for unit in sorted(active, key=lambda u: u.last_activated or 0, reverse=True): + self.stop(unit.name) + self.quit.set() + + # queries + + def state_of(self, name): + kind, _, _ = split_name(name) + if self.definition(name) is None: + return "not-found", INACTIVE, "dead" + if kind == "timer": + timer = self.timers.get(full_name(name, "timer")) + return ("loaded", ACTIVE, "waiting") if timer and timer.active else ("loaded", INACTIVE, "dead") + if kind == "path": + watch = self.paths.get(full_name(name, "path")) + return ("loaded", ACTIVE, "waiting") if watch and watch.active else ("loaded", INACTIVE, "dead") + unit = self.units.get(full_name(name)) + if unit is None: + return "loaded", INACTIVE, "dead" + sub = {ACTIVE: "running" if unit.main else "exited", AUTO_RESTART: "auto-restart", ACTIVATING: "start"} + return "loaded", unit.public_state(), sub.get(unit.state, "dead" if unit.state == INACTIVE else unit.state) + + def properties(self, name): + kind = split_name(name)[0] + load, active, sub = self.state_of(name) + definition = self.definition(name) or {} + unit = self.units.get(full_name(name)) if kind == "service" else None + return { + "Id": full_name(name, kind), + "Description": (definition.get("Unit") or {}).get("Description", ""), + "LoadState": load, + "ActiveState": active, + "SubState": sub, + "Result": unit.result if unit else "success", + "MainPID": str(unit.main.pid if unit and unit.main else 0), + } + + def list_timers(self, names): + rows = [] + for name, timer in sorted(self.timers.items()): + if names and name not in map(lambda n: full_name(n, "timer"), names): + continue + if not timer.active: + continue + at, _ = self.next_elapse(timer) + rows.append({ + "next": int(at * 1e6) if at else None, + "left": int(max(0, at - time.time()) * 1e6) if at else None, + "last": int(timer.last * 1e6) if timer.last else None, + "passed": int((time.time() - timer.last) * 1e6) if timer.last else None, + "unit": name, + "activates": full_name(timer.target()), + }) + return rows + + +# --- daemon --------------------------------------------------------------------- + + +class short_socket_path: + """SOCKET, reached through a descriptor of its directory when the whole path is longer + than a socket address holds (108 bytes; a deep home directory gets there).""" + + def __enter__(self): + self.fd = None + if len(os.fsencode(SOCKET)) < 100: + return SOCKET + self.fd = os.open(SUPERVISOR_DIR, os.O_RDONLY | os.O_DIRECTORY) + return f"/proc/self/fd/{self.fd}/{os.path.basename(SOCKET)}" + + def __exit__(self, *_): + if self.fd is not None: + os.close(self.fd) + + +def handle(supervisor, request): + """(status, output) for one client request.""" + verb, units, opts = request["verb"], request.get("units", []), request.get("options", {}) + out = [] + if verb == "start": + if opts.get("no_block"): + for name in units: + supervisor.in_background(supervisor.start, name) + return 0, "" + status = 0 + for name in units: + result = supervisor.start(name) + if result == 5: + out.append(f"Failed to start {full_name(name, split_name(name)[0])}: Unit not found.") + elif result: + out.append(f"Job for {full_name(name, split_name(name)[0])} failed. See \"proxy-ctl logs {split_name(name)[1]}\".") + status = status or result + return status, "\n".join(out) + if verb in ("stop", "restart", "try-restart"): + status = 0 + for name in units: + if verb == "stop": + result = supervisor.stop(name) + else: + result = supervisor.restart(name, only_if_active=verb == "try-restart") + status = status or result + return status, "" + if verb == "reset-failed": + for unit in supervisor.units.values(): + if unit.state == FAILED and (not units or unit.name in map(full_name, units)): + unit.set_state(INACTIVE) + return 0, "" + if verb == "is-active": + states = [supervisor.state_of(name)[1] for name in units] + return (0 if ACTIVE in states else 3), "\n".join(states) + if verb == "is-failed": + states = [supervisor.state_of(name)[1] for name in units] + return (0 if FAILED in states else 1), "\n".join(states) + if verb == "show": + wanted = opts.get("properties") or ["Id", "Description", "LoadState", "ActiveState", "SubState", "Result", "MainPID"] + blocks = [] + for name in units: + props = supervisor.properties(name) + lines = [props.get(p, "") if opts.get("value") else f"{p}={props.get(p, '')}" for p in wanted] + blocks.append("\n".join(lines)) + return 0, "\n\n".join(blocks) + if verb == "list-timers": + return 0, json.dumps(supervisor.list_timers(units)) + if verb == "status": + names = units or [u.name for u in supervisor.units.values()] + status = 0 + for name in names: + props = supervisor.properties(name) + if props["LoadState"] == "not-found": + out.append(f"Unit {props['Id']} could not be found.") + status = 4 + continue + out.append(f"* {props['Id']} - {props['Description']}") + out.append(f" Active: {props['ActiveState']} ({props['SubState']})") + if props["MainPID"] != "0": + out.append(f" Main PID: {props['MainPID']}") + out.extend(f" {line}" for line in journal_lines([props["Id"].rsplit(".", 1)[0]], count=10, fmt="short")) + if props["ActiveState"] != ACTIVE: + status = status or 3 + return status, "\n".join(out) + if verb == "daemon-reload": + return supervisor.reload(), "" + if verb == "reload": + return supervisor.reload(restart_changed=True), "" + if verb == "boot": + # Again (a switch): what changed restarts, what is new starts. + if supervisor.booted: + return supervisor.reload(restart_changed=True), "" + return supervisor.reload() or supervisor.boot(), "" + if verb == "shutdown": + supervisor.in_background(supervisor.shutdown) + return 0, "" + if verb == "ping": + return 0, "pong" + return 1, f"proxy-suitectl: unknown verb {verb}" + + +def serve(manifest_path=None): + os.makedirs(SUPERVISOR_DIR, mode=0o700, exist_ok=True) + os.makedirs(LOG_DIR, mode=0o700, exist_ok=True) + lock = open(LOCK, "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + print("proxy-suitectl: the supervisor is already running", file=sys.stderr) + return 0 + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + try: + resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard)) + except (ValueError, OSError): + pass + supervisor = Supervisor(manifest_path) + try: + os.unlink(SOCKET) + except FileNotFoundError: + pass + + class Handler(socketserver.StreamRequestHandler): + def handle(self): + try: + request = json.loads(self.rfile.readline()) + status, output = handle(supervisor, request) + except Exception as e: # a bad request must not take the daemon down + status, output = 1, f"proxy-suitectl: {e}" + try: + self.wfile.write((json.dumps({"status": status, "output": output}) + "\n").encode()) + except OSError: + pass + + class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): + daemon_threads = True + + old_umask = os.umask(0o077) + with short_socket_path() as address: + server = Server(address, Handler) + os.umask(old_umask) + threading.Thread(target=server.serve_forever, daemon=True).start() + signal.signal(signal.SIGTERM, lambda *_: supervisor.in_background(supervisor.shutdown)) + signal.signal(signal.SIGINT, lambda *_: supervisor.in_background(supervisor.shutdown)) + signal.signal(signal.SIGHUP, lambda *_: supervisor.in_background(supervisor.reload)) + print(f"proxy-suitectl: supervising {supervisor.manifest_path}", file=sys.stderr) + while not supervisor.quit.wait(1): + try: + supervisor.tick() + except Exception as e: + print(f"proxy-suitectl: {e}", file=sys.stderr) + server.shutdown() + try: + os.unlink(SOCKET) + except FileNotFoundError: + pass + return 0 + + +# --- client --------------------------------------------------------------------- + + +def request(verb, units=(), options=None, spawn=False): + """(status, output) from the daemon; None when it is not running (and not spawned).""" + message = json.dumps({"verb": verb, "units": list(units), "options": options or {}}) + "\n" + for attempt in range(100): + try: + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: + with short_socket_path() as address: + sock.connect(address) + sock.sendall(message.encode()) + with sock.makefile("rb") as f: + reply = json.loads(f.readline()) + return reply["status"], reply["output"] + except (FileNotFoundError, ConnectionRefusedError, NotADirectoryError): + if not spawn: + return None + if attempt == 0: + start_daemon() + time.sleep(0.1) + print(f"proxy-suitectl: the supervisor did not come up; see {log_path('supervisor')}", file=sys.stderr) + return 1, "" + + +def start_daemon(): + if not MANIFEST or not os.path.exists(MANIFEST): + print(f"proxy-suitectl: no manifest at {MANIFEST or '(unset)'}: switch the configuration first", file=sys.stderr) + sys.exit(1) + os.makedirs(LOG_DIR, mode=0o700, exist_ok=True) + with open(log_path("supervisor"), "a") as log: + subprocess.Popen( + [sys.executable, os.path.abspath(__file__), "daemon"], + stdin=subprocess.DEVNULL, + stdout=log, + stderr=log, + start_new_session=True, + cwd=os.path.expanduser("~"), + ) + + +def parse_systemctl(args): + options, units, verb = {}, [], None + it = iter(args) + for arg in it: + if arg == "--": + units.extend(it) + break + if arg in ("--user", "--system", "--no-ask-password", "--no-pager", "--all", "-a", "--full", "-l"): + continue + if arg in ("-q", "--quiet"): + options["quiet"] = True + elif arg == "--no-block": + options["no_block"] = True + elif arg == "--value": + options["value"] = True + elif arg.startswith("--property=") or arg.startswith("-p") and len(arg) > 2: + options.setdefault("properties", []).extend(arg.split("=", 1)[1].split(",") if arg.startswith("--") else arg[2:].split(",")) + elif arg in ("-p", "--property"): + options.setdefault("properties", []).extend(next(it, "").split(",")) + elif arg in ("-o", "--output"): + options["output"] = next(it, "") + elif arg.startswith("--output="): + options["output"] = arg.split("=", 1)[1] + elif arg.startswith("-") and arg != "-": + continue + elif verb is None: + verb = arg + else: + units.append(arg) + return verb, units, options + + +def cat(units): + try: + manifest = load_manifest() + except (OSError, ValueError): + manifest = None + status = 0 + for name in units: + kind, base, _ = split_name(name) + definition = (manifest or {}).get(kind + "s", {}).get(base) + if definition is None: + print(f"No files found for {full_name(name, kind)}.", file=sys.stderr) + status = 1 + continue + print(f"# {MANIFEST}: {full_name(name, kind)}") + for section, values in definition.items(): + print(f"[{section}]") + for key, value in values.items(): + for item in as_list(value): + print(f"{key}={str(item).lower() if isinstance(item, bool) else item}") + print() + return status + + +def offline(verb, units, options): + """Answers for a daemon that is not running: nothing is active.""" + try: + supervisor = Supervisor() + except (OSError, ValueError): + supervisor = None + if verb in ("stop", "try-restart", "reset-failed", "daemon-reload", "shutdown", "reload"): + return 0, "" + if supervisor is None: + return (3 if verb == "is-active" else 1), "\n".join(INACTIVE for _ in units) + return handle(supervisor, {"verb": verb, "units": units, "options": options}) + + +def systemctl_main(args): + verb, units, options = parse_systemctl(args) + if verb is None: + verb = "status" + if verb == "cat": + return cat(units) + if verb == "daemon": + return serve() + if verb == "ensure": + # A new session: boot unless the daemon already runs. + if request("ping") is not None: + return 0 + verb = "boot" + spawn = verb in ("start", "restart", "boot") + reply = request(verb, units, options, spawn=spawn) + if reply is None: + reply = offline(verb, units, options) + status, output = reply + if output and not options.get("quiet"): + print(output, file=sys.stderr if verb in ("start",) and status else sys.stdout) + return status + + +# --- journal -------------------------------------------------------------------- + + +def parse_since(value): + value = value.strip() + now = time.time() + if value.startswith("@"): + return float(value[1:]) + if value in ("now",): + return now + if value in ("today", "yesterday"): + midnight = datetime.datetime.combine(datetime.date.today(), datetime.time()) + return midnight.timestamp() - (86400 if value == "yesterday" else 0) + if value[:1] in "-+": + return now + (1 if value[0] == "+" else -1) * timespan(value[1:]) + if value.endswith(" ago"): + return now - timespan(value[:-4]) + for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d", "%H:%M:%S", "%H:%M"): + try: + parsed = datetime.datetime.strptime(value, fmt) + except ValueError: + continue + if fmt.startswith("%H"): + parsed = datetime.datetime.combine(datetime.date.today(), parsed.time()) + return parsed.timestamp() + raise ValueError(f"cannot parse time {value!r}") + + +def log_units(patterns): + try: + names = sorted(f[:-4] for f in os.listdir(LOG_DIR) if f.endswith(".log")) + except OSError: + names = [] + names = [n for n in names if n != "supervisor"] + if not patterns: + return names + wanted = [p[: -len(".service")] if p.endswith(".service") else p for p in patterns] + return [n for n in names if any(fnmatch.fnmatchcase(n, p) for p in wanted)] + [ + p for p in wanted if p == "supervisor" + ] + + +def read_entries(unit, since=None): + entries = [] + for path in (log_path(unit) + ".1", log_path(unit)): + try: + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + stamp, _, text = line.rstrip("\n").partition("\t") + try: + at = float(stamp) + except ValueError: + continue + if since is None or at >= since: + entries.append((at, unit, text)) + except OSError: + pass + return entries + + +def format_entry(entry, fmt): + at, unit, text = entry + if fmt == "cat": + return text + stamp = datetime.datetime.fromtimestamp(at).strftime("%b %d %H:%M:%S") + return f"{stamp} {unit}: {text}" + + +def journal_lines(patterns, count=None, since=None, fmt="short"): + entries = sorted(e for unit in log_units(patterns) for e in read_entries(unit, since)) + if count is not None: + entries = entries[-count:] if count else [] + return [format_entry(e, fmt) for e in entries] + + +def journal_main(args): + patterns, follow, count, since, fmt = [], False, None, None, "short" + it = iter(args) + for arg in it: + if arg in ("-u", "--unit"): + patterns.append(next(it, "")) + elif arg.startswith("--unit="): + patterns.append(arg.split("=", 1)[1]) + elif arg.startswith("-u") and len(arg) > 2: + patterns.append(arg[2:]) + elif arg in ("-f", "--follow"): + follow = True + elif arg in ("-n", "--lines"): + count = int(next(it, "10")) + elif arg.startswith("--lines="): + count = int(arg.split("=", 1)[1]) + elif arg.startswith("-n") and len(arg) > 2: + count = int(arg[2:]) + elif arg in ("-S", "--since"): + since = parse_since(next(it, "")) + elif arg.startswith("--since="): + since = parse_since(arg.split("=", 1)[1]) + elif arg in ("-o", "--output"): + fmt = next(it, "short") + elif arg.startswith("--output="): + fmt = arg.split("=", 1)[1] + if follow and count is None: + count = 10 + for line in journal_lines(patterns, count, since, fmt): + print(line) + if not follow: + return 0 + sys.stdout.flush() + offsets = {} + for unit in log_units(patterns): + try: + offsets[unit] = (os.stat(log_path(unit)).st_ino, os.path.getsize(log_path(unit))) + except OSError: + pass + try: + while True: + time.sleep(0.5) + for unit in log_units(patterns): + path = log_path(unit) + try: + st = os.stat(path) + except OSError: + continue + inode, offset = offsets.get(unit, (st.st_ino, 0)) + if inode != st.st_ino or st.st_size < offset: + offset = 0 + if st.st_size == offset: + offsets[unit] = (st.st_ino, offset) + continue + with open(path, encoding="utf-8", errors="replace") as f: + f.seek(offset) + chunk = f.read() + offset = f.tell() + offsets[unit] = (st.st_ino, offset) + for line in chunk.splitlines(): + stamp, _, text = line.partition("\t") + try: + print(format_entry((float(stamp), unit, text), fmt), flush=True) + except ValueError: + continue + except KeyboardInterrupt: + return 0 + + +def main(argv): + args = argv[1:] + if args[:1] == ["journal"]: + return journal_main(args[1:]) + if args[:1] in (["-h"], ["--help"], ["help"]): + print(__doc__.strip()) + return 0 + return systemctl_main(args) + + +if __name__ == "__main__": + try: + sys.exit(main(sys.argv)) + except BrokenPipeError: + sys.exit(0) diff --git a/pkgs/proxy-ctl/proxy_tui.py b/pkgs/proxy-ctl/proxy_tui.py index 432b5bd..fbce537 100644 --- a/pkgs/proxy-ctl/proxy_tui.py +++ b/pkgs/proxy-ctl/proxy_tui.py @@ -558,7 +558,7 @@ class ProxyTui(App): def check_action(self, action, parameters): if action in ("retry_root", "switch_root"): - return not model.is_root() + return model.can_elevate() # A row action that does not apply: its key does nothing. if action != "act" or self.screen is not self.main: return True diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index 55773f5..cf0b158 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -291,6 +291,52 @@ class ProbeWalkTest(EnvTest): self.assertIn('pin: proxy.routing.rules = [ { outbound = "de"; domains = [ "sekai.test" ]; } ]', out) +class ServiceManagerTest(EnvTest): + def calls(self): + seen = [] + self.patch("_run", lambda argv, **kw: seen.append(argv) or (0, "")) + return seen + + def test_system_units(self): + seen = self.calls() + ctl.systemctl("--user", "start", "anchor.service") + ctl.systemctl("start", "proxy-suite-socks") + self.assertEqual(seen, [["systemctl", "--user", "start", "anchor.service"], ["systemctl", "start", "proxy-suite-socks"]]) + self.assertEqual(ctl.journal_hint("proxy-suite-autoproxy-learn", 20), "journalctl -u proxy-suite-autoproxy-learn -n 20") + + def test_user_units(self): + # home-manager: every unit is the user's, and a --user of the caller's is not doubled. + os.environ["SERVICE_MANAGER"] = "systemd-user" + seen = self.calls() + ctl.systemctl("--user", "stop", "anchor.service") + ctl._unit_states(["proxy-suite-socks"]) + self.assertEqual(seen[0], ["systemctl", "--user", "stop", "anchor.service"]) + self.assertEqual(seen[1][:3], ["systemctl", "--user", "show"]) + self.assertEqual(ctl.journal_hint("proxy-suite-socks"), "journalctl --user -u proxy-suite-socks") + + def test_supervisor_units(self): + # nix-on-droid: proxy-suitectl stands in for systemctl and journalctl. + os.environ.update(SERVICE_MANAGER="supervisor", SUPERVISOR_CTL="/bin/proxy-suitectl") + seen = self.calls() + ctl.systemctl("--user", "stop", "anchor.service") + ctl._unit_states(["proxy-suite-socks"]) + self.assertEqual(seen[0], ["/bin/proxy-suitectl", "stop", "anchor.service"]) + self.assertEqual(seen[1][:2], ["/bin/proxy-suitectl", "show"]) + self.assertEqual(ctl.journal_hint("proxy-suite-socks", 5), "/bin/proxy-suitectl journal -u proxy-suite-socks -n 5") + + def test_paths_follow_host_dirs(self): + for name in ("SUB_CACHE_DIR", "AUTOPROXY_STATE_DIR", "INBOUNDS_STATS_FILE", "OUTBOUND_INVENTORY_FILE"): + os.environ.pop(name, None) + os.environ.update(STATE_DIR="/home/u/.local/state/proxy-suite", RUNTIME_DIR="/tmp/ps") + self.assertEqual(ctl._autoproxy_dir(), "/home/u/.local/state/proxy-suite/autoproxy") + self.assertEqual(os.path.dirname(ctl._subscription_cache("x")), "/home/u/.local/state/proxy-suite/subscriptions") + + def test_rootless_hosts_never_ask_for_root(self): + self.assertIn("sudo", ctl.ask_group()) + os.environ["PRIVILEGED"] = "0" + self.assertNotIn("sudo", ctl.ask_group()) + + class AutoProxyTest(EnvTest): def setUp(self): super().setUp() diff --git a/pkgs/proxy-ctl/test_proxy_supervisor.py b/pkgs/proxy-ctl/test_proxy_supervisor.py new file mode 100644 index 0000000..834cb6b --- /dev/null +++ b/pkgs/proxy-ctl/test_proxy_supervisor.py @@ -0,0 +1,172 @@ +import json +import os +import shutil +import subprocess +import sys +import tempfile +import time +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +SUPERVISOR = os.path.join(HERE, "proxy_supervisor.py") + + +def wait_for(predicate, timeout=10): + deadline = time.time() + timeout + while time.time() < deadline: + value = predicate() + if value: + return value + time.sleep(0.05) + raise AssertionError("timed out") + + +class SupervisorTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="proxy-supervisor-") + self.run_dir = os.path.join(self.tmp, "run") + self.manifest = os.path.join(self.tmp, "manifest.json") + self.env = dict( + os.environ, + # Deeper than a socket address holds. + PROXY_SUITE_SUPERVISOR_DIR=os.path.join(self.tmp, "x" * 100, "supervisor"), + PROXY_SUITE_MANIFEST=self.manifest, + HOME=self.tmp, + ) + self.write_manifest() + + def tearDown(self): + subprocess.run([sys.executable, SUPERVISOR, "shutdown"], env=self.env, capture_output=True) + # The daemon removes its socket once every unit is down. + try: + wait_for(lambda: not self.daemon_running(), timeout=30) + finally: + shutil.rmtree(self.tmp, ignore_errors=True) + + def daemon_running(self): + return os.path.exists(os.path.join(self.env["PROXY_SUITE_SUPERVISOR_DIR"], "control.sock")) + + def write_manifest(self, crash_times=1, marker="one"): + out = os.path.join(self.tmp, "out") + sh = lambda text: ["/bin/sh -c " + json.dumps(text)] + manifest = { + "services": { + # Fails the first crash_times starts, then stays up. + "proxy-suite-counter": { + "Unit": {"Description": "counter"}, + "Service": { + "Type": "simple", + "Restart": "on-failure", + "RestartSec": "100ms", + "Environment": [json.dumps(f"MARKER={marker}")], + "ExecStartPre": [f'/bin/sh -c "mkdir -p {out}"'], + "ExecStart": sh( + f'n=$(cat {out}/starts 2>/dev/null || echo 0); n=$((n+1)); echo $n > {out}/starts; ' + f'echo "start $n $MARKER"; [ $n -gt {crash_times} ] || exit 3; exec sleep 1000' + ), + "ExecStopPost": sh(f"echo stopped >> {out}/stops"), + }, + "Install": {"WantedBy": ["default.target"]}, + }, + "proxy-suite-once": { + "Unit": {"Description": "oneshot", "After": ["proxy-suite-counter.service"]}, + "Service": { + "Type": "oneshot", + "RemainAfterExit": True, + "ExecStart": sh(f"echo ran >> {out}/once"), + }, + "Install": {"WantedBy": ["default.target"]}, + }, + "proxy-suite-tick": { + "Unit": {"Description": "timer job"}, + "Service": {"Type": "oneshot", "ExecStart": sh(f"echo tick >> {out}/ticks")}, + }, + "proxy-suite-pin@": { + "Unit": {"Description": "template"}, + "Service": {"Type": "oneshot", "ExecStart": sh(f"echo '%I' >> {out}/pins")}, + }, + }, + "timers": { + "proxy-suite-tick": { + "Unit": {"Description": "tick"}, + "Timer": {"OnActiveSec": "1s", "OnUnitActiveSec": "1s"}, + "Install": {"WantedBy": ["timers.target"]}, + }, + }, + "paths": {}, + "tmpfiles": [f"d {self.run_dir} 0700 - - -"], + } + with open(self.manifest + ".tmp", "w") as f: + json.dump(manifest, f) + os.replace(self.manifest + ".tmp", self.manifest) + + def ctl(self, *args): + p = subprocess.run([sys.executable, SUPERVISOR, *args], env=self.env, capture_output=True, text=True, timeout=60) + return p.returncode, p.stdout + + def read(self, name): + try: + with open(os.path.join(self.tmp, "out", name)) as f: + return f.read().split() + except FileNotFoundError: + return [] + + def test_without_daemon(self): + self.assertEqual(self.ctl("is-active", "--quiet", "proxy-suite-counter"), (3, "")) + status, out = self.ctl("show", "--property=Id,LoadState,ActiveState", "--", "proxy-suite-counter", "nope") + self.assertEqual(status, 0) + self.assertEqual( + out.split("\n\n"), + ["Id=proxy-suite-counter.service\nLoadState=loaded\nActiveState=inactive", "Id=nope.service\nLoadState=not-found\nActiveState=inactive\n"], + ) + self.assertEqual(self.ctl("stop", "proxy-suite-counter")[0], 0) + self.assertFalse(self.daemon_running()) + + def test_boot_restart_timers_and_stop(self): + self.assertEqual(self.ctl("boot")[0], 0) + self.assertTrue(os.path.isdir(self.run_dir)) + # Crashed once, restarted, then up. + wait_for(lambda: self.ctl("show", "-p", "SubState", "--value", "proxy-suite-counter")[1].strip() == "running") + self.assertEqual(self.read("starts"), ["2"]) + self.assertEqual(self.read("stops"), ["stopped"]) + self.assertEqual(self.read("once"), ["ran"]) + self.assertEqual(self.ctl("is-active", "proxy-suite-once"), (0, "active\n")) + + status, out = self.ctl("list-timers", "-o", "json", "proxy-suite-tick.timer") + timers = json.loads(out) + self.assertEqual([t["activates"] for t in timers], ["proxy-suite-tick.service"]) + self.assertGreater(timers[0]["next"], (time.time() - 5) * 1e6) + wait_for(lambda: len(self.read("ticks")) >= 2) + + # Template instances get %I unescaped. + self.assertEqual(self.ctl("start", "proxy-suite-pin@de\\x2dfra.service")[0], 0) + self.assertEqual(self.read("pins"), ["de-fra"]) + + status, out = self.ctl("journal", "-u", "proxy-suite-count*", "-o", "cat", "--since", "-1h", "--no-pager") + self.assertEqual([l for l in out.splitlines() if l.startswith("start")][:2], ["start 1 one", "start 2 one"]) + self.assertIn("proxy-suitectl: exited with status 3; restarting", out) + self.assertEqual(self.ctl("journal", "-u", "proxy-suite-counter", "-n", "1", "-o", "cat")[1], "start 2 one\n") + + self.assertEqual(self.ctl("stop", "proxy-suite-counter")[0], 0) + self.assertEqual(self.ctl("is-active", "proxy-suite-counter"), (3, "inactive\n")) + self.assertEqual(self.read("stops"), ["stopped", "stopped"]) + # try-restart leaves a stopped unit stopped. + self.assertEqual(self.ctl("try-restart", "proxy-suite-counter")[0], 0) + self.assertEqual(self.ctl("is-active", "proxy-suite-counter")[0], 3) + + def test_boot_again_restarts_changed_units(self): + self.write_manifest(crash_times=0) + self.ctl("boot") + wait_for(lambda: self.ctl("is-active", "proxy-suite-counter")[0] == 0) + pid = self.ctl("show", "-p", "MainPID", "--value", "proxy-suite-counter")[1].strip() + self.write_manifest(crash_times=0, marker="two") + self.assertEqual(self.ctl("boot")[0], 0) + wait_for(lambda: self.ctl("is-active", "proxy-suite-counter")[0] == 0) + self.assertNotEqual(self.ctl("show", "-p", "MainPID", "--value", "proxy-suite-counter")[1].strip(), pid) + self.assertIn("start 2 two", self.ctl("journal", "-u", "proxy-suite-counter", "-o", "cat")[1]) + # The unchanged oneshot is not run again. + self.assertEqual(self.read("once"), ["ran"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/pkgs/proxy-suite-supervisor.nix b/pkgs/proxy-suite-supervisor.nix new file mode 100644 index 0000000..631a72d --- /dev/null +++ b/pkgs/proxy-suite-supervisor.nix @@ -0,0 +1,38 @@ +# proxy-suitectl: the service manager of hosts without systemd (nix-on-droid). It reads +# the units from `manifest`, a path outside the store the host's activation points at the +# current generation's units, so the command itself does not change with the configuration. +{ + lib, + pkgs, +}: + +{ + # Where the daemon keeps its socket, logs and credentials. + supervisorDir, + manifest, + # What %t and %S expand to. + runtimeDir, + stateDir, +}: + +let + unwrapped = pkgs.writeScriptBin "proxy-suitectl" ( + "#!${pkgs.python3}/bin/python3\n" + builtins.readFile ./proxy-ctl/proxy_supervisor.py + ); +in +pkgs.symlinkJoin { + name = "proxy-suitectl"; + paths = [ unwrapped ]; + nativeBuildInputs = [ pkgs.makeWrapper ]; + postBuild = '' + wrapProgram "$out/bin/proxy-suitectl" \ + --set PROXY_SUITE_SUPERVISOR_DIR ${lib.escapeShellArg supervisorDir} \ + --set PROXY_SUITE_MANIFEST ${lib.escapeShellArg manifest} \ + --set PROXY_SUITE_RUNTIME_BASE ${lib.escapeShellArg runtimeDir} \ + --set PROXY_SUITE_STATE_BASE ${lib.escapeShellArg stateDir} + ''; + meta = { + description = "A systemctl-like supervisor for proxy-suite's units on hosts without systemd"; + mainProgram = "proxy-suitectl"; + }; +} diff --git a/pkgs/wireproxy-awg.nix b/pkgs/wireproxy-awg.nix new file mode 100644 index 0000000..fd6afe8 --- /dev/null +++ b/pkgs/wireproxy-awg.nix @@ -0,0 +1,41 @@ +# wireproxy with AmneziaWG 3.1: a profile as a SOCKS5 listener, with no interface or +# privileges, for asOutbound = "userspace". Its vendored amneziawg-go gets the suite's +# userspace patch, and wireproxy learns FwMark for hosts that capture traffic. +{ pkgs }: + +pkgs.buildGo126Module (finalAttrs: { + pname = "wireproxy-awg"; + version = "1.0.18"; + + src = pkgs.fetchFromGitHub { + owner = "artem-russkikh"; + repo = "wireproxy-awg"; + rev = "v${finalAttrs.version}"; + hash = "sha256-aiDHUkAP9vuRVmdt/6be0ExaPheE7xWkI8twxVHTzYc="; + }; + vendorHash = "sha256-jHi8bg8Y+L1Hio/UOrSGQNbF+tJg37tfYDjeqlVLmHM="; + + patches = [ ./patches/wireproxy-awg-fwmark.patch ]; + + # The vendored copy, once it exists: the module fetch keeps upstream's. + overrideModAttrs = _: { preBuild = ""; }; + preBuild = '' + chmod -R u+w vendor/github.com/amnezia-vpn/amneziawg-go/v3 + patch -p1 -d vendor/github.com/amnezia-vpn/amneziawg-go/v3 \ + < ${./patches/amneziawg-go-random-trailers-transport.patch} + ''; + + subPackages = [ "cmd/wireproxy" ]; + ldflags = [ + "-s" + "-w" + "-X main.version=${finalAttrs.version}" + ]; + + meta = { + description = "WireGuard/AmneziaWG client as a userspace SOCKS5/HTTP proxy"; + homepage = "https://github.com/artem-russkikh/wireproxy-awg"; + license = pkgs.lib.licenses.isc; + mainProgram = "wireproxy"; + }; +}) diff --git a/scripts/amneziawg_config.py b/scripts/amneziawg_config.py index 39725da..2484f80 100644 --- a/scripts/amneziawg_config.py +++ b/scripts/amneziawg_config.py @@ -307,6 +307,42 @@ def as_outbound(config: str, fwmark: int) -> str: return _set_interface_value(config, "FwMark", str(fwmark)) +# Read once by wireproxy: repeated lines are joined into one list. +WIREPROXY_LIST_KEYS = {"address", "dns", "allowedips"} +# wg-quick's, which wireproxy has no use for. +WIREPROXY_DROPPED_KEYS = FORBIDDEN_WG_QUICK_KEYS | {"table", "fwmark"} + + +def as_wireproxy(config: str, socks_address: str, fwmark: int | None = None) -> str: + """A wireproxy configuration: the profile, served as a SOCKS5 listener on socks_address. + + With fwmark, the tunnel's own packets are marked, to get past TUN and TProxy capture. + """ + lines: list[str] = [] + for name, pairs in conf_sections(config): + if name not in {"interface", "peer"}: + continue + if lines: + lines.append("") + lines.append(f"[{name.capitalize()}]") + lists: dict[str, list[str]] = {} + for key, value in pairs: + if key in WIREPROXY_DROPPED_KEYS: + continue + if key in WIREPROXY_LIST_KEYS: + if key not in lists: + lists[key] = [] + lines.append(key) + lists[key].extend(item.strip() for item in value.split(",") if item.strip()) + else: + lines.append(f"{key} = {value}") + lines = [f"{line} = {','.join(lists[line])}" if line in lists else line for line in lines] + if name == "interface" and fwmark is not None: + lines.append(f"fwmark = {fwmark}") + lines.extend(["", "[Socks5]", f"BindAddress = {socks_address}"]) + return "\n".join(lines) + "\n" + + def conf_sections(config: str) -> list[tuple[str, list[tuple[str, str]]]]: """Each [Section] of a WireGuard .conf, lowercased, with its key = value lines in order. @@ -629,6 +665,7 @@ def write_private(path: str, content: str) -> None: def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--manifest") + parser.add_argument("--config", metavar="CONFIG", help="render a .conf file, as a configFile manifest") parser.add_argument("--output") parser.add_argument( "--outbound-fwmark", @@ -636,6 +673,11 @@ def main() -> int: metavar="MARK", help="render for an outbound-only interface: no routes or DNS, packets marked MARK", ) + parser.add_argument( + "--wireproxy", + metavar="ADDRESS", + help="render for wireproxy, as a SOCKS5 listener on ADDRESS (packets marked with --outbound-fwmark)", + ) parser.add_argument( "--inspect", metavar="CONFIG", @@ -644,18 +686,25 @@ def main() -> int: args = parser.parse_args() try: if args.inspect is not None: - if args.manifest is not None or args.output is not None: + if args.manifest is not None or args.config is not None or args.output is not None: raise ConfigError("--inspect cannot be combined with rendering options") config = _read_limited(args.inspect) print(transport_implementation(config), probe_address(config), rekey_after_time(config)) return 0 - if args.manifest is None or args.output is None: - raise ConfigError("--manifest and --output are required when rendering a configuration") - manifest = json.loads(_read_limited(args.manifest)) + if (args.manifest is None) == (args.config is None) or args.output is None: + raise ConfigError( + "--output and one of --manifest or --config are required when rendering a configuration" + ) + if args.config is not None: + manifest = {"kind": "configFile", "path": args.config} + else: + manifest = json.loads(_read_limited(args.manifest)) if not isinstance(manifest, dict): raise ConfigError("manifest must be a JSON object") config = prepare(manifest) - if args.outbound_fwmark is not None: + if args.wireproxy is not None: + config = as_wireproxy(config, args.wireproxy, args.outbound_fwmark) + elif args.outbound_fwmark is not None: config = as_outbound(config, args.outbound_fwmark) write_private(args.output, config) except (ConfigError, KeyError, OSError, json.JSONDecodeError) as exc: diff --git a/scripts/test-amneziawg-config.py b/scripts/test-amneziawg-config.py index b90566e..8ea3cac 100644 --- a/scripts/test-amneziawg-config.py +++ b/scripts/test-amneziawg-config.py @@ -458,6 +458,28 @@ class AmneziaWgConfigTests(unittest.TestCase): # The peer is untouched. self.assertIn("Endpoint = vpn.example.com:51820", rendered) + def test_wireproxy_render_joins_lists_and_adds_socks_listener(self): + config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1").replace( + "Address = 10.8.0.2/32", + "Address = 10.8.0.2/32\nAddress = fd00::2/128\nTable = off\nPostUp = true\nDNS = 9.9.9.9", + ) + "AllowedIPs = ::/0\n\n[Peer]\nPublicKey = other\nAllowedIPs = 10.0.0.0/8\n" + rendered = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700", 2) + sections = amneziawg_config.conf_sections(rendered) + self.assertEqual([name for name, _ in sections], ["interface", "peer", "peer", "socks5"]) + interface = dict(sections[0][1]) + self.assertEqual(interface["address"], "10.8.0.2/32,fd00::2/128") + self.assertEqual(interface["dns"], "9.9.9.9,1.1.1.1") + self.assertEqual(interface["fwmark"], "2") + self.assertEqual(interface["headerprotectionkey"], "header") + self.assertNotIn("table", interface) + self.assertNotIn("postup", interface) + self.assertEqual(dict(sections[1][1])["allowedips"], "0.0.0.0/0,::/0") + self.assertEqual(dict(sections[2][1])["publickey"], "other") + self.assertEqual(sections[3][1], [("bindaddress", "127.0.0.1:18700")]) + # Rootless: no mark. + unmarked = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700") + self.assertEqual(amneziawg_config.section_values(unmarked, "interface", "fwmark"), []) + if __name__ == "__main__": unittest.main()