diff --git a/README.md b/README.md index deb08d4..a250416 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,8 @@ Changes and secrets need root or the userControl group. proxy outbounds add [tag] [--detour ] add an outbound from a link or JSON (-: stdin); --detour: connect through another outbound + proxy outbounds add [tag] [--container ] + add an AmneziaWG outbound (runs in wireproxy) proxy outbounds chain [new tag] add a copy of an outbound that connects through another proxy outbounds rm remove a runtime outbound @@ -186,6 +188,9 @@ Changes and secrets need root or the userControl group. awg [list] AmneziaWG profiles awg on | off [profile] | toggle [profile] | restart [profile] + awg add [name] [--container ] + add a global profile (-: stdin) + awg rm remove a profile added with awg add killswitch [status|on|off] block traffic outside the global tunnel; stays on until turned off here or with the tunnel diff --git a/docs/options/amneziaWg.md b/docs/options/amneziaWg.md index 706c0b7..35fc2ce 100644 --- a/docs/options/amneziaWg.md +++ b/docs/options/amneziaWg.md @@ -66,6 +66,9 @@ Part of the [proxy-suite options reference](./index.md). - [vpn](#services-proxy-suite-amneziawg-profiles-name-vpn) - [vpnContainer](#services-proxy-suite-amneziawg-profiles-name-vpncontainer) - [vpnFile](#services-proxy-suite-amneziawg-profiles-name-vpnfile) + - runtime + - [enable](#services-proxy-suite-amneziawg-runtime-enable) + - [interfaceName](#services-proxy-suite-amneziawg-runtime-interfacename) - [serverUdpPorts](#services-proxy-suite-amneziawg-serverudpports) - [toolsPackage](#services-proxy-suite-amneziawg-toolspackage) - [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage) @@ -548,6 +551,25 @@ File with a vpn:// export\. **Type:** null or string\ **Default:** `null` + +## services\.proxy-suite\.amneziaWg\.runtime\.enable + +Let ` proxy-ctl ` add configs and ` vpn:// ` links without a rebuild: ` proxy-ctl awg add ` +for a global profile (root hosts only), and ` proxy-ctl proxy outbounds add ` for an +outbound, which runs in wireproxy (needs ` proxy.enable `)\. wg-quick hooks such as +` PostUp ` are always refused in them\. With this on, ` profiles ` may be empty\. + +**Type:** boolean\ +**Default:** `true` + + +## services\.proxy-suite\.amneziaWg\.runtime\.interfaceName + +Interface of the global profiles added at runtime\. Only one of them runs at a time, so they share it\. + +**Type:** string matching the pattern ^\[A-Za-z0-9_\.-]{1,15}$\ +**Default:** `"awg-rt"` + ## services\.proxy-suite\.amneziaWg\.serverUdpPorts diff --git a/docs/options/inbounds.md b/docs/options/inbounds.md index 681321e..ab3cb8a 100644 --- a/docs/options/inbounds.md +++ b/docs/options/inbounds.md @@ -122,6 +122,7 @@ Part of the [proxy-suite options reference](./index.md). - [via](#services-proxy-suite-inbounds-routing-via) - [zapretDirect](#services-proxy-suite-inbounds-routing-zapretdirect) - [serverAddress](#services-proxy-suite-inbounds-serveraddress) + - [serverAliases](#services-proxy-suite-inbounds-serveraliases) - [shareLinks](#services-proxy-suite-inbounds-sharelinks) - subscriptions - [enable](#services-proxy-suite-inbounds-subscriptions-enable) @@ -1137,6 +1138,19 @@ Public address for share links\. ` null `: detect the uplink IPv4\. **Default:** `null`\ **Example:** `"vpn.example.com"` + +## services\.proxy-suite\.inbounds\.serverAliases + +Other names and IPs of this host that clients reach through the tunnel, such as a +TURN relay’s name beside the site on ` serverAddress `\. Like ` serverAddress `, they go +direct on the listener ports instead of looping back through ` routing.via `, which +often cannot reach this host at all\. List the IPs too: a client that resolves a name +itself hands XRay the address, which no name rule matches\. + +**Type:** list of string matching the pattern \[^\[:space:]]+\ +**Default:** `[ ]`\ +**Example:** `[ "turn.example.com" "203.0.113.10" "2001:db8::10" ]` + ## services\.proxy-suite\.inbounds\.shareLinks diff --git a/docs/options/index.md b/docs/options/index.md index ed98763..360ca53 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -43,6 +43,10 @@ services.proxy-suite = { enable = false; kernelModulePackage = ‹amneziawg from boot.kernelPackages on NixOS, null elsewhere›; profiles = { }; + runtime = { + enable = true; + interfaceName = "awg-rt"; + }; serverUdpPorts = [ ]; toolsPackage = ‹proxy-suite's patched amneziawg-tools (pkgs/amneziawg.nix)›; userspacePackage = ‹proxy-suite's patched amneziawg-go (pkgs/amneziawg.nix)›; @@ -81,6 +85,7 @@ services.proxy-suite = { zapretDirect = true; }; serverAddress = null; + serverAliases = [ ]; shareLinks = true; subscriptions = { baseUrl = null; diff --git a/docs/options/userControl.md b/docs/options/userControl.md index 8a323fe..fa98a4c 100644 --- a/docs/options/userControl.md +++ b/docs/options/userControl.md @@ -41,7 +41,10 @@ What the group may do\. Empty allows everything\. - “zapret”: change zapret2’s learned sites, and ` zapret cutoff probe `\. - “stats”: ` inbounds stats `\. - “whitelistBypass”: everything under ` proxy-ctl wl `\. + - “amneziaWg”: add and remove global AmneziaWG profiles (` proxy-ctl awg add `, ` awg rm `)\. + A global profile takes over the host’s routes and DNS\. Starting and stopping one is + “services”; an AmneziaWG outbound is “outbounds”\. -**Type:** list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “whitelistBypass”)\ +**Type:** list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “whitelistBypass”, “amneziaWg”)\ **Default:** `[ ]`\ **Example:** `[ "services" "routing" ]` diff --git a/docs/usage/.snippets/amneziawg-3.nix b/docs/usage/.snippets/amneziawg-3.nix new file mode 100644 index 0000000..a518e25 --- /dev/null +++ b/docs/usage/.snippets/amneziawg-3.nix @@ -0,0 +1,11 @@ +{ config, lib, pkgs, ... }: +{ + services.proxy-suite = { + enable = true; + amneziaWg.enable = true; # no profiles needed + userControl = { + enable = true; + scopes = [ "services" "amneziaWg" "outbounds" ]; # optional: no sudo for these + }; +}; +} diff --git a/docs/usage/amneziawg.md b/docs/usage/amneziawg.md index 0f47396..b3e4bed 100644 --- a/docs/usage/amneziawg.md +++ b/docs/usage/amneziawg.md @@ -64,6 +64,43 @@ host's routes and DNS alone. Use it like any other outbound: for selection, in | `"userspace"` | yes | no | Runs in wireproxy. The only mode on home-manager and Nix-on-Droid. | | `"singBox"` | no | no | Plain WireGuard inside sing-box. For servers without obfuscation, such as WARP. | +## Add one without rebuilding + +`amneziaWg.enable` alone is enough: profiles and outbounds can come from `proxy-ctl` instead +of the config. + +```nix +services.proxy-suite = { + enable = true; + amneziaWg.enable = true; # no profiles needed + userControl = { + enable = true; + scopes = [ "services" "amneziaWg" "outbounds" ]; # optional: no sudo for these + }; +}; +``` + +```sh +proxy-ctl awg add vpn://AAAA… # named after the export, or the server's host +proxy-ctl awg add home ~/home.conf # a name first; a link, a file, or - for stdin +proxy-ctl awg on home +proxy-ctl awg rm home +proxy-ctl proxy outbounds add de ~/de.conf # an outbound instead (needs proxy.enable) +``` + +- A global profile works like a declared one: `awg on`, the tray menu, the kill switch. The + ones added this way share one interface, `amneziaWg.runtime.interfaceName`. +- An outbound runs in wireproxy (like `asOutbound = "userspace"`), so the obfuscation stays. + It cannot chain through another outbound. +- In `proxy-tui` and the desktop app, paste a `vpn://` link or a whole `.conf` onto a tab: on + the Outbounds tab it becomes an outbound, anywhere else a global profile. The AmneziaWG tab + also adds one from a prompt, and removes what was added. +- Hooks (`PostUp` and the like) are always refused, whoever adds the config. + `--container ` picks one from a `vpn://` export that holds several. +- Adding and removing takes root, or a `userControl` scope: `amneziaWg` for global profiles, + `outbounds` for outbounds. Turning a profile on and off is `services`. +- They are kept across reboots. `amneziaWg.runtime.enable = false` turns all of this off. + ## Good to know - A profile that stops getting handshake replies moves to a new source port on its own. @@ -77,5 +114,6 @@ host's routes and DNS alone. Use it like any other outbound: for selection, in ## See also - [`amneziaWg.profiles`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles) +- [`amneziaWg.runtime`](../options/amneziaWg.md#services-proxy-suite-amneziawg-runtime-enable) - [`asOutbound`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles-name-asoutbound) - [`settings`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles-name-settings) diff --git a/docs/usage/control.md b/docs/usage/control.md index 71b97c2..76329e3 100644 --- a/docs/usage/control.md +++ b/docs/usage/control.md @@ -37,7 +37,8 @@ Members of the group get the listed scopes. An empty `scopes` list grants all of |---|---| | `services` | turning services on, off and restarting them | | `routing` | `proxy pin`, `proxy unpin`, `proxy mode` | -| `outbounds` | adding, removing, enabling and disabling outbounds and subscriptions | +| `outbounds` | adding, removing, enabling and disabling outbounds and subscriptions, AmneziaWG outbounds included | +| `amneziaWg` | `awg add` and `awg rm`: global AmneziaWG profiles, which take over the host's routes and DNS | | `perApp` | `apps run` with `tun`, `tproxy` and `zapret` profiles | | `secrets` | reading share links, subscription URLs and running configs | | `autoProxy`, `zapret`, `stats`, `whitelistBypass` | the matching `proxy-ctl` groups | @@ -49,13 +50,19 @@ admin password, or you run `proxy-ctl` with sudo. | Change | Lasts | |---|---| -| `proxy outbounds add`, `proxy subs add` | until removed with `rm`; kept across reboots | +| `proxy outbounds add`, `proxy subs add`, `awg add` | until removed with `rm`; kept across reboots | | `proxy outbounds disable` | until `enable`; works on outbounds from Nix too | | `proxy pin` | until `unpin`; kept across reboots | | `proxy mode` | until the next reboot | | `… on` / `… off` | until the next reboot; boot state comes from the config | -Outbounds from the Nix config cannot be removed at runtime, only disabled. +Outbounds from the Nix config cannot be removed at runtime, only disabled. The same goes for +AmneziaWG profiles: `awg rm` only removes those added with `awg add`. + +In the TUI and the app, pasting a link onto a tab adds it there: a share link becomes an +outbound, a subscription URL a subscription. An AmneziaWG `vpn://` link or a whole `.conf` +becomes a global profile, or an outbound when pasted onto the Outbounds tab. See +[Use an AmneziaWG config](./amneziawg.md). ## Commands diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index a0ea2cc..bc068ee 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -16,6 +16,11 @@ let awgGlobalGroup awgOutboundRulePriority awgServerUdpRulePriority + runtimeAwgDir + runtimeOutboundsDir + awgRuntimeTunnelBasePort + awgRuntimeTunnelSlots + systemctl ; killSwitchUnit = "proxy-suite-killswitch.service"; # Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick. @@ -91,8 +96,63 @@ let ); configTool = "${import ./lib/scripts-dir.nix { inherit lib; }}/amneziawg_config.py"; awgCommon = import ./awg-common.nix { inherit lib pkgs awgCfg; }; - runtimeDir = name: "/run/${serviceName name}"; - runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf"; + + # What a unit's scripts know of the profile they run. `init` is their first line and sets + # $profile_name; `runDir` is the runtime directory, as shell text; `source` the arguments + # amneziawg_config.py reads the profile with; `outbound` whether it is an "interface" one. + staticSpec = name: profile: { + inherit name profile; + template = false; + unit = serviceName name; + init = "profile_name=${lib.escapeShellArg name}"; + runDir = "/run/${serviceName name}"; + runtimeDirectory = serviceName name; + source = "--manifest ${lib.escapeShellArg (toString (manifestFor profile))}"; + outbound = profile.asOutbound == "interface"; + }; + + # Global profiles added with `proxy-ctl awg add`: instances of one template, the name + # passed in as $1 (%i), the .conf in runtimeAwgDir. They share an interface, and hooks are + # refused (--config), since whoever added one need not be root. + runtimeProfile = { + inherit (awgCfg.runtime) interfaceName; + asOutbound = null; + autostart = false; + settings = null; + }; + runtimeSpec = { + name = "$profile_name"; + profile = runtimeProfile; + template = true; + unit = "proxy-suite-awg@"; + init = '' + profile_name=''${1:-} + if [[ ! $profile_name =~ ^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$ ]]; then + echo "proxy-suite: '$profile_name' is not an AmneziaWG profile name" >&2 + exit 1 + fi + ''; + runDir = "/run/proxy-suite-awg-rt-$profile_name"; + runtimeDirectory = "proxy-suite-awg-rt-%i"; + source = ''--config "${runtimeAwgDir}/$profile_name.conf"''; + outbound = false; + }; + specConfig = spec: "${spec.runDir}/${spec.profile.interfaceName}.conf"; + + # Runtime profiles cannot be named in Conflicts= at build time, and share one interface: + # starting any global profile stops the runtime ones still up. $1: its own instance, if one. + stopRuntimeProfiles = pkgs.writeShellScript "proxy-suite-awg" '' + set -uo pipefail + self="proxy-suite-awg@''${1:-}.service" + # A failed unit's line starts with a glyph: take the name wherever it is. + ${systemctl} list-units --plain --no-legend --state=active,activating,reloading 'proxy-suite-awg@*.service' \ + | ${pkgs.gnugrep}/bin/grep -o 'proxy-suite-awg@[^ ]*\.service' \ + | while read -r unit; do + [[ $unit == "$self" ]] || ${systemctl} stop "$unit" || true + done + # grep finds nothing when none is up, which pipefail would make this script's failure. + exit 0 + ''; # Keep proxy backend sockets (proxyMark) out of AWG's default-route table. proxyBypassRulePriority = 8998; bypassRule = @@ -211,14 +271,15 @@ let # awg-quick turns src_valid_mark on for a default route and never back off; left on, it # changes how the kernel checks every marked packet's source. Put back as it was. srcValidMark = "/proc/sys/net/ipv4/conf/all/src_valid_mark"; - savedSrcValidMark = name: "${runtimeDir name}/src_valid_mark"; - saveSrcValidMark = name: '' - [[ -e ${savedSrcValidMark name} ]] || cat ${srcValidMark} > ${savedSrcValidMark name} + # Unquoted: a runtime profile's name is checked against [A-Za-z0-9_-] first (runtimeSpec). + savedSrcValidMark = spec: "${spec.runDir}/src_valid_mark"; + saveSrcValidMark = spec: '' + [[ -e ${savedSrcValidMark spec} ]] || cat ${srcValidMark} > ${savedSrcValidMark spec} ''; - restoreSrcValidMark = name: '' - if [[ -s ${savedSrcValidMark name} ]]; then - cat ${savedSrcValidMark name} > ${srcValidMark} || true - rm -f ${savedSrcValidMark name} + restoreSrcValidMark = spec: '' + if [[ -s ${savedSrcValidMark spec} ]]; then + cat ${savedSrcValidMark spec} > ${srcValidMark} || true + rm -f ${savedSrcValidMark spec} fi ''; @@ -233,15 +294,15 @@ let # An outbound interface keeps the host's routes and resolver, and marks its packets so TUN and # TProxy let them past. A global one under the kill switch marks them with a mark it knows. - prepareCommand = profile: output: '' + prepareCommand = spec: output: '' ${pkgs.python3}/bin/python3 ${configTool} \ - --manifest ${lib.escapeShellArg (toString (manifestFor profile))} \ + ${spec.source} \ --output ${output}${ - if profile.asOutbound == "interface" then + if spec.profile.asOutbound == "interface" then " --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}" else lib.optionalString ( - derived.killSwitchEnabled && profile.asOutbound == null + derived.killSwitchEnabled && spec.profile.asOutbound == null ) " --fwmark ${toString awgGlobalFwmark} --resolve-endpoints" } ''; @@ -259,19 +320,27 @@ let exec "$@" ''; + # A global profile, or an "interface" outbound: a unit for a declared profile (staticSpec), + # or the template the runtime ones start from (runtimeSpec). `conflicts`: the global units + # it stops by starting. mkService = - name: profile: + spec: conflicts: let - outbound = profile.asOutbound == "interface"; - configPath = runtimeConfig name profile; - prepare = pkgs.writeShellScript "proxy-suite-awg" '' + inherit (spec) name profile outbound; + configPath = specConfig spec; + # Every script: a template's instance name comes in as $1. + withInit = body: '' + ${spec.init} + ${body} + ''; + prepare = pkgs.writeShellScript "proxy-suite-awg" (withInit '' set -euo pipefail ${ lib.optionalString ( derived.killSwitchEnabled && !outbound ) "${pkgs.util-linux}/bin/unshare --mount ${ownLookups} " - }${prepareCommand profile (lib.escapeShellArg configPath)} - ''; + }${prepareCommand spec ''"${configPath}"''} + ''); proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" '' set -euo pipefail ${clearBypassRules} @@ -286,12 +355,12 @@ let set +e ${clearBypassRules} ''; - start = pkgs.writeShellScript "proxy-suite-awg" '' + start = pkgs.writeShellScript "proxy-suite-awg" (withInit '' set -Eeuo pipefail cleanup() { set +e - ${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath} + ${awgCfg.toolsPackage}/bin/awg-quick down "${configPath}" # Without the control socket awg-quick cannot find its fwmark; clean up this # interface only. @@ -318,7 +387,7 @@ let if outbound then outboundRuleCleanup name profile else - repliesDown profile + restoreSrcValidMark name + repliesDown profile + restoreSrcValidMark spec } } trap cleanup ERR @@ -326,9 +395,9 @@ let ${awgCommon.modprobe} read -r implementation probe _ < <(${pkgs.python3}/bin/python3 ${configTool} \ - --inspect ${lib.escapeShellArg configPath}) - ${lib.optionalString (!outbound) (saveSrcValidMark name)} - ${awgCommon.awgQuickUp "$implementation" (lib.escapeShellArg configPath)} + --inspect "${configPath}") + ${lib.optionalString (!outbound) (saveSrcValidMark spec)} + ${awgCommon.awgQuickUp "$implementation" ''"${configPath}"''} ${if outbound then outboundRoutesUp name profile else repliesUp profile} ${mkHandshakeHelpers profile} @@ -344,21 +413,23 @@ let fi done - echo "proxy-suite: AmneziaWG profile '${name}' did not complete a handshake; rolling back routes" >&2 + echo "proxy-suite: AmneziaWG profile '$profile_name' did not complete a handshake; rolling back routes" >&2 false - ''; - stop = pkgs.writeShellScript "proxy-suite-awg" '' + ''); + stop = pkgs.writeShellScript "proxy-suite-awg" (withInit '' set -uo pipefail status=0 - ${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath} || status=$? + ${awgCfg.toolsPackage}/bin/awg-quick down "${configPath}" || status=$? ${ if outbound then outboundRuleCleanup name profile else - repliesDown profile + restoreSrcValidMark name + repliesDown profile + restoreSrcValidMark spec } exit "$status" - ''; + ''); + # A template's scripts get the instance name. + withArg = script: if spec.template then "${script} %i" else script; in ( if outbound then @@ -372,7 +443,11 @@ let } else { - description = "proxy-suite AmneziaWG client profile ${name}"; + description = + if spec.template then + "proxy-suite AmneziaWG client profile %i (added at runtime)" + else + "proxy-suite AmneziaWG client profile ${name}"; # Start the local proxy before AWG takes the default route, so HTTP_PROXY clients # do not race it. after = [ @@ -386,7 +461,7 @@ let ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service" ++ lib.optional derived.killSwitchEnabled killSwitchUnit; wantedBy = lib.optionals profile.autostart [ "multi-user.target" ]; - conflicts = allProfileConflicts name ++ [ + conflicts = conflicts ++ [ "proxy-suite-tun.service" "proxy-suite-tproxy.service" "proxy-suite-zapret.service" @@ -410,7 +485,7 @@ let serviceConfig = { Type = "oneshot"; RemainAfterExit = true; - RuntimeDirectory = serviceName name; + RuntimeDirectory = spec.runtimeDirectory; RuntimeDirectoryMode = "0700"; UMask = "0077"; NoNewPrivileges = true; @@ -421,9 +496,14 @@ let ProtectKernelLogs = true; RestrictRealtime = true; RestrictSUIDSGID = true; - ExecStartPre = [ prepare ] ++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ]; - ExecStart = start; - ExecStop = stop; + # Another profile stopping clears the bypass rules on its way out: before they go in. + ExecStartPre = [ + (withArg prepare) + ] + ++ lib.optionals (!outbound && derived.awgRuntimeGlobal) [ (withArg stopRuntimeProfiles) ] + ++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ]; + ExecStart = withArg start; + ExecStop = withArg stop; } // lib.optionalAttrs (cfg.proxy.enable && !outbound) { ExecStopPost = proxyBypassDown; @@ -464,10 +544,81 @@ let fi ''} profile="$RUNTIME_DIRECTORY/profile.conf" - ${prepareCommand profile ''"$profile"''} + ${prepareCommand (staticSpec ob.name profile) ''"$profile"''} ''; }; + # Outbounds added with `proxy-ctl proxy outbounds add`: .awg in the runtime outbound + # spool, and the loopback port proxy-ctl gave it in .port. They run in wireproxy, + # which keeps the obfuscation; --config refuses hooks, as the spool is group-writable. + runtimeTunnelLastPort = awgRuntimeTunnelBasePort + awgRuntimeTunnelSlots - 1; + runtimeTunnelService = mkTunnel { + description = "proxy-suite AmneziaWG tunnel behind the %i outbound (added at runtime)"; + unit = "proxy-suite-awg-tunnel@"; + runtimeDirectory = "proxy-suite-awg-tunnel-%i"; + engine = "userspace"; + tag = "$TUNNEL_TAG"; + tunnelPort = "$TUNNEL_PORT"; + execArgs = " %i"; + # The sync unit starts one per entry. + wantedBy = [ ]; + # A removed entry exits cleanly, and stays stopped. + restart = "on-failure"; + profile = '' + TUNNEL_TAG=''${1:-} + if [[ ! $TUNNEL_TAG =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then + echo "proxy-suite: '$TUNNEL_TAG' is not an outbound tag" >&2 + exit 1 + fi + profile="${runtimeOutboundsDir}/$TUNNEL_TAG.awg" + if [[ ! -s $profile ]]; then + echo "proxy-suite: no AmneziaWG outbound '$TUNNEL_TAG' in ${runtimeOutboundsDir}" >&2 + exit 0 + fi + TUNNEL_PORT=$(${pkgs.coreutils}/bin/head -n 1 "${runtimeOutboundsDir}/$TUNNEL_TAG.port" 2>/dev/null || true) + if [[ ! $TUNNEL_PORT =~ ^[0-9]+$ ]] || (( TUNNEL_PORT < ${toString awgRuntimeTunnelBasePort} || TUNNEL_PORT > ${toString runtimeTunnelLastPort} )); then + echo "proxy-suite: AmneziaWG outbound '$TUNNEL_TAG' needs a port in ${toString awgRuntimeTunnelBasePort}-${toString runtimeTunnelLastPort} in $TUNNEL_TAG.port" >&2 + exit 1 + fi + export TUNNEL_TAG TUNNEL_PORT + ''; + }; + + # One tunnel per runtime AmneziaWG outbound, and none for an entry removed since: at boot, + # and with every proxy-suite-outbound-reload, which proxy-ctl starts after a change. + runtimeSyncService = { + description = "proxy-suite AmneziaWG outbounds added at runtime"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + wantedBy = [ + "multi-user.target" + "proxy-suite-outbound-reload.service" + ]; + serviceConfig = { + Type = "oneshot"; + ExecStart = pkgs.writeShellScript "proxy-suite-awg" '' + set -uo pipefail + declare -A keep=() + for entry in "${runtimeOutboundsDir}"/*.awg; do + [[ -e $entry ]] || continue + tag=''${entry##*/} + tag=''${tag%.awg} + keep[$tag]=1 + ${systemctl} start --no-block "proxy-suite-awg-tunnel@$tag.service" || true + done + ${systemctl} list-units --all --plain --no-legend 'proxy-suite-awg-tunnel@*.service' \ + | ${pkgs.gnugrep}/bin/grep -o 'proxy-suite-awg-tunnel@[^ ]*\.service' \ + | while read -r unit; do + tag=''${unit#proxy-suite-awg-tunnel@} + tag=''${tag%.service} + [[ -n ''${keep[$tag]:-} ]] || ${systemctl} stop --no-block "$unit" || true + done + # grep finds nothing when no tunnel is loaded, which pipefail would make a failure. + exit 0 + ''; + }; + }; + # Runs alongside a started profile. Its pings keep traffic flowing, and traffic makes # WireGuard rekey every RekeyAfterTime (120 seconds by default); a handshake older than that # on two checks in a row is a rekey that is not getting through, so the interface moves to @@ -477,15 +628,18 @@ let # peer can keep rekeying while carrying no traffic. After three misses the peer is re-added # for a fresh session (a new port alone keeps the old one), at most once in five minutes. mkWatchdog = - name: profile: + spec: let + inherit (spec) profile; egressProbe = profile.asOutbound == "interface"; + unit = if spec.template then "proxy-suite-awg@%i.service" else "${spec.unit}.service"; watchdog = pkgs.writeShellScript "proxy-suite-awg" '' + ${spec.init} set -uo pipefail read -r _ probe rekey < <(${pkgs.python3}/bin/python3 ${configTool} \ - --inspect ${lib.escapeShellArg (runtimeConfig name profile)}) || exit 1 + --inspect "${specConfig spec}") || exit 1 if (( rekey == 0 )); then - echo "proxy-suite: AmneziaWG profile '${name}' never rekeys; nothing to watch" >&2 + echo "proxy-suite: AmneziaWG profile '$profile_name' never rekeys; nothing to watch" >&2 exec ${pkgs.coreutils}/bin/sleep infinity fi ${mkHandshakeHelpers profile} @@ -512,7 +666,7 @@ let if (( $(handshake_age) <= rekey + 10 )); then stale=0 elif (( ++stale >= 2 )); then - echo "proxy-suite: AmneziaWG profile '${name}' is not rekeying; moving to a new source port" >&2 + echo "proxy-suite: AmneziaWG profile '$profile_name' is not rekeying; moving to a new source port" >&2 new_source_port stale=0 ${lib.optionalString egressProbe "continue"} @@ -522,7 +676,7 @@ let ${lib.escapeShellArg cfg.proxy.urlTest.url}; then misses=0 elif (( ++misses >= 3 && SECONDS - last_session >= 300 )); then - echo "proxy-suite: AmneziaWG profile '${name}' carries no IPv4 past its peer; starting a new session" >&2 + echo "proxy-suite: AmneziaWG profile '$profile_name' carries no IPv4 past its peer; starting a new session" >&2 new_session misses=0 last_session=$SECONDS @@ -532,12 +686,15 @@ let ''; in { - description = "proxy-suite AmneziaWG client profile ${name} watchdog"; - bindsTo = [ "${serviceName name}.service" ]; - after = [ "${serviceName name}.service" ]; - wantedBy = [ "${serviceName name}.service" ]; + description = "proxy-suite AmneziaWG client profile ${ + if spec.template then "%i" else spec.name + } watchdog"; + bindsTo = [ unit ]; + after = [ unit ]; + # A template's instances are pulled in by the profile's own Wants=. + wantedBy = lib.optional (!spec.template) unit; serviceConfig = { - ExecStart = watchdog; + ExecStart = if spec.template then "${watchdog} %i" else watchdog; Restart = "on-failure"; RestartSec = 5; CapabilityBoundingSet = [ @@ -620,7 +777,9 @@ let ) ) profileNames; - interfaceNames = map (name: profiles.${name}.interfaceName) profileNames; + interfaceNames = + map (name: profiles.${name}.interfaceName) profileNames + ++ lib.optional derived.awgRuntimeGlobal awgCfg.runtime.interfaceName; autostartProfiles = builtins.filter (name: profiles.${name}.autostart) globalProfileNames; globalAutostartCount = builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0); @@ -630,10 +789,12 @@ in awgCfg.toolsPackage awgCfg.userspacePackage ] - ++ lib.optional (builtins.any (ob: ob.kind == "userspace") tunnelOutbounds) awgCfg.wireproxyPackage; + ++ lib.optional ( + derived.awgRuntimeOutbounds || builtins.any (ob: ob.kind == "userspace") tunnelOutbounds + ) awgCfg.wireproxyPackage; services.proxy-suite.internal.groups = lib.optional ( - derived.killSwitchEnabled && globalProfileNames != [ ] + derived.killSwitchEnabled && derived.awgGlobalAvailable ) awgGlobalGroup; services.proxy-suite.internal.kernelModulePackages = @@ -649,11 +810,30 @@ in services.proxy-suite.internal.services = lib.mkMerge [ (lib.mapAttrs' ( - name: profile: lib.nameValuePair (serviceName name) (mkService name profile) + name: profile: + lib.nameValuePair (serviceName name) ( + mkService (staticSpec name profile) (allProfileConflicts name) + ) ) interfaceProfiles) (lib.mapAttrs' ( - name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile) + name: profile: + lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog (staticSpec name profile)) ) interfaceProfiles) + (lib.mkIf derived.awgRuntimeGlobal { + "proxy-suite-awg@" = lib.mkMerge [ + (mkService runtimeSpec (map (other: "${serviceName other}.service") globalProfileNames)) + { + wants = [ "proxy-suite-awg-watchdog@%i.service" ]; + # The kill switch cannot order itself after instances it does not know. + before = [ killSwitchUnit ]; + } + ]; + "proxy-suite-awg-watchdog@" = mkWatchdog runtimeSpec; + }) + (lib.mkIf derived.awgRuntimeOutbounds { + "proxy-suite-awg-tunnel@" = runtimeTunnelService; + proxy-suite-awg-runtime-sync = runtimeSyncService; + }) (lib.listToAttrs ( map (ob: lib.nameValuePair (serviceName ob.name) (mkTunnelService ob)) tunnelOutbounds )) @@ -667,8 +847,8 @@ in assertions = profileAssertions ++ [ { - assertion = profiles != { }; - message = "proxy-suite: amneziaWg.enable requires at least one profile"; + assertion = profiles != { } || derived.awgRuntimeGlobal || derived.awgRuntimeOutbounds; + message = "proxy-suite: amneziaWg.enable needs a profile, or amneziaWg.runtime.enable for profiles added with proxy-ctl (global ones need a root host, outbounds proxy.enable)"; } { assertion = builtins.length interfaceNames == builtins.length (lib.unique interfaceNames); diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 81ff881..0483b39 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -59,7 +59,7 @@ let # Some global tunnel for it to guard. killSwitchEnabled = cfg.killSwitch.enable - && (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalProfiles != { }); + && (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalAvailable); perAppRoutingTun = cfg.perAppRouting.tun; perAppRoutingTproxy = cfg.perAppRouting.tproxy; zapretCfg = cfg.zapret; @@ -158,6 +158,14 @@ let } ) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles)); awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds; + # Added with proxy-ctl at runtime: global profiles (`awg add`), as template instances + # sharing runtime.interfaceName, need root; outbounds (`proxy outbounds add`) run in + # wireproxy template instances, which the supervisor cannot template. + awgRuntimeEnabled = cfg.amneziaWg.enable && cfg.amneziaWg.runtime.enable; + awgRuntimeGlobal = awgRuntimeEnabled && cfg.host.privileged; + awgRuntimeOutbounds = awgRuntimeEnabled && proxyEnabled && cfg.host.serviceManager != "supervisor"; + # Some global profile may run: declared, or added at runtime. + awgGlobalAvailable = awgGlobalProfiles != { } || awgRuntimeGlobal; # Profiles run behind a loopback SOCKS hop rather than an interface. awgTunnelOutbounds = builtins.filter (ob: ob.kind != "interface") awgOutbounds; @@ -442,6 +450,12 @@ let awgOutboundRulePriority = 8991; # A global AmneziaWG profile's rules keeping the host's UDP services on the main table. awgServerUdpRulePriority = 8989; + # Global profiles and outbounds added with proxy-ctl: .conf here, and + # .awg with .port in runtimeOutboundsDir. + runtimeAwgDir = "${stateDir}/amneziawg.d"; + # Loopback SOCKS listeners of the runtime AmneziaWG outbounds, one per slot. + awgRuntimeTunnelBasePort = 18800; + awgRuntimeTunnelSlots = 32; # sing-box's fake IP caches, one per TUN config; the start script hands it to the backend. fakeIpCacheDir = "${stateDir}/fakeip"; # Downloaded proxy.routing.ruleSets, one file each, written by the service user. @@ -550,6 +564,9 @@ in torOnionInbounds proxyInboundOnionCapable awgGlobalProfiles + awgGlobalAvailable + awgRuntimeGlobal + awgRuntimeOutbounds awgOutbounds awgInterfaceOutbounds awgTunnelOutbounds diff --git a/modules/proxy-suite/nftables.nix b/modules/proxy-suite/nftables.nix index d333587..9e71379 100644 --- a/modules/proxy-suite/nftables.nix +++ b/modules/proxy-suite/nftables.nix @@ -6,7 +6,12 @@ }: let - inherit (import ./derived.nix { inherit lib cfg; }) constants awgGlobalProfiles; + inherit (import ./derived.nix { inherit lib cfg; }) + constants + awgGlobalProfiles + awgGlobalAvailable + awgRuntimeGlobal + ; inherit (constants) serviceUser; proxyCfg = cfg.proxy; globalTproxy = proxyCfg.tproxy; @@ -158,8 +163,10 @@ let ++ lib.optional perAppTun.enable perAppTun.fwmark ++ lib.optional perAppTproxy.enable perAppTproxy.fwmark ++ lib.optional tgWsProxyBypassEnabled tgWsProxyCfg.fwmark - ++ lib.optional (awgGlobalProfiles != { }) constants.awgGlobalFwmark; - awgGlobalInterfaces = lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles; + ++ lib.optional awgGlobalAvailable constants.awgGlobalFwmark; + awgGlobalInterfaces = + lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles + ++ lib.optional awgRuntimeGlobal cfg.amneziaWg.runtime.interfaceName; globalTunEnabled = proxyCfg.enable && proxyCfg.tun.enable; killSwitchAllowLines = '' ip daddr $RESERVED_IP accept @@ -183,7 +190,7 @@ let ip daddr ${proxyCfg.tun.address} accept ${lib.optionalString proxyCfg.ipv6 "ip6 daddr ${constants.globalTunIPv6Address} accept"} ''} - ${lib.optionalString (awgGlobalProfiles != { }) '' + ${lib.optionalString awgGlobalAvailable '' oifname { ${lib.concatMapStringsSep ", " (i: ''"${i}"'') awgGlobalInterfaces} } accept meta skgid "${constants.awgGlobalGroup}" accept ''} diff --git a/modules/proxy-suite/options/amnezia-wg.nix b/modules/proxy-suite/options/amnezia-wg.nix index 9d56869..b037c4b 100644 --- a/modules/proxy-suite/options/amnezia-wg.nix +++ b/modules/proxy-suite/options/amnezia-wg.nix @@ -66,6 +66,25 @@ in ]; }; + runtime = { + enable = mkOption { + type = types.bool; + default = true; + description = '' + Let `proxy-ctl` add configs and `vpn://` links without a rebuild: `proxy-ctl awg add` + for a global profile (root hosts only), and `proxy-ctl proxy outbounds add` for an + outbound, which runs in wireproxy (needs `proxy.enable`). wg-quick hooks such as + `PostUp` are always refused in them. With this on, `profiles` may be empty. + ''; + }; + + interfaceName = mkOption { + type = types.strMatching "^[A-Za-z0-9_.-]{1,15}$"; + default = "awg-rt"; + description = "Interface of the global profiles added at runtime. Only one of them runs at a time, so they share it."; + }; + }; + profiles = mkOption { type = types.attrsOf t.profileType; default = { }; diff --git a/modules/proxy-suite/options/inbounds.nix b/modules/proxy-suite/options/inbounds.nix index 178cf98..f5f2c49 100644 --- a/modules/proxy-suite/options/inbounds.nix +++ b/modules/proxy-suite/options/inbounds.nix @@ -30,6 +30,23 @@ in example = "vpn.example.com"; }; + serverAliases = mkOption { + type = types.listOf (types.strMatching "[^[:space:]]+"); + default = [ ]; + description = '' + Other names and IPs of this host that clients reach through the tunnel, such as a + TURN relay's name beside the site on `serverAddress`. Like `serverAddress`, they go + direct on the listener ports instead of looping back through `routing.via`, which + often cannot reach this host at all. List the IPs too: a client that resolves a name + itself hands XRay the address, which no name rule matches. + ''; + example = [ + "turn.example.com" + "203.0.113.10" + "2001:db8::10" + ]; + }; + openFirewall = bool true "Open the firewall for every listener not on loopback."; shareLinks = bool true "Generate client share links for `proxy-ctl inbounds link`. Readable by root, and by `userControl.group` with the secrets scope."; diff --git a/modules/proxy-suite/options/user-control.nix b/modules/proxy-suite/options/user-control.nix index fc80ae1..5c89815 100644 --- a/modules/proxy-suite/options/user-control.nix +++ b/modules/proxy-suite/options/user-control.nix @@ -25,6 +25,7 @@ in "zapret" "stats" "whitelistBypass" + "amneziaWg" ] ); default = [ ]; @@ -39,6 +40,9 @@ in - "zapret": change zapret2's learned sites, and `zapret cutoff probe`. - "stats": `inbounds stats`. - "whitelistBypass": everything under `proxy-ctl wl`. + - "amneziaWg": add and remove global AmneziaWG profiles (`proxy-ctl awg add`, `awg rm`). + A global profile takes over the host's routes and DNS. Starting and stopping one is + "services"; an AmneziaWG outbound is "outbounds". ''; example = [ "services" diff --git a/modules/proxy-suite/rules/proxy-inbounds.nix b/modules/proxy-suite/rules/proxy-inbounds.nix index fc48786..54ee62f 100644 --- a/modules/proxy-suite/rules/proxy-inbounds.nix +++ b/modules/proxy-suite/rules/proxy-inbounds.nix @@ -38,13 +38,15 @@ let }; # The address clients dial must stay reachable even when blockRu covers it - # (a .ru domain or IP). After blockPrivate, so it cannot open the LAN. - serverAddressIsIp = - let - addr = proxyInboundsCfg.serverAddress; - in - addr != null - && (lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null); + # (a .ru domain or IP). After blockPrivate, so it cannot open the LAN. Its aliases + # too: routing.via usually cannot loop back to this host, so they would fail there. + isIp = + addr: lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null; + serverAddresses = + lib.optional (proxyInboundsCfg.serverAddress != null) proxyInboundsCfg.serverAddress + ++ proxyInboundsCfg.serverAliases; + serverIps = lib.unique (builtins.filter isIp serverAddresses); + serverNames = lib.unique (builtins.filter (addr: !isIp addr) serverAddresses); # Only the ports clients dial there: the rest of this host (wildcard services the # firewall keeps from the internet) must not be reachable through it. @@ -59,23 +61,23 @@ let ] ); + # Names and IPs in rules of their own: XRay ANDs the fields of one rule. + mkServerAddressRule = + ruleTag: field: items: + lib.optional (items != [ ] && exceptionInboundTags != [ ]) { + type = "field"; + inherit ruleTag; + ${field} = items; + inboundTag = exceptionInboundTags; + port = lib.concatMapStringsSep "," toString serverAddressPorts; + outboundTag = "direct"; + }; + serverAddressRule = - lib.optional (proxyInboundsCfg.serverAddress != null && exceptionInboundTags != [ ]) - ( - { - type = "field"; - ruleTag = "inbound-server-address-direct"; - inboundTag = exceptionInboundTags; - port = lib.concatMapStringsSep "," toString serverAddressPorts; - outboundTag = "direct"; - } - // ( - if serverAddressIsIp then - { ip = [ proxyInboundsCfg.serverAddress ]; } - else - { domain = [ "full:${proxyInboundsCfg.serverAddress}" ]; } - ) - ); + mkServerAddressRule "inbound-server-address-direct" "domain" ( + map (name: "full:${name}") serverNames + ) + ++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps; blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [ { diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 25dce1d..47ed858 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -82,7 +82,12 @@ let ++ map (j: j.port) derived.whitelistBypassJoiners ++ lib.optionals derived.proxyInboundsEnabled ( map (listener: listener.internalPort) derived.proxyInboundsAwg - ); + ) + ++ awgRuntimeTunnelPorts; + # The loopback listeners of AmneziaWG outbounds added at runtime, one per slot. + awgRuntimeTunnelPorts = lib.optionals derived.awgRuntimeOutbounds ( + lib.genList (i: constants.awgRuntimeTunnelBasePort + i) constants.awgRuntimeTunnelSlots + ); # A rootless host (home-manager, nix-on-droid) runs everything as the user: nothing # that programs routing, firewalls or interfaces, and no privileged ports. @@ -274,7 +279,7 @@ let (mkAssertion ( !derived.killSwitchEnabled - || derived.awgGlobalProfiles == { } + || !derived.awgGlobalAvailable || !builtins.elem constants.awgGlobalFwmark ( [ globalTproxy.fwmark @@ -461,11 +466,12 @@ let !proxyInboundsEnabled || !lib.any (port: builtins.elem port derived.proxyInboundPorts) ( map (listener: listener.internalPort) derived.proxyInboundsAwg + ++ awgRuntimeTunnelPorts ++ builtins.attrValues derived.constants.xrayDnsBridgePorts ++ lib.optionals hybridEnabled (builtins.attrValues derived.constants.xraySidecarPorts) ) ) - "proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, 18533-18535, or the hybrid XRay sidecar's 33080, 33180 and 33280)" + "proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, the runtime AmneziaWG outbounds' 18800-18831, 18533-18535, or the hybrid XRay sidecar's 33080, 33180 and 33280)" ) # The prober opens one loopback listener per exit from probeBasePort; the WARP # and AmneziaWG tunnels open two each from their own bases. They all bind @@ -764,7 +770,8 @@ let map (ib: ib.listener.amneziaWg.interfaceName) awgListeners ++ lib.optionals cfg.amneziaWg.enable ( lib.mapAttrsToList (_: profile: profile.interfaceName) cfg.amneziaWg.profiles - ); + ) + ++ lib.optional derived.awgRuntimeGlobal cfg.amneziaWg.runtime.interfaceName; otherInterfaces = lib.optional (proxyEnabled && globalTun.enable) globalTun.interface ++ lib.optional (perAppRoutingCfg.enable && perAppRoutingTun.enable) perAppRoutingTun.interface; diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 7e72e14..af4f155 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -22,6 +22,9 @@ let proxyInboundsCfg proxyInboundsEnabled amneziaWgProfileNamesFile + awgRuntimeGlobal + awgRuntimeOutbounds + proxySuiteScriptsDir ruleSets pkgs ; @@ -73,6 +76,13 @@ in ROUTE_MODE_STATE_FILE = routeModeStateFile; DEFAULT_ROUTE_MODE = if proxyCfg.routing.default == "proxy" then "blacklist" else "whitelist"; AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile; + # Profiles and outbounds added with `awg add` and `proxy outbounds add`. + AWG_RUNTIME_GLOBAL = flag awgRuntimeGlobal; + AWG_RUNTIME_OUTBOUNDS = flag awgRuntimeOutbounds; + AWG_RUNTIME_DIR = constants.runtimeAwgDir; + AWG_CONFIG_TOOL = "${proxySuiteScriptsDir}/amneziawg_config.py"; + AWG_TUNNEL_BASE_PORT = toString constants.awgRuntimeTunnelBasePort; + AWG_TUNNEL_SLOTS = toString constants.awgRuntimeTunnelSlots; WL_FILE = toString ( pkgs.writeText "proxy-suite-control" ( builtins.toJSON ( diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 3121d9b..e716670 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -175,24 +175,33 @@ lib.mkMerge [ # 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 - ] - ); + tmpfiles = lib.mkMerge [ + (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 + ] + )) + # Global AmneziaWG profiles added at runtime. Listable, so the tray and TUI show + # their names to everyone; each file is 0600 (amneziawg_config.py writes it so). + (lib.mkIf (cfg.enable && derived.awgRuntimeGlobal) [ + "d ${constants.runtimeAwgDir} ${ + if userControlAllows "amneziaWg" then "2775 root ${userControlCfg.group}" else "0755 root root" + } -" + ]) + ]; userServices = lib.mkMerge [ (mkNamedUnits userServiceEntries) diff --git a/modules/proxy-suite/service/polkit.nix b/modules/proxy-suite/service/polkit.nix index 5eb4e0f..5a542fe 100644 --- a/modules/proxy-suite/service/polkit.nix +++ b/modules/proxy-suite/service/polkit.nix @@ -11,6 +11,10 @@ let "proxy-suite-route-mode@" = "routing"; "proxy-suite-outbound-reload." = "outbounds"; "proxy-suite-subscription-update." = "outbounds"; + # Tunnels of the AmneziaWG outbounds added at runtime; a global profile's own unit + # (proxy-suite-awg@) is "services", like the declared ones. + "proxy-suite-awg-tunnel@" = "outbounds"; + "proxy-suite-awg-runtime-sync." = "outbounds"; "proxy-suite-autoproxy-learn." = "autoProxy"; "proxy-suite-zapret2-cutoff." = "zapret"; "proxy-suite-inbound-stats." = "stats"; diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index 098b23e..f3774d4 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -8,6 +8,7 @@ torCfg, whitelistBypassJoiners, awgOutbounds, + awgRuntimeOutbounds ? false, constants, pureXrayEnabled, hybridEnabled, @@ -136,6 +137,27 @@ let OUTBOUND_SOURCES_JSON=$(${jq} --arg t "$1" --arg s "$2" '.[$t] = $s' <<< "$OUTBOUND_SOURCES_JSON") } + # $1 tag, $2 loopback SOCKS port, $3 source label: mkTunnelOutboundBlock, for a port + # only known at runtime (an AmneziaWG outbound added with proxy-ctl). + _proxy_suite_add_socks_hop() { + local ob + ob=$(${jq} -nc --arg t "$1" --argjson p "$2" ${ + lib.escapeShellArg ( + if pureXrayEnabled then + ''{protocol: "socks", tag: $t, settings: {address: "127.0.0.1", port: $p}}'' + else + ''{type: "socks", tag: $t, server: "127.0.0.1", server_port: $p}'' + ) + }) || return 1 + ${ + if hybridEnabled then + ''_proxy_suite_add_sing_box_ob "$ob"'' + else + ''OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")'' + } + _proxy_suite_record_tag_source "$1" "$3" + } + # $1 sub tag, $2 file holding its URL, $3 its links file (absent for a cache # written before links existed: those entries share as JSON until the next update). _proxy_suite_record_subscription_share() { @@ -196,13 +218,14 @@ let _proxy_suite_record_tag_source "$tag" "$source" } - # Every runtime outbound, as "\t" lines: .url or .json. proxy-ctl refuses + # Every runtime outbound, as "\t" lines: .url, .json or .awg (an + # AmneziaWG config, behind a tunnel on the port in .port). proxy-ctl refuses # the reserved names, but the spool is group-writable, so check again here: # a second outbound tagged "proxy" would quietly shadow the real one. _proxy_suite_runtime_outbounds() { local f tag [ -d "${runtimeOutboundsDir}" ] || return 0 - for f in "${runtimeOutboundsDir}"/*.url "${runtimeOutboundsDir}"/*.json; do + for f in "${runtimeOutboundsDir}"/*.url "${runtimeOutboundsDir}"/*.json${lib.optionalString awgRuntimeOutbounds ''"${runtimeOutboundsDir}"/*.awg''}; do [ -e "$f" ] || continue tag="''${f##*/}" tag="''${tag%.*}" @@ -448,6 +471,8 @@ let [ -n "$RUNTIME_OB_TAG" ] || continue case "$RUNTIME_OB_SRC" in *.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;; + # Its tunnel (proxy-suite-awg-tunnel@) checks the port again before listening. + *.awg) _proxy_suite_add_socks_hop "$RUNTIME_OB_TAG" "$(head -n 1 "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.port" 2>/dev/null)" runtime ;; *) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime ;; esac || { echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2; continue; } if [ -s "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" ]; then diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 4398c04..c08be12 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -128,6 +128,7 @@ let torCfg whitelistBypassJoiners awgOutbounds + awgRuntimeOutbounds constants pureXrayEnabled hybridEnabled diff --git a/modules/proxy-suite/wg-tunnel.nix b/modules/proxy-suite/wg-tunnel.nix index 4c6ab06..a0c20e3 100644 --- a/modules/proxy-suite/wg-tunnel.nix +++ b/modules/proxy-suite/wg-tunnel.nix @@ -147,6 +147,9 @@ let # the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort, # `endpoint`, a host:port in place of the profile's Endpoint, and `domainStrategy`, the # address family it dials destinations over first. + # + # A template unit passes `tag` and `tunnelPort` as shell words ("$TUNNEL_TAG") that + # `profile` exports: the watchdog runs as a script of its own, after the exec. mkTunnel = { description, @@ -158,6 +161,11 @@ let endpoint ? null, domainStrategy ? null, engine ? "singBox", + runtimeDirectory ? unit, + wantedBy ? [ "multi-user.target" ], + restart ? "always", + # " %i" for a template, whose `profile` reads the instance name from $1. + execArgs ? "", }: let chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) { @@ -188,18 +196,17 @@ let ''; in { - inherit description; + inherit description wantedBy; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; - wantedBy = [ "multi-user.target" ]; # Probe-triggered restarts must not trip the start limit. startLimitIntervalSec = 0; serviceConfig = { Type = "simple"; - ExecStart = tunnelScript; - Restart = "always"; + ExecStart = if execArgs == "" then tunnelScript else "${tunnelScript}${execArgs}"; + Restart = restart; RestartSec = 2; - RuntimeDirectory = unit; + RuntimeDirectory = runtimeDirectory; RuntimeDirectoryMode = "0750"; UMask = "0077"; }; diff --git a/nix/checks/amnezia-wg-runtime.nix b/nix/checks/amnezia-wg-runtime.nix index 780f9a4..899d9f5 100644 --- a/nix/checks/amnezia-wg-runtime.nix +++ b/nix/checks/amnezia-wg-runtime.nix @@ -134,6 +134,42 @@ pkgs.testers.runNixOSTest { userspace.succeed("systemctl stop proxy-suite-awg-test.service") userspace.fail("ip link show awg-test") + with subtest("a profile added at runtime"): + # The same client as "test", as a .conf pasted in rather than declared. + userspace.succeed("""umask 077; cat > /root/rt.conf <<'EOF' + [Interface] + PrivateKey = ${keys.peer1.privateKey} + Address = 10.23.42.2/32 + Jc = ${toString obfuscation.jc} + Jmin = ${toString obfuscation.jmin} + Jmax = ${toString obfuscation.jmax} + S1 = ${toString obfuscation.s1} + S2 = ${toString obfuscation.s2} + + [Peer] + PublicKey = ${keys.peer0.publicKey} + Endpoint = 192.168.0.1:23542 + AllowedIPs = 10.23.42.1/32 + PersistentKeepalive = 5 + EOF""") + userspace.succeed("proxy-ctl awg add rt /root/rt.conf") + userspace.succeed("test $(stat -c %a /var/lib/proxy-suite/amneziawg.d/rt.conf) = 600") + userspace.succeed("proxy-ctl awg list | grep -E 'rt +inactive +runtime'") + userspace.succeed("proxy-ctl awg on rt") + userspace.succeed("ip link show awg-rt") + userspace.succeed("ping -c 5 10.23.42.1") + userspace.succeed("systemctl is-active proxy-suite-awg-watchdog@rt.service") + # A declared profile takes over: they share the peer, and only one global tunnel runs. + userspace.succeed("systemctl start proxy-suite-awg-test.service") + userspace.fail("systemctl is-active proxy-suite-awg@rt.service") + userspace.fail("ip link show awg-rt") + userspace.succeed("systemctl stop proxy-suite-awg-test.service") + # Hooks are refused whoever adds the config, and nothing is written. + userspace.fail("sed 's/^Address/PostUp = touch \\/pwned\\nAddress/' /root/rt.conf | proxy-ctl awg add hooked -") + userspace.fail("test -e /var/lib/proxy-suite/amneziawg.d/hooked.conf") + userspace.succeed("proxy-ctl awg rm rt") + userspace.fail("test -e /var/lib/proxy-suite/amneziawg.d/rt.conf") + with subtest("failed handshake rolls back userspace routing"): userspace.fail("systemctl start proxy-suite-awg-broken.service") userspace.fail("ip link show awg-broken") diff --git a/nix/checks/amnezia-wg.nix b/nix/checks/amnezia-wg.nix index 2ff36da..b6c1fa8 100644 --- a/nix/checks/amnezia-wg.nix +++ b/nix/checks/amnezia-wg.nix @@ -67,6 +67,15 @@ let } ]; homeService = awgOnly.config.systemd.services.proxy-suite-awg-home; + awgOnlyNoRuntime = mkProxySuite { + enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + runtime.enable = false; + profiles.home.configFile = "/run/secrets/awg.conf"; + }; + }; workService = awgOnly.config.systemd.services.proxy-suite-awg-work; ctl = mkProxyCtlDerived awgOnly; homeWatchdog = awgOnly.config.systemd.services.proxy-suite-awg-home-watchdog; @@ -146,10 +155,105 @@ let ]; withGlobalAwgService = withGlobalTun.config.systemd.services.proxy-suite-awg-home; withGlobalAwgStartPre = withGlobalAwgService.serviceConfig.ExecStartPre; - withGlobalAwgBypassUp = generated.readDerivation (builtins.elemAt withGlobalAwgStartPre 1); + withGlobalAwgBypassUp = generated.readDerivation (builtins.elemAt withGlobalAwgStartPre 2); + + # Nothing declared: every profile and AmneziaWG outbound comes from proxy-ctl. + runtimeOnly = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + killSwitch.enable = true; + userControl = { + enable = true; + scopes = [ "amneziaWg" ]; + }; + proxy = { + enable = true; + backend = "sing-box"; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + amneziaWg = { + enable = true; + kernelModulePackage = null; + }; + }; + } + ]; + runtimeUnits = runtimeOnly.config.systemd.services; + + # The scripts that list units, run against a systemctl that lists what the check says. + stubSystemctl = pkgs.writeShellScript "systemctl" '' + echo "$*" >> "$SYSTEMCTL_LOG" + if [ "$1" = list-units ]; then cat "$UNITS"; fi + ''; + stubbed = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + host.systemctl = pkgs.lib.mkForce "${stubSystemctl}"; + proxy = { + enable = true; + backend = "sing-box"; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles.home.configFile = "/run/secrets/awg.conf"; + }; + }; + } + ]; + stubbedUnits = stubbed.config.systemd.services; + runtimeTemplate = runtimeUnits."proxy-suite-awg@"; + runtimeTunnel = runtimeUnits."proxy-suite-awg-tunnel@"; + runtimeSync = generated.readDerivation runtimeUnits.proxy-suite-awg-runtime-sync.serviceConfig.ExecStart; + runtimeKillSwitchRules = checkLib.mkNftRules runtimeOnly "killSwitchRulesFile"; + runtimeCtl = mkProxyCtlDerived runtimeOnly; + runtimeOutboundScript = generated.readDerivation runtimeUnits.proxy-suite-socks.serviceConfig.ExecStart; withGlobalAwgBypassDown = generated.readDerivation withGlobalAwgService.serviceConfig.ExecStopPost; in { + # Nothing listed is no failure (grep finding nothing, under pipefail, once was); what is + # listed is stopped, a failed unit's glyph and all, but never the unit itself. + unitScripts = pkgs.runCommand "amneziawg-unit-scripts-check" { } '' + export SYSTEMCTL_LOG=$PWD/log UNITS=$PWD/units + stop=${builtins.elemAt stubbedUnits.proxy-suite-awg-home.serviceConfig.ExecStartPre 1} + sync=${stubbedUnits.proxy-suite-awg-runtime-sync.serviceConfig.ExecStart} + + : > units + $stop + $stop self + $sync + ! grep -q '^stop' log + + printf '%s\n' \ + '● proxy-suite-awg@gone.service loaded failed failed x' \ + ' proxy-suite-awg@self.service loaded active exited x' > units + : > log + $stop self + grep -qx 'stop proxy-suite-awg@gone.service' log + ! grep -q 'stop proxy-suite-awg@self.service' log + + printf '%s\n' '● proxy-suite-awg-tunnel@old.service loaded failed failed x' > units + : > log + $sync + grep -qx 'stop --no-block proxy-suite-awg-tunnel@old.service' log + touch "$out" + ''; + manifest = pkgs.runCommand "amneziawg-secret-manifest-check" { } '' ${pkgs.python3}/bin/python3 - <<'PY' import json @@ -185,7 +289,11 @@ in assert builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts; assert workService.wantedBy == [ ]; assert homeService.serviceConfig.NoNewPrivileges; - assert builtins.length homeService.serviceConfig.ExecStartPre == 1; + # Rendering, then stopping any profile added at runtime: they share an interface. + assert builtins.length homeService.serviceConfig.ExecStartPre == 2; + assert pkgs.lib.hasInfix "proxy-suite-awg@*.service" ( + generated.readDerivation (builtins.elemAt homeService.serviceConfig.ExecStartPre 1) + ); assert !(homeService.serviceConfig ? ExecStopPost); # A silent handshake moves the interface to a new port: at start, and from the watchdog. assert pkgs.lib.hasInfix "set \"$interface\" listen-port 0" homeStart; @@ -255,7 +363,7 @@ in withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts; assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.after; assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.wants; - assert builtins.length withGlobalAwgStartPre == 2; + assert builtins.length withGlobalAwgStartPre == 3; assert pkgs.lib.hasInfix "rule add" withGlobalAwgBypassUp; assert pkgs.lib.hasInfix "pref 8998" withGlobalAwgBypassUp; assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassUp; @@ -266,11 +374,71 @@ in assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassDown; true ) + # Profiles added with proxy-ctl: a template sharing one interface, which the kill switch + # knows; a tunnel template per outbound, started by a sync unit the reload pulls in. + ( + assert runtimeTemplate.wantedBy == [ ]; + assert builtins.elem "proxy-suite-awg-watchdog@%i.service" runtimeTemplate.wants; + assert builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.before; + assert builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.wants; + assert builtins.elem "proxy-suite-tun.service" runtimeTemplate.conflicts; + assert runtimeTemplate.serviceConfig.Group == "proxy-suite-awg"; + assert runtimeTemplate.serviceConfig.RuntimeDirectory == "proxy-suite-awg-rt-%i"; + assert pkgs.lib.hasSuffix " %i" runtimeTemplate.serviceConfig.ExecStart; + assert builtins.all (pkgs.lib.hasSuffix " %i") ( + pkgs.lib.take 2 runtimeTemplate.serviceConfig.ExecStartPre + ); + assert runtimeUnits."proxy-suite-awg-watchdog@".bindsTo == [ "proxy-suite-awg@%i.service" ]; + assert runtimeUnits."proxy-suite-awg-watchdog@".wantedBy == [ ]; + assert runtimeTunnel.wantedBy == [ ]; + assert runtimeTunnel.serviceConfig.Restart == "on-failure"; + assert runtimeTunnel.serviceConfig.RuntimeDirectory == "proxy-suite-awg-tunnel-%i"; + assert builtins.elem "proxy-suite-outbound-reload.service" + runtimeUnits.proxy-suite-awg-runtime-sync.wantedBy; + assert pkgs.lib.hasInfix "proxy-suite-awg-tunnel@$tag.service" runtimeSync; + # The backend dials each one's tunnel on the port in .port. + assert pkgs.lib.hasInfix ''"/var/lib/proxy-suite/outbounds.d"/*.awg'' runtimeOutboundScript; + assert pkgs.lib.hasInfix "_proxy_suite_add_socks_hop" runtimeOutboundScript; + assert pkgs.lib.hasInfix ''oifname { "awg-rt" } accept'' runtimeKillSwitchRules; + assert pkgs.lib.hasInfix ''meta skgid "proxy-suite-awg" accept'' runtimeKillSwitchRules; + assert builtins.elem "d /var/lib/proxy-suite/amneziawg.d 2775 root proxy-suite -" + runtimeOnly.config.systemd.tmpfiles.rules; + assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 0700 root root -" + runtimeOnly.config.systemd.tmpfiles.rules; + assert builtins.elem runtimeOnly.config.services.proxy-suite.amneziaWg.wireproxyPackage + runtimeOnly.config.environment.systemPackages; + assert pkgs.lib.hasInfix "proxy-suite-awg-tunnel@" runtimeOnly.config.security.polkit.extraConfig; + assert runtimeCtl.wrapperEnv.AWG_RUNTIME_GLOBAL == "1"; + assert runtimeCtl.wrapperEnv.AWG_RUNTIME_OUTBOUNDS == "1"; + assert runtimeCtl.wrapperEnv.AWG_RUNTIME_DIR == "/var/lib/proxy-suite/amneziawg.d"; + assert pkgs.lib.hasSuffix "/amneziawg_config.py" runtimeCtl.wrapperEnv.AWG_CONFIG_TOOL; + assert runtimeCtl.awgProfiles == [ ]; + # Declared profiles only in a configuration that turns the runtime ones off. + assert !(awgOnlyNoRuntime.config.systemd.services ? "proxy-suite-awg@"); + assert + builtins.length awgOnlyNoRuntime.config.systemd.services.proxy-suite-awg-home.serviceConfig.ExecStartPre + == 1; + true + ) ] ++ mkFailingAssertions mkBadProxySuiteFixture [ { enable = true; - amneziaWg.enable = true; + amneziaWg = { + enable = true; + runtime.enable = false; + }; + } + { + enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles.home = { + interfaceName = "awg-rt"; + configFile = "/run/home.conf"; + }; + }; } { enable = true; diff --git a/nix/checks/global-proxy-modes.nix b/nix/checks/global-proxy-modes.nix index 0b78453..72e03e6 100644 --- a/nix/checks/global-proxy-modes.nix +++ b/nix/checks/global-proxy-modes.nix @@ -151,8 +151,9 @@ in assert cfg.users.groups ? proxy-suite-awg; assert pkgs.lib.hasInfix "--fwmark 51820" awgKillSwitchPrepare; assert pkgs.lib.hasInfix ''meta skgid "proxy-suite-awg" accept'' rules; + # And the one the profiles added at runtime share. assert pkgs.lib.hasInfix - ''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}" } accept'' + ''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}", "awg-rt" } accept'' rules; assert pkgs.lib.hasInfix "meta mark { 1, 2, 51820 } accept" rules; assert !(pkgs.lib.hasInfix "skgid" killSwitchNftRules); diff --git a/nix/checks/hosts.nix b/nix/checks/hosts.nix index 561b7fd..4b2d694 100644 --- a/nix/checks/hosts.nix +++ b/nix/checks/hosts.nix @@ -165,6 +165,18 @@ let ]; smCfg = systemManager.config; + # AmneziaWG with nothing declared: outbounds added with proxy-ctl run as user units. + hmRuntimeAwg = evalHost "homeManager" [ + rootlessSettings + { + services.proxy-suite.amneziaWg = { + enable = true; + kernelModulePackage = null; + }; + } + ]; + hmRuntimeAwgUnits = hmRuntimeAwg.config.systemd.user.services; + nixOnDroid = evalHost "nixOnDroid" [ rootlessSettings ]; nodCfg = nixOnDroid.config; @@ -200,6 +212,17 @@ in )); true ) + ( + # Rootless: AmneziaWG outbounds added at runtime, never a global profile. + assert failedAssertions hmRuntimeAwg == [ ]; + assert hmRuntimeAwgUnits ? "proxy-suite-awg-tunnel@"; + assert hmRuntimeAwgUnits ? proxy-suite-awg-runtime-sync; + assert !(hmRuntimeAwgUnits ? "proxy-suite-awg@"); + assert + !(lib.hasInfix "setpriv" (toString hmRuntimeAwgUnits."proxy-suite-awg-tunnel@".Service.ExecStart)); + assert forced hmRuntimeAwgUnits; + true + ) ( # Rootless, the socks unit only listens: no TProxy inbound, no SO_MARK. assert lib.any (inbound: inbound.type == "mixed") hmSocksConfig.inbounds; @@ -244,6 +267,13 @@ in perAppRouting.zapret.enable = true; } "perAppRouting.zapret needs root"; assert rejects "nixOnDroid" { gui.enable = true; } "the GUI needs a desktop session"; + # No templates in proxy-suitectl, and no root for a global profile: nothing to add to. + assert rejects "nixOnDroid" { + amneziaWg = { + enable = true; + kernelModulePackage = null; + }; + } "amneziaWg.enable needs a profile"; assert rejects "nixOnDroid" { inbounds.listeners.vless.port = lib.mkForce 443; } "inbounds.listeners.vless.port = 443 is a privileged port"; diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 31848f8..10757f2 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -332,6 +332,7 @@ in { proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok"); amneziawg-secret-manifest = amneziaWgChecks.manifest; + amneziawg-unit-scripts = amneziaWgChecks.unitScripts; xray-jq-filter-runtime = xrayBackendChecks.runtime; tor-guard-runtime = torChecks.runtime; per-app-zapret-runtime = perAppRoutingChecks.runtime; diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index 6e06753..ad76f5a 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -122,6 +122,19 @@ let }; ipNamedConfig = mkInboundsConfig ipNamedFixture; + # Other names and IPs of this host, beside the one in share links. + aliasedFixture = mkInbounds { + serverAddress = "vpn.example.com"; + serverAliases = [ + "turn.example.com" + "203.0.113.10" + "2001:db8::10" + "vpn.example.com" + ]; + listeners.vless-in = realityListener; + }; + aliasedConfig = mkInboundsConfig aliasedFixture; + unguardedFixture = mkInbounds { routing = { blockRu = false; @@ -812,7 +825,28 @@ let (ok ((ruleByTag blockedConfig "inbound-server-address-direct").inboundTag == [ "open" ])) # No address to exempt when it is detected at runtime instead. (ok (!builtins.elem "inbound-server-address-direct" (ruleTags relayConfig))) - (ok ((ruleByTag ipNamedConfig "inbound-server-address-direct").ip == [ "82.146.44.102" ])) + (ok ((ruleByTag ipNamedConfig "inbound-server-address-direct-ip").ip == [ "82.146.44.102" ])) + (ok (!builtins.elem "inbound-server-address-direct" (ruleTags ipNamedConfig))) + (ok (!builtins.elem "inbound-server-address-direct-ip" (ruleTags namedConfig))) + # Aliases join serverAddress, names and IPs apart, as XRay ANDs one rule's fields. + ( + assert + (ruleByTag aliasedConfig "inbound-server-address-direct").domain == [ + "full:vpn.example.com" + "full:turn.example.com" + ]; + true + ) + ( + assert + (ruleByTag aliasedConfig "inbound-server-address-direct-ip").ip == [ + "203.0.113.10" + "2001:db8::10" + ]; + true + ) + (ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").port == "443")) + (ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").outboundTag == "direct")) (ok (!builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig))) # A per-listener via becomes its own rule; listeners on the default do not. diff --git a/nix/checks/python-tests.nix b/nix/checks/python-tests.nix index d6cd5b7..8382124 100644 --- a/nix/checks/python-tests.nix +++ b/nix/checks/python-tests.nix @@ -73,7 +73,10 @@ pkgs.lib.mapAttrs mkPythonCheck { proxy-ctl-unit = { drv = "proxy-suite-proxy-ctl-unit"; file = "${proxyCtl}/test_proxy_ctl.py"; - env = singBox; + # `awg add` and AmneziaWG outbounds hand their configs to it. + env = singBox // { + AWG_CONFIG_TOOL = "${scripts}/amneziawg_config.py"; + }; }; # proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped. proxy-suite-supervisor-unit = { diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index 5f9bd15..b065700 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -503,6 +503,8 @@ in has exclude zapret auto has proxy-suite-awg-work logs has work awg on + has add awg + has rm awg has torrent apps run has unpin proxy has newnym tor diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index d98169a..13a800e 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -65,6 +65,8 @@ Changes and secrets need root or the userControl group. proxy outbounds add [tag] [--detour ] add an outbound from a link or JSON (-: stdin); --detour: connect through another outbound + proxy outbounds add [tag] [--container ] + add an AmneziaWG outbound (runs in wireproxy) proxy outbounds chain [new tag] add a copy of an outbound that connects through another proxy outbounds rm remove a runtime outbound @@ -105,6 +107,9 @@ Changes and secrets need root or the userControl group. awg [list] AmneziaWG profiles awg on | off [profile] | toggle [profile] | restart [profile] + awg add [name] [--container ] + add a global profile (-: stdin) + awg rm remove a profile added with awg add killswitch [status|on|off] block traffic outside the global tunnel; stays on until turned off here or with the tunnel @@ -442,9 +447,35 @@ def _sub_tags(): def _awg_profiles(): + """Global AmneziaWG profiles: the declared ones, then those added with `awg add`.""" + declared = _awg_declared() + return declared + [p for p in _awg_runtime_profiles() if p not in declared] + + +def _awg_declared(): return _json_list(env("AWG_PROFILES_FILE")) +def _awg_added(profile): + """Whether a profile was added with `awg add` (a declared one of that name wins).""" + return profile in _awg_runtime_profiles() and profile not in _awg_declared() + + +def _awg_runtime_dir(): + return env("AWG_RUNTIME_DIR", f"{state_dir()}/amneziawg.d") + + +def _awg_runtime_profiles(): + """Profiles added with `awg add`: .conf in a listable dir, each file root-only.""" + if env("AWG_RUNTIME_GLOBAL") != "1": + return [] + try: + names = os.listdir(_awg_runtime_dir()) + except OSError: + return [] + return sorted(n.removesuffix(".conf") for n in names if n.endswith(".conf") and AWG_NAME.fullmatch(n.removesuffix(".conf"))) + + # --- completion --------------------------------------------------------------- # # Candidates for the words already typed, one per line as worddescription. @@ -612,8 +643,12 @@ COMPLETE = { "off": "stop a profile", "toggle": "start a profile if stopped, stop it if running", "restart": "restart a profile", + "add": "add a profile from a .conf or vpn:// link", + "rm": "remove a profile added with awg add", } }, + "awg add": {"flags": {"--container": "which container of a vpn:// export"}}, + "awg rm": {"args": lambda: _names(_awg_runtime_profiles())}, "awg on": {"args": lambda: _names(_awg_profiles())}, "awg off": {"args": lambda: _names(_awg_profiles())}, "awg toggle": {"args": lambda: _names(_awg_profiles())}, @@ -770,7 +805,8 @@ def _status_snapshot(states=None): name: {"available": unit in states, "active": states.get(unit) == "active"} for name, unit in SNAPSHOT_UNITS.items() } snapshot["awg"] = { - "available": bool(profiles), + # With runtime profiles on, `awg add` can add the first one. + "available": bool(profiles) or env("AWG_RUNTIME_GLOBAL") == "1", "profiles": profiles, "active": next((p for p in profiles if states.get(_awg_service(p)) == "active"), ""), } @@ -1006,7 +1042,14 @@ def cmd_outbounds(verb="list", *args): del args[i : i + 2] if not detour: usage("proxy outbounds add [tag] [--detour ]") - _runtime_entry_add("outbound", *args, detour=detour) + container = "" + if "--container" in args: + i = args.index("--container") + container = args[i + 1] if i + 1 < len(args) else "" + del args[i : i + 2] + if not container: + usage("proxy outbounds add [tag] [--container ]") + _runtime_entry_add("outbound", *args, detour=detour, container=container) elif verb == "chain": cmd_outbound_chain(*args) elif verb in ("rm", "remove", "del"): @@ -1409,13 +1452,13 @@ def _runtime_tags(kind): names = os.listdir(_runtime_dir(kind)) except OSError: return [] - exts = (".url", ".json") if kind == "outbound" else (".url",) + exts = (".url", ".json", ".awg") if kind == "outbound" else (".url",) return sorted(os.path.splitext(n)[0] for n in names if n.endswith(exts)) def _runtime_path(kind, tag): """The file behind a runtime entry, or its .url spelling when there is none.""" - for ext in (".url", ".json") if kind == "outbound" else (".url",): + for ext in (".url", ".json", ".awg") if kind == "outbound" else (".url",): path = os.path.join(_runtime_dir(kind), tag + ext) if os.path.exists(path): return path @@ -1453,6 +1496,8 @@ RUNTIME_TAG_MAX = 32 def _runtime_source(kind, arg): """Whether an add argument is the entry itself rather than its tag.""" + if kind == "outbound" and (_awg_source(arg) or _awg_file(arg)): + return True return "://" in arg or (kind == "outbound" and (arg == "-" or arg.lstrip().startswith("{"))) @@ -1516,7 +1561,7 @@ def _unique_runtime_tag(kind, name, fallback): return tag -def _runtime_entry_add(kind, *args, detour=""): +def _runtime_entry_add(kind, *args, detour="", container=""): what = " [--detour ]" if kind == "outbound" else "" shape = f"proxy {_runtime_noun(kind)} add [tag] {what}" if len(args) == 1 and _runtime_source(kind, args[0]): @@ -1534,6 +1579,13 @@ def _runtime_entry_add(kind, *args, detour=""): die(f"Cannot chain through '{detour}': not an outbound. See: proxy-ctl proxy outbounds") if kind == "outbound" and url == "-": url = sys.stdin.read() + if kind == "outbound" and _awg_file(url): + url = _awg_input(url) + if kind == "outbound" and _awg_source(url): + _awg_outbound_add(tag, url, detour, container) + return + if container: + die("--container only applies to an AmneziaWG vpn:// link.") if not tag: tag = _runtime_tag_for(kind, url) _check_runtime_tag(kind, tag) @@ -1583,6 +1635,8 @@ def cmd_outbound_chain(tag="", hop="", new_tag="", *_): die(f"'{tag}' cannot chain through itself; name another outbound as the hop.") entry = _outbound_share_entry(tag) source = _s(entry.get("url") or "") + if not source and _awg_tunnel_hop(entry.get("outbound") or {}): + die(f"'{tag}' is an AmneziaWG outbound: its tunnel dials the peer itself and cannot go through another outbound.") if not source: ob = entry.get("outbound") or {} if not ob: @@ -1610,7 +1664,7 @@ def _runtime_entry_rm(kind, tag="", *_): try: os.unlink(path) # Its hop, and a disable left from it: a new entry of this name would inherit them. - for extra in (".detour", ".disabled") if kind == "outbound" else (): + for extra in (".detour", ".disabled", ".port") if kind == "outbound" else (): if os.path.exists(os.path.join(_runtime_dir(kind), tag + extra)): os.unlink(os.path.join(_runtime_dir(kind), tag + extra)) except FileNotFoundError: @@ -2832,15 +2886,227 @@ def cmd_where(domain="", *_): # --- awg ---------------------------------------------------------------------- +AWG_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,31}") + + def _awg_service(profile): + # Added with `awg add`: an instance of the template, which reads amneziawg.d/.conf. + if profile and _awg_added(profile): + return f"proxy-suite-awg@{profile}" return f"proxy-suite-awg-{profile}" +# --- AmneziaWG configs added at runtime ----------------------------------------- +# +# A .conf or vpn:// link becomes a global profile (`awg add`, amneziawg.d/.conf) or an +# outbound (`proxy outbounds add`, outbounds.d/.awg with its tunnel's port in .port). +# amneziawg_config.py --import checks and normalizes it, hooks refused. The config always +# reaches it on stdin: keys in argv would show in ps. + + +def _awg_source(text): + """Whether text is an AmneziaWG config itself: a vpn:// link, or .conf text.""" + t = (text or "").strip() + return t.startswith("vpn://") or ("[interface]" in t.lower() and "[peer]" in t.lower()) + + +def _awg_file(arg): + """Whether an add argument names a .conf or vpn:// export on disk.""" + return bool(arg) and arg.endswith((".conf", ".vpn")) and os.path.isfile(os.path.expanduser(arg)) + + +def _awg_input(arg): + """The config an add argument stands for: stdin (-), the text itself, or a file's.""" + if arg == "-": + return sys.stdin.read() + if _awg_source(arg): + return arg + path = os.path.expanduser(arg) + try: + return read_text(path) + except OSError as e: + die(f"Cannot read {path}: {e.strerror or e}") + + +def _awg_import(text, *args): + """amneziawg_config.py --import on text: its output, or its complaint as ours.""" + tool = env("AWG_CONFIG_TOOL") + if not tool: + die("AmneziaWG is not enabled in this configuration.") + try: + p = subprocess.run([sys.executable, tool, "--import", "-", *args], input=text, capture_output=True, text=True) + except OSError as e: + die(f"Cannot run {tool}: {e}") + if p.returncode: + message = p.stderr.strip().removeprefix("amneziawg-config: ") or f"{tool} exited with {p.returncode}" + die(message.replace("set vpnContainer", "pick one with --container ")) + return p.stdout + + +def _awg_describe(text, container=""): + """What the config says of itself: {"name", "endpoint"}. Dies when it is not one.""" + out = _awg_import(text, "--describe", *(["--container", container] if container else [])) + try: + described = json.loads(out) + except ValueError: + described = {} + return described if isinstance(described, dict) else {} + + +def _awg_label(described, fallback): + """A name for an entry added without one: the export's description, else awg-.""" + name = _s(described.get("name") or "") + host = _s(described.get("endpoint") or "").rsplit(":", 1)[0].strip("[]") + if name and name == host: + return f"awg-{_host_label(host)}" + return name or fallback + + +def _awg_write(text, path, container=""): + """The normalized config at path, 0600; the directory must let us in.""" + directory = os.path.dirname(path) + if not os.access(directory, os.W_OK | os.X_OK): + denied(directory, "write to") + _awg_import(text, "--output", path, *(["--container", container] if container else [])) + + +def _awg_tunnel_ports(): + return range(int(env("AWG_TUNNEL_BASE_PORT", "18800")), int(env("AWG_TUNNEL_BASE_PORT", "18800")) + int(env("AWG_TUNNEL_SLOTS", "32"))) + + +def _awg_tunnel_hop(ob): + """Whether a backend outbound is the SOCKS hop to a runtime AmneziaWG tunnel.""" + port = ob.get("server_port") or (ob.get("settings") or {}).get("port") + server = ob.get("server") or (ob.get("settings") or {}).get("address") + return server == "127.0.0.1" and isinstance(port, int) and port in _awg_tunnel_ports() + + +def _awg_free_port(): + taken = set() + directory = _runtime_dir("outbound") + try: + names = os.listdir(directory) + except OSError: + names = [] + for name in names: + if name.endswith(".port"): + try: + taken.add(int(read_text(os.path.join(directory, name)).split()[0])) + except (OSError, ValueError, IndexError): + pass + port = next((p for p in _awg_tunnel_ports() if p not in taken), None) + if port is None: + die(f"No free port for another AmneziaWG outbound: all {len(_awg_tunnel_ports())} are taken. Remove one first.") + return port + + +def _awg_outbound_add(tag, text, detour, container): + require_enabled("AWG_RUNTIME_OUTBOUNDS", "Adding AmneziaWG outbounds at runtime") + if detour: + die("An AmneziaWG outbound cannot chain through another: its tunnel dials the peer itself.") + described = _awg_describe(text, container) + if not tag: + tag = _unique_runtime_tag("outbound", _awg_label(described, "awg"), "awg") + _check_runtime_tag("outbound", tag) + print(f"Tag: {tag} (none given; pass one first to choose it)") + directory = _runtime_dir("outbound") + if not os.access(directory, os.W_OK | os.X_OK): + denied(directory, "write to") + port = _awg_free_port() + old = os.umask(0o027) + try: + # The port first: the config is what the start script and the sync unit look for. + for extra in (".detour", ".disabled"): + if os.path.exists(os.path.join(directory, tag + extra)): + os.unlink(os.path.join(directory, tag + extra)) # left from an earlier entry of this name + with open(os.path.join(directory, f"{tag}.port"), "w", encoding="utf-8") as f: + f.write(f"{port}\n") + except OSError: + denied(directory, "write to") + finally: + os.umask(old) + _awg_write(text, os.path.join(directory, f"{tag}.awg"), container) + _runtime_reload() + _runtime_entry_verify("outbound", tag) + + +def _awg_add(*args): + shape = "awg add [name] [--container ]" + args = list(args) + container = "" + if "--container" in args: + i = args.index("--container") + container = args[i + 1] if i + 1 < len(args) else "" + del args[i : i + 2] + if not container: + usage(shape) + require_enabled("AWG_RUNTIME_GLOBAL", "Adding AmneziaWG profiles at runtime") + if len(args) == 1: + name, source = "", args[0] + elif len(args) == 2 and (_awg_source(args[0]) or args[0] == "-"): + die(f"The name goes first, the config after it: proxy-ctl {shape}") + elif len(args) == 2: + name, source = args + else: + usage(shape) + # "warp" names WARP's own AmneziaWG unit (_warp_unit). + taken = {*_awg_profiles(), "warp"} + if name == "warp": + die("'warp' is reserved for WARP; pick another name.") + if name: + if not AWG_NAME.fullmatch(name): + die(f"Invalid profile name '{name}': up to 32 letters, digits, dashes and underscores, starting with a letter or digit.") + if name in taken: + die(f"An AmneziaWG profile named '{name}' already exists." + ("" if name in _awg_runtime_profiles() else " It is declared in the NixOS configuration.")) + text = _awg_input(source) + described = _awg_describe(text, container) + if not name: + base = re.sub(r"[^A-Za-z0-9_-]+", "-", _awg_label(described, "awg")).strip("-_")[:32].strip("-_") or "awg" + name, n = base, 1 + while name in taken: + n += 1 + name = f"{base[: 32 - len(str(n)) - 1]}-{n}" + print(f"Name: {name} (none given; pass one first to choose it)") + _awg_write(text, os.path.join(_awg_runtime_dir(), f"{name}.conf"), container) + print(f"Added AmneziaWG profile: {name} - start it with: proxy-ctl awg on {name}") + + +def _awg_rm(name="", *_): + if not name: + usage("awg rm ") + if name not in _awg_runtime_profiles(): + if name in _awg_profiles(): + die(f"'{name}' is declared in the NixOS configuration; remove it there.") + die(f"No AmneziaWG profile named '{name}' was added with awg add.") + directory = _awg_runtime_dir() + if not os.access(directory, os.W_OK | os.X_OK): + denied(directory, "write to") + unit = _awg_service(name) + if svc_active(unit) or svc_state(unit) == "failed": + must("stop", unit) + # As `awg off`: the kill switch would otherwise hold with no tunnel to guard. + if svc_exists(KILL_SWITCH): + systemctl("stop", KILL_SWITCH) + try: + os.unlink(os.path.join(directory, f"{name}.conf")) + except FileNotFoundError: + pass + except OSError: + denied(os.path.join(directory, f"{name}.conf"), "remove") + print(f"Removed AmneziaWG profile: {name}") + + def _active_awg_profiles(): return [p for p in _awg_profiles() if svc_active(_awg_service(p))] def cmd_awg(verb="list", *args): + if verb == "add": + _awg_add(*args) + return + if verb in ("rm", "remove", "del"): + _awg_rm(*args) + return profiles = _awg_profiles() if args and args[0] not in profiles: die(f"Unknown AmneziaWG profile: {args[0]}") @@ -2854,11 +3120,11 @@ def cmd_awg(verb="list", *args): usage("awg toggle ") if verb in ("list", "status"): if not profiles: - print("No AmneziaWG profiles configured.") + print("No AmneziaWG profiles configured." + (" Add one with: proxy-ctl awg add " if env("AWG_RUNTIME_GLOBAL") == "1" else "")) return - print(f" {'PROFILE':<24} STATUS") + print(f" {'PROFILE':<24} {'STATUS':<12} SOURCE") for profile in profiles: - print(f" {profile:<24} {svc_state(_awg_service(profile)) or 'unknown'}") + print(f" {profile:<24} {svc_state(_awg_service(profile)) or 'unknown':<12} {'runtime' if _awg_added(profile) else 'declared'}") elif verb == "on": if not args: usage("awg on ") @@ -2873,7 +3139,7 @@ def cmd_awg(verb="list", *args): if verb == "off" and svc_exists(KILL_SWITCH): systemctl("stop", KILL_SWITCH) else: - usage("awg [list] | on | off [profile] | toggle [profile] | restart [profile]") + usage("awg [list] | on | off [profile] | toggle [profile] | restart [profile] | add [name] | rm ") # --- wl ----------------------------------------------------------------------- diff --git a/pkgs/proxy-ctl/proxy_gui.py b/pkgs/proxy-ctl/proxy_gui.py index 60976d8..23180c3 100644 --- a/pkgs/proxy-ctl/proxy_gui.py +++ b/pkgs/proxy-ctl/proxy_gui.py @@ -953,11 +953,11 @@ class Window(Adw.ApplicationWindow): except GLib.Error as e: self.toast(f"Cannot read the clipboard: {e.message}") return - argv, what = model.paste_argv(page.tab.id, text) + argv, what, stdin = model.paste_argv(page.tab.id, text) if argv is None: self.toast(what) else: - self.app.run_argv("run", argv, self) + self.app.run_argv("run", argv, self, stdin=stdin) def follow_logs(self): self.app.run_argv("suspend", ["logs"], self) @@ -977,13 +977,14 @@ class Window(Adw.ApplicationWindow): def with_text(text=""): try: argv = action.argv(row, text, self.app.states) + stdin = action.stdin(row, text) if action.stdin else None except (ValueError, IndexError) as e: self.toast(f"Cannot run that: {e}") return if model.needs_confirm(action, row): - self.app.confirm(argv, lambda: self.app.run_argv(action.mode, argv, self), self) + self.app.confirm(argv, lambda: self.app.run_argv(action.mode, argv, self, stdin=stdin), self) else: - self.app.run_argv(action.mode, argv, self) + self.app.run_argv(action.mode, argv, self, stdin=stdin) if not action.prompt: with_text() @@ -1280,9 +1281,10 @@ class ProxySuiteGui(Adw.Application): dialog.connect("response", lambda _, r: r == "run" and then()) dialog.present(parent) - def run_argv(self, mode, argv, win, root=False): + def run_argv(self, mode, argv, win, root=False, stdin=None): """run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard. - root, or the elevated toggle: through pkexec. Never `apps run`, which is per user.""" + root, or the elevated toggle: through pkexec. Never `apps run`, which is per user. + stdin: text proxy-ctl reads (argv says "-"), kept out of argv and pkexec's log.""" root = (root or self.elevated()) and argv[:1] != ["apps"] command = f"{'pkexec ' if root else ''}proxy-ctl {shlex.join(argv)}" retry_argv = argv @@ -1295,12 +1297,12 @@ class ProxySuiteGui(Adw.Application): dialog.present(win) elif win is not None: win.toast(f"… {command}") - threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr, root, retry_argv), daemon=True).start() + threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr, root, retry_argv, stdin), daemon=True).start() - def stream(self, command, argv, mode, win, dialog, qr, root, retry_argv): + def stream(self, command, argv, mode, win, dialog, qr, root, retry_argv, stdin=None): out = [] try: - p = model.popen(argv, "pkexec" if root else None) + p = model.popen(argv, "pkexec" if root else None, stdin=stdin) if dialog: GLib.idle_add(lambda: dialog.running(p, stoppable=not root) and False) for line in p.stdout: @@ -1313,13 +1315,13 @@ class ProxySuiteGui(Adw.Application): status = 127 if root and status == 126 and not out: out.append("authentication cancelled") # pkexec: the password dialog was dismissed - GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv) and False) + GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv, stdin) and False) - def ran(self, command, mode, win, dialog, qr, out, status, retry_argv): + def ran(self, command, mode, win, dialog, qr, out, status, retry_argv, stdin=None): last = last_line(out) text = "\n".join(out) output = (command, text) - retry = (lambda: self.run_argv(mode, retry_argv, win, root=True)) if model.needs_root(out, status) else None + retry = (lambda: self.run_argv(mode, retry_argv, win, root=True, stdin=stdin)) if model.needs_root(out, status) else None if win is not None: win.last_output = output win.last_retry = retry diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index 0c3362b..01c05b1 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -66,6 +66,7 @@ class Action: mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal; pause: suspend, then wait for enter; copy: last line to the clipboard offered: Callable = None # () -> this configuration has it; None: every one does tty: bool = False # it asks on the terminal: only a front end that hands the terminal over offers it + stdin: Callable = None # (selected row or None, prompt text) -> text proxy-ctl reads on stdin, or None @dataclass @@ -150,6 +151,7 @@ TOGGLES = { "proxy-suite-zapret": ["zapret"], } AWG_PREFIX = ctl._awg_service("") +AWG_RUNTIME_PREFIX = "proxy-suite-awg@" ZAPRET_LISTS = ( ("learned", "zapret-hosts-auto.txt"), ("pinned", "zapret-hosts-user.txt"), @@ -183,8 +185,11 @@ def _wl_argv(verb, *extra): def _awg_profile(row): """The global AmneziaWG profile behind a row, or empty.""" - name = row["unit"].removeprefix(AWG_PREFIX) - return name if row["unit"].startswith(AWG_PREFIX) and name in ctl._awg_profiles() else "" + unit = row["unit"] + for prefix in (AWG_RUNTIME_PREFIX, AWG_PREFIX): + if unit.startswith(prefix) and (name := unit.removeprefix(prefix)) in ctl._awg_profiles(): + return name + return "" def _unit_argv(row, verb): @@ -264,6 +269,44 @@ def outbound_summary(): ) +def awg_rows(states): + return [ + { + "key": p, + "profile": p, + "unit": ctl._awg_service(p), + "state": states.get(ctl._awg_service(p)) or "inactive", + "source": "runtime" if ctl._awg_added(p) else "declared", + } + for p in ctl._awg_profiles() + ] + + +def _awg_available(_): + return bool(ctl._awg_profiles()) or ctl.env("AWG_RUNTIME_GLOBAL") == "1" + + +def _awg_add(text): + """[name] as typed: (name or None, the config or a path to it).""" + text = text.strip() + if ctl._awg_source(text): + return None, text + parts = text.split(None, 1) + return (parts[0], parts[1].strip()) if len(parts) == 2 else (None, text) + + +def _awg_add_argv(text): + name, source = _awg_add(text) + # The config itself goes on stdin: in argv its keys would show in ps, sudo's log and here. + what = "-" if ctl._awg_source(source) else _path(source) + return ["awg", "add", *([name] if name else []), what] + + +def _awg_add_stdin(text): + _, source = _awg_add(text) + return source if ctl._awg_source(source) else None + + def subscription_rows(_): rows = [] for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))): @@ -441,9 +484,19 @@ def _sub_url(row): def _add_args(text): - """[tag] , or JSON with spaces in it, as `proxy-ctl ... add` takes them.""" + """[tag] , or JSON with spaces in it, as `proxy-ctl ... add` takes them. + An AmneziaWG config becomes "-": _add_stdin hands it over on stdin.""" text = text.strip() - return [text] if text.startswith("{") else text.split(None, 1) + if text.startswith("{"): + return [text] + name, source = _awg_add(text) + if ctl._awg_source(source): + return [*([name] if name else []), "-"] + return text.split(None, 1) + + +def _add_stdin(text): + return _awg_add_stdin(text) def _zapret_auto(): @@ -519,6 +572,28 @@ TABS = [ ), ], ), + Tab( + "awg", + "AmneziaWG", + _awg_available, + [("profile", "Profile"), ("state", "State"), ("source", "Source")], + awg_rows, + summary=lambda: "Only one global tunnel runs at a time: starting a profile stops TUN, TProxy and any other profile.", + actions=[ + Action("space", "start / stop", lambda r, *_: ["awg", "off" if r["state"] == "active" else "on", r["profile"]], when=ROW), + Action("ctrl+r", "restart it", lambda r, *_: ["awg", "restart", r["profile"]], when=lambda r: r["state"] in ("active", "failed")), + Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"), + Action( + "n", + "add a profile (name optional)…", + lambda r, t, _: _awg_add_argv(t), + prompt="[name] - e.g. home vpn://… (or paste a whole .conf onto the table)", + stdin=lambda r, t: _awg_add_stdin(t), + offered=lambda: ctl.env("AWG_RUNTIME_GLOBAL") == "1", + ), + Action("d", "remove it", lambda r, *_: ["awg", "rm", r["profile"]], when=lambda r: r["source"] == "runtime", confirm=True), + ], + ), Tab( "routing", "Routing", @@ -557,7 +632,8 @@ TABS = [ "n", "add a runtime outbound (tag optional)…", lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t)], - prompt="[tag] - e.g. de-1 vless://… or just vless://…", + prompt="[tag] - e.g. de-1 vless://… or just vless://…", + stdin=lambda r, t: _add_stdin(t), ), Action( "h", @@ -704,28 +780,42 @@ OUTBOUND_ADD = ["proxy", "outbounds", "add"] def paste_argv(tab_id, text): - """What pasting the clipboard onto a tab runs: (argv, ""), or (None, why it runs nothing). + """What pasting the clipboard onto a tab runs: (argv, "", stdin), or (None, why it runs nothing, None). Dumb on purpose: a share link becomes an outbound, a subscription URL a subscription, - a bare host a pinned or learned one. The tag comes from the link, as `add` derives it. + a bare host a pinned or learned one, an AmneziaWG vpn:// link or .conf a global profile + (an outbound on the outbounds tab). The tag comes from the link, as `add` derives it. """ text = (text or "").strip() if not text: - return None, "Nothing to paste." + return None, "Nothing to paste.", None + if ctl._awg_source(text): + return _awg_paste(tab_id, text) if text.startswith("{"): - return [*OUTBOUND_ADD, text], "" # only outbounds take JSON + return [*OUTBOUND_ADD, text], "", None # only outbounds take JSON if len(text.splitlines()) > 1: - return None, "Paste one link at a time." + return None, "Paste one link at a time.", None scheme = text.split("://", 1)[0].lower() if "://" in text else "" if scheme in PROXY_SCHEMES: - return [*OUTBOUND_ADD, text], "" + return [*OUTBOUND_ADD, text], "", None if scheme in ("http", "https"): - return ([*OUTBOUND_ADD, text] if tab_id == "outbounds" else ["proxy", "subs", "add", text]), "" + return ([*OUTBOUND_ADD, text] if tab_id == "outbounds" else ["proxy", "subs", "add", text]), "", None if scheme: - return None, f"Nothing takes a {scheme}:// link." + return None, f"Nothing takes a {scheme}:// link.", None if HOST.fullmatch(text) and tab_id in HOST_ARGV: - return [*HOST_ARGV[tab_id], text], "" - return None, "Not a share link, a subscription URL or a host." + return [*HOST_ARGV[tab_id], text], "", None + return None, "Not a share link, a subscription URL or a host.", None + + +def _awg_paste(tab_id, text): + """An AmneziaWG config, on stdin: an outbound where outbounds are, else a global profile.""" + outbound = ctl.env("AWG_RUNTIME_OUTBOUNDS") == "1" + global_ = ctl.env("AWG_RUNTIME_GLOBAL") == "1" + if outbound and (tab_id == "outbounds" or not global_): + return [*OUTBOUND_ADD, "-"], "", text + if global_: + return ["awg", "add", "-"], "", text + return None, "AmneziaWG configs cannot be added here: amneziaWg.runtime is off in this configuration.", None def available_tabs(states): @@ -795,13 +885,28 @@ def load_tab_as_root(tab, via): return None, (p.stderr.strip().splitlines() or [f"exit status {p.returncode}"])[-1] -def popen(argv, root=None): +def popen(argv, root=None, stdin=None): """proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too. - root: "pkexec" to run it as root, asking through the desktop's polkit agent.""" - return subprocess.Popen( - elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, + root: "pkexec" to run it as root, asking through the desktop's polkit agent. + stdin: text for it to read (argv then says "-"), kept out of argv, ps and sudo's log.""" + p = subprocess.Popen( + elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL if stdin is None else subprocess.PIPE, text=True, errors="replace", start_new_session=True, ) + feed(p, stdin) + return p + + +def feed(p, stdin): + """Hands a started process its stdin text, and closes it.""" + if stdin is None: + return + try: + p.stdin.write(stdin) + p.stdin.close() + except (BrokenPipeError, OSError): + pass # it exited first: its output says why def stop(proc): @@ -889,7 +994,8 @@ def tray_menu(snap, outbounds=None): if snap[name]["available"]: active = snap[name]["active"] traffic.append(MenuItem(name, label, kind="check", checked=active, argv=["proxy", name, "off" if active else "on"])) - if snap["awg"]["available"]: + # Available with none added yet: nothing to pick until `awg add`. + if snap["awg"]["available"] and snap["awg"]["profiles"]: current = snap["awg"]["active"] traffic.append( MenuItem( diff --git a/pkgs/proxy-ctl/proxy_tui.py b/pkgs/proxy-ctl/proxy_tui.py index 82904a3..1787b34 100644 --- a/pkgs/proxy-ctl/proxy_tui.py +++ b/pkgs/proxy-ctl/proxy_tui.py @@ -433,7 +433,7 @@ class ProxyTui(App): self.typed = {} # prompt title -> what was last typed there self.feedback_timer = None self.last_output = None # (title, text) - self.retry = None # (mode, argv) of the last run that only root could do + self.retry = None # (mode, argv, stdin) of the last run that only root could do self.animation_level = "none" # tab switches land at once self.register_theme(THEME) self.theme = THEME.name @@ -641,11 +641,11 @@ class ProxyTui(App): if self.screen is not self.main: return event.stop() - argv, what = model.paste_argv(self.active_tab(), event.text) + argv, what, stdin = model.paste_argv(self.active_tab(), event.text) if argv is None: self.feedback(what, False) else: - self.run_argv("run", argv) + self.run_argv("run", argv, stdin) def action_where(self): self.perform(model.WHERE, None) @@ -705,13 +705,14 @@ class ProxyTui(App): def with_text(text=""): try: argv = action.argv(row, text, self.states) + stdin = action.stdin(row, text) if action.stdin else None except (ValueError, IndexError) as e: # an unbalanced quote in a typed command self.feedback(f"Cannot run that: {e}", False) return if model.needs_confirm(action, row): - self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv)) + self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv, stdin)) else: - self.run_argv(action.mode, argv) + self.run_argv(action.mode, argv, stdin) def typed(text): if text: @@ -724,7 +725,8 @@ class ProxyTui(App): else: with_text() - def run_argv(self, mode, argv): + def run_argv(self, mode, argv, stdin=None): + """stdin: text proxy-ctl reads (argv says "-"); only for runs that stay in the TUI.""" command = f"proxy-ctl {shlex.join(argv)}" if mode in ("suspend", "pause"): self.foreground(mode, [CTL, *argv]) @@ -734,7 +736,7 @@ class ProxyTui(App): if dialog: self.push_screen(dialog) self.feedback(f"… {command}") - self.stream(command, argv, dialog, mode == "copy") + self.stream(command, argv, dialog, mode == "copy", stdin) def foreground(self, mode, argv): with self.suspend(): @@ -747,10 +749,10 @@ class ProxyTui(App): self.action_reload() @work(thread=True) - def stream(self, command, argv, dialog, copy=False): + def stream(self, command, argv, dialog, copy=False, stdin=None): out = [] try: - p = model.popen(argv) + p = model.popen(argv, stdin=stdin) if dialog: dialog.proc = p for line in p.stdout: @@ -761,9 +763,9 @@ class ProxyTui(App): except OSError as e: out.append(f"cannot run proxy-ctl: {e}") status = 127 - self.call_from_thread(self.finish, command, argv, dialog, copy, out, status, stream_shown=True) + self.call_from_thread(self.finish, command, argv, dialog, copy, out, status, stream_shown=True, stdin=stdin) - def finish(self, command, argv, dialog, copy, out, status, stream_shown=False): + def finish(self, command, argv, dialog, copy, out, status, stream_shown=False, stdin=None): """A run's end: the feedback line, the clipboard, and the dialog's tail.""" if dialog and not stream_shown: for line in out: @@ -784,7 +786,7 @@ class ProxyTui(App): hints = ["o: full output"] if len(out) > 1 and not dialog else [] self.retry = None if model.needs_root(out, status): - self.retry = ("dialog" if dialog else "copy" if copy else "run", argv) + self.retry = ("dialog" if dialog else "copy" if copy else "run", argv, stdin) hints.append("!: retry as root") if dialog: dialog.offer_retry() @@ -795,7 +797,8 @@ class ProxyTui(App): if not self.retry: self.feedback("Nothing to retry as root.") return - (mode, argv), self.retry = self.retry, None + (mode, argv, *rest), self.retry = self.retry, None + stdin = rest[0] if rest else None command = f"sudo proxy-ctl {shlex.join(argv)}" root_argv = model.elevated(argv, "sudo") # sudo asks on the terminal, so the run happens there; the output comes back as usual. @@ -803,7 +806,12 @@ class ProxyTui(App): with self.suspend(): print(f"$ {command}", flush=True) try: - p = subprocess.Popen(root_argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace") + # sudo asks for the password on the terminal itself, so stdin can carry the text. + p = subprocess.Popen( + root_argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace", + **({"stdin": subprocess.PIPE} if stdin is not None else {}), + ) + model.feed(p, stdin) except OSError as e: p, status, out = None, 127, [f"cannot run sudo: {e}"] if p: @@ -821,7 +829,7 @@ class ProxyTui(App): dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None if dialog: self.push_screen(dialog) - self.finish(command, argv, dialog, mode == "copy", out, status) + self.finish(command, argv, dialog, mode == "copy", out, status, stdin=stdin) def action_switch_root(self): def switch(ok): diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index 0d297c9..918969f 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -602,7 +602,9 @@ class AutoProxyTest(EnvTest): self.assertIn("proxy-suite group, or re-run with sudo", err) -class RuntimeEntryTest(EnvTest): +class RuntimeSpoolTest(EnvTest): + """The runtime spools, and a backend that reads them back on every reload.""" + def setUp(self): super().setUp() os.environ.update( @@ -636,6 +638,8 @@ class RuntimeEntryTest(EnvTest): self.backend_start() return 0, "" + +class RuntimeEntryTest(RuntimeSpoolTest): def test_tag_for(self): tag = ctl._runtime_tag_for self.assertEqual(tag("outbound", "vless://u@de1.example.net:443?security=reality#%F0%9F%87%A9%F0%9F%87%AA%20DE-1"), "DE-1") @@ -754,6 +758,115 @@ class RuntimeEntryTest(EnvTest): self.assertEqual(os.listdir(self.path("outbounds.d")), []) +AWG_CONF = """[Interface] +PrivateKey = private +Address = 10.8.0.2/32 + +[Peer] +PublicKey = public +AllowedIPs = 0.0.0.0/0 +Endpoint = vpn.example.com:51820 +""" + + +def awg_vpn_link(description): + """A vpn:// export carrying AWG_CONF, as the Amnezia app writes one.""" + import base64 + import zlib + + data = json.dumps({"description": description, "containers": [{"container": "amnezia-awg", "awg": {"last_config": json.dumps({"config": AWG_CONF})}}]}).encode() + return "vpn://" + base64.urlsafe_b64encode(len(data).to_bytes(4, "big") + zlib.compress(data)).decode().rstrip("=") + + +class AmneziaWgRuntimeTest(RuntimeSpoolTest): + """`awg add`/`rm` and AmneziaWG outbounds: amneziawg_config.py itself checks and writes them.""" + + def setUp(self): + super().setUp() + tool = os.environ.get("AWG_CONFIG_TOOL") or os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../scripts/amneziawg_config.py") + os.makedirs(self.path("amneziawg.d")) + os.environ.update( + AWG_CONFIG_TOOL=tool, + AWG_RUNTIME_GLOBAL="1", + AWG_RUNTIME_OUTBOUNDS="1", + AWG_RUNTIME_DIR=self.path("amneziawg.d"), + AWG_PROFILES_FILE=self.write("awg-profiles.json", ["home"]), + AWG_TUNNEL_BASE_PORT="18800", + AWG_TUNNEL_SLOTS="2", + ) + self.active = set() + self.patch("svc_active", lambda unit: unit in self.active) + self.patch("svc_state", lambda unit: "active" if unit in self.active else "inactive") + self.patch("svc_exists", lambda unit: True) + + def test_add_and_rm_global_profiles(self): + # Named after the server's host, then after the export's description; the config on stdin. + self.assertIn("Name: awg-example (none given", ok(ctl.cmd_awg, "add", AWG_CONF)) + self.assertIn("Name: awg-example-2", ok(ctl.cmd_awg, "add", AWG_CONF)) + with mock.patch.object(sys, "stdin", io.StringIO(awg_vpn_link("Work VPN"))): + self.assertIn("Name: Work-VPN", ok(ctl.cmd_awg, "add", "-")) + conf = self.write("office.conf", AWG_CONF) + ok(ctl.cmd_awg, "add", "office", conf) + path = self.path("amneziawg.d/office.conf") + self.assertEqual(os.stat(path).st_mode & 0o777, 0o600) + self.assertIn("Endpoint = vpn.example.com:51820", ctl.read_text(path)) + self.assertEqual(ctl._awg_profiles(), ["home", "Work-VPN", "awg-example", "awg-example-2", "office"]) + self.assertEqual(ctl._awg_service("office"), "proxy-suite-awg@office") + self.assertEqual(ctl._awg_service("home"), "proxy-suite-awg-home") + listing = ok(ctl.cmd_awg, "list") + self.assertRegex(listing, r"home\s+inactive\s+declared") + self.assertRegex(listing, r"office\s+inactive\s+runtime") + self.assertIn("office", ctl._complete_tree("awg", "rm")) + # Refused: a taken or reserved name, the wrong order, hooks, and anything but a config. + for args, why in [ + (("home", AWG_CONF), "declared in the NixOS configuration"), + (("office", AWG_CONF), "already exists"), + (("warp", AWG_CONF), "reserved"), + (("bad name", AWG_CONF), "Invalid profile name"), + ((AWG_CONF, "later"), "The name goes first"), + (("hooked", AWG_CONF.replace("Address", "PostUp = id\nAddress")), "privileged"), + (("nothing", "vless://u@x.test:443"), "Cannot read"), + ]: + with self.subTest(args=args[0][:10]): + status, _, err = run(ctl.cmd_awg, "add", *args) + self.assertNotEqual(status, 0) + self.assertIn(why, err) + self.assertFalse(os.path.exists(self.path("amneziawg.d/hooked.conf"))) + # rm: only what awg add added; a running one stops first, and its kill switch with it. + self.assertIn("remove it there", run(ctl.cmd_awg, "rm", "home")[2]) + self.active.add("proxy-suite-awg@office") + self.assertIn("Removed AmneziaWG profile: office", ok(ctl.cmd_awg, "rm", "office")) + self.assertIn(("stop", "proxy-suite-awg@office"), self.started) + self.assertIn(("stop", ctl.KILL_SWITCH), self.started) + self.assertFalse(os.path.exists(path)) + self.assertNotIn("office", ctl._awg_profiles()) + # Off in the configuration: nothing to add to, and nothing listed. + os.environ["AWG_RUNTIME_GLOBAL"] = "0" + self.assertIn("not enabled", run(ctl.cmd_awg, "add", AWG_CONF)[2]) + self.assertEqual(ctl._awg_profiles(), ["home"]) + + def test_outbounds(self): + self.assertIn("Tag: awg-example", ok(ctl.cmd_outbounds, "add", AWG_CONF)) + self.assertEqual(ctl.read_text(self.path("outbounds.d/awg-example.port")), "18800\n") + self.assertEqual(os.stat(self.path("outbounds.d/awg-example.awg")).st_mode & 0o777, 0o600) + self.assertIn("proxy-suite-outbound-reload.service", self.started) + # A file, with a tag: the next port. + self.assertIn("Added outbound: de", ok(ctl.cmd_outbounds, "add", "de", self.write("de.conf", AWG_CONF))) + self.assertEqual(ctl.read_text(self.path("outbounds.d/de.port")), "18801\n") + self.assertIn("No free port", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF)[2]) + self.assertIn("cannot chain", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF, "--detour", "primary")[2]) + self.assertIn("--container only applies", run(ctl.cmd_outbounds, "add", "x", "vless://u@x.test:443", "--container", "c")[2]) + # A copy through a hop makes no sense for a tunnel that dials its peer itself. + self.write("outbound-share.json", {"outbounds": {"de": {"outbound": {"type": "socks", "server": "127.0.0.1", "server_port": 18801}}}}) + self.assertIn("AmneziaWG outbound", run(ctl.cmd_outbound_chain, "de", "primary")[2]) + # rm takes the port along, which frees it. + ok(ctl.cmd_outbounds, "rm", "de") + self.assertFalse(os.path.exists(self.path("outbounds.d/de.port"))) + self.assertEqual(ctl._awg_free_port(), 18801) + os.environ["AWG_RUNTIME_OUTBOUNDS"] = "0" + self.assertIn("not enabled", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF)[2]) + + class ZapretAutoTest(EnvTest): @unittest.skipIf(os.geteuid() == 0, "root writes anything") def test_clear_replaces_what_it_cannot_write(self): diff --git a/pkgs/proxy-ctl/test_proxy_model.py b/pkgs/proxy-ctl/test_proxy_model.py index 337dfce..6993376 100644 --- a/pkgs/proxy-ctl/test_proxy_model.py +++ b/pkgs/proxy-ctl/test_proxy_model.py @@ -11,7 +11,10 @@ import unittest from unittest import mock import proxy_ctl as ctl -import proxy_model as model + +CLI_AWG_PROFILES = ctl._awg_profiles # before setUp patches it + +import proxy_model as model # noqa: E402 def walk(items): @@ -244,10 +247,67 @@ class ModelTest(unittest.TestCase): ("zapret", "not a host", "Not a share link"), ]: with self.subTest(text=text): - argv, message = paste(tab, text) + argv, message, stdin = paste(tab, text) self.assertIsNone(argv) + self.assertIsNone(stdin) self.assertIn(why, message) + def test_paste_amneziawg(self): + conf = "[Interface]\nPrivateKey = secret\nAddress = 10.8.0.2/32\n\n[Peer]\nPublicKey = p\nAllowedIPs = 0.0.0.0/0\n" + runtime = {"AWG_RUNTIME_GLOBAL": "1", "AWG_RUNTIME_OUTBOUNDS": "1"} + with mock.patch.dict(os.environ, runtime): + # A global profile, but an outbound on the outbounds tab. The config itself only on stdin. + self.assertEqual(model.paste_argv("services", conf), (["awg", "add", "-"], "", conf.strip())) + self.assertEqual(model.paste_argv("awg", "vpn://AAAA"), (["awg", "add", "-"], "", "vpn://AAAA")) + self.assertEqual(model.paste_argv("outbounds", "vpn://AAAA"), (["proxy", "outbounds", "add", "-"], "", "vpn://AAAA")) + with mock.patch.dict(os.environ, {"AWG_RUNTIME_GLOBAL": "0", "AWG_RUNTIME_OUTBOUNDS": "1"}): + self.assertEqual(model.paste_argv("services", "vpn://AAAA")[0], ["proxy", "outbounds", "add", "-"]) + with mock.patch.dict(os.environ, {"AWG_RUNTIME_GLOBAL": "0", "AWG_RUNTIME_OUTBOUNDS": "0"}): + argv, why, stdin = model.paste_argv("services", conf) + self.assertIsNone(argv) + self.assertIn("amneziaWg.runtime", why) + + def test_awg_tab(self): + tab = next(t for t in model.TABS if t.id == "awg") + with tempfile.TemporaryDirectory() as d: + open(os.path.join(d, "added.conf"), "w").close() + profiles = os.path.join(d, "profiles.json") + with open(profiles, "w") as f: + json.dump(["home"], f) + env = {"AWG_RUNTIME_GLOBAL": "1", "AWG_RUNTIME_DIR": d, "AWG_PROFILES_FILE": profiles} + with mock.patch.dict(os.environ, env), mock.patch.object(ctl, "_awg_profiles", CLI_AWG_PROFILES): + self.assertTrue(tab.available({})) + rows, _ = model.load_tab(tab, {"proxy-suite-awg@added": "active"}) + self.assertEqual( + [(r["profile"], r["unit"], r["state"], r["source"]) for r in rows], + [("home", "proxy-suite-awg-home", "inactive", "declared"), ("added", "proxy-suite-awg@added", "active", "runtime")], + ) + self.assertEqual([a.key for a in model.applicable(tab, rows[0])], ["space", "l", "n"]) + self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["space", "ctrl+r", "l", "n", "d"]) + act = {a.key: a for a in tab.actions} + self.assertEqual(act["space"].argv(rows[1], "", {}), ["awg", "off", "added"]) + self.assertEqual(act["d"].argv(rows[1], "", {}), ["awg", "rm", "added"]) + # The Services tab's row for the instance toggles it through `awg` too. + self.assertEqual(model.toggle_argv({"unit": "proxy-suite-awg@added", "state": "active"}), ["awg", "off", "added"]) + add = next(a for a in tab.actions if a.key == "n") + self.assertEqual((add.argv(None, "work vpn://AAAA", {}), add.stdin(None, "work vpn://AAAA")), (["awg", "add", "work", "-"], "vpn://AAAA")) + self.assertEqual((add.argv(None, "vpn://AAAA", {}), add.stdin(None, "vpn://AAAA")), (["awg", "add", "-"], "vpn://AAAA")) + # A path goes as one: proxy-ctl reads it, and it may run as root elsewhere. + self.assertEqual((add.argv(None, "work /tmp/w.conf", {}), add.stdin(None, "work /tmp/w.conf")), (["awg", "add", "work", "/tmp/w.conf"], None)) + outbound_add = next(a for a in next(t for t in model.TABS if t.id == "outbounds").actions if a.key == "n") + self.assertEqual(outbound_add.argv(None, "de vpn://AAAA", {}), ["proxy", "outbounds", "add", "de", "-"]) + self.assertEqual(outbound_add.stdin(None, "de vpn://AAAA"), "vpn://AAAA") + self.assertEqual(outbound_add.argv(None, "de vless://x", {}), ["proxy", "outbounds", "add", "de", "vless://x"]) + self.assertIsNone(outbound_add.stdin(None, "de vless://x")) + + def test_popen_feeds_stdin(self): + with mock.patch.object(model, "CTL", "cat"): + for stdin, out in (("secret\n", "secret\n"), (None, "")): + p = model.popen([], stdin=stdin) + with p.stdout: + self.assertEqual(p.stdout.read(), out) + p.wait() + def test_load_tab(self): tab = next(t for t in model.TABS if t.id == "outbounds") inventory = {"tags": ["a", "b"], "pinned": "b", "detours": {"a": "b"}, "excluded": ["b"]} diff --git a/pkgs/proxy-ctl/test_proxy_tui.py b/pkgs/proxy-ctl/test_proxy_tui.py index 62f4c27..5e20a7f 100644 --- a/pkgs/proxy-ctl/test_proxy_tui.py +++ b/pkgs/proxy-ctl/test_proxy_tui.py @@ -54,7 +54,8 @@ class TuiTest(unittest.TestCase): patcher.start() self.addCleanup(patcher.stop) self.ran = [] - patcher = mock.patch.object(tui.ProxyTui, "run_argv", lambda app, mode, argv: self.ran.append(argv)) + # A run with stdin is recorded with it: (argv, stdin). + patcher = mock.patch.object(tui.ProxyTui, "run_argv", lambda app, mode, argv, stdin=None: self.ran.append(argv if stdin is None else (argv, stdin))) patcher.start() self.addCleanup(patcher.stop) @@ -69,7 +70,7 @@ class TuiTest(unittest.TestCase): def test_retry_root_leaves_sigint_to_sudo(self): """Ctrl-C at sudo's password prompt is sudo's: raised here it would take the TUI down with it.""" - app = mock.MagicMock(retry=("run", ["proxy", "on"])) + app = mock.MagicMock(retry=("run", ["proxy", "on"], None)) app.suspend.return_value = contextlib.nullcontext() before, during = signal.getsignal(signal.SIGINT), [] with mock.patch.object(tui.subprocess, "Popen") as popen, contextlib.redirect_stdout(io.StringIO()): @@ -79,6 +80,20 @@ class TuiTest(unittest.TestCase): self.assertEqual(during, [signal.SIG_IGN]) self.assertEqual(signal.getsignal(signal.SIGINT), before) self.assertEqual(app.finish.call_args.args[-2:], (["done"], 0)) + self.assertNotIn("stdin", popen.call_args.kwargs) + + def test_retry_root_carries_stdin(self): + """A config pasted on stdin reaches sudo's proxy-ctl the same way.""" + app = mock.MagicMock(retry=("run", ["awg", "add", "-"], "vpn://AAAA")) + app.suspend.return_value = contextlib.nullcontext() + with mock.patch.object(tui.subprocess, "Popen") as popen, contextlib.redirect_stdout(io.StringIO()): + popen.return_value.stdout = iter(["Added\n"]) + popen.return_value.wait.return_value = 0 + tui.ProxyTui.action_retry_root(app) + self.assertEqual(popen.call_args.args[0][-3:], ["awg", "add", "-"]) + self.assertEqual(popen.call_args.kwargs["stdin"], tui.subprocess.PIPE) + popen.return_value.stdin.write.assert_called_once_with("vpn://AAAA") + self.assertEqual(app.finish.call_args.kwargs["stdin"], "vpn://AAAA") def test_filter_sort_pack(self): rows = [{"key": "a", "host": "a.example", "kind": "learned"}, {"key": "b", "host": "learned.org", "kind": "pinned"}] @@ -139,6 +154,12 @@ class TuiTest(unittest.TestCase): await pilot.pause() self.assertEqual(self.ran, []) self.assertIn("ftp:// link", str(app.main.query_one("#feedback").content)) + # An AmneziaWG config: its keys go on stdin, never into argv. + self.env["AWG_RUNTIME_OUTBOUNDS"] = "1" + conf = "[Interface]\nPrivateKey = k\n[Peer]\nPublicKey = p" + app.post_message(events.Paste(conf)) + await pilot.pause() + self.assertEqual(self.ran.pop(), (["proxy", "outbounds", "add", "-"], conf)) asyncio.run(run()) @@ -211,7 +232,16 @@ class TuiTest(unittest.TestCase): self.assertEqual(self.ran.pop(), ["awg", "restart", "p"]) app.table().move_cursor(row=list(app.rows["services"]).index("proxy-suite-tun")) - # Right arrow moves to Routing and its table has focus. + # Right arrow moves to AmneziaWG, there with a profile, and its table has focus. + await pilot.press("right") + await self.settle(app, pilot) + self.assertEqual((app.active_tab(), app.focused.id), ("awg", "awg-table")) + await pilot.press("space") + self.assertEqual(self.ran.pop(), ["awg", "off", "p"]) + # Declared: nothing removes it here. + self.assertNotIn("d", app.screen.active_bindings) + + # On to Routing. await pilot.press("right") await self.settle(app, pilot) self.assertEqual((app.active_tab(), app.focused.id), ("routing", "routing-table")) @@ -263,7 +293,7 @@ class TuiTest(unittest.TestCase): await pilot.press("escape") # An empty tab says how to fill it. - await pilot.press("4") + await pilot.press("5") await self.settle(app, pilot) self.assertIn("Nothing here yet. n: add a runtime subscription", str(app.main.query_one("#subs-summary").content)) @@ -280,7 +310,7 @@ class TuiTest(unittest.TestCase): # Brackets in a summary are text, not markup. self.env["ZAPRET_CUTOFF_ENABLED"] = "1" self.capture = "Probed: [b] from [/x]\nCutoff: none on this line\n" - await pilot.press("5") + await pilot.press("6") await self.settle(app, pilot) self.assertIn("[/x]", str(app.main.query_one("#zapret-summary").content)) await self.settle(app, pilot) @@ -333,7 +363,7 @@ class TuiTest(unittest.TestCase): self.env["INBOUNDS_ENABLED"] = "1" app.action_reload() await self.settle(app, pilot) - await pilot.press("6") + await pilot.press("7") await self.settle(app, pilot) await pilot.press("c") self.assertEqual(self.ran.pop(), ["inbounds", "link", "vless", "alice"]) diff --git a/scripts/amneziawg_config.py b/scripts/amneziawg_config.py index f785ce3..2fbeb56 100644 --- a/scripts/amneziawg_config.py +++ b/scripts/amneziawg_config.py @@ -11,6 +11,7 @@ import json import os import re import socket +import sys import tempfile import zlib from pathlib import Path @@ -736,6 +737,35 @@ def prepare(manifest: dict[str, Any]) -> str: return config +def import_source(text: str, container: str | None = None) -> tuple[str, dict[str, str]]: + """A pasted .conf or vpn:// link as a normalized .conf, and what it says about itself. + + For profiles added at runtime: hooks are refused whatever the source, since whoever may + add one need not be root. The name is the export's description, else its server's host. + """ + text = text.strip() + name = "" + if text.startswith("vpn://"): + data = decode_vpn_link(text) + config = extract_vpn_config(data, container) + for key in ("description", "name", "hostName"): + if isinstance(data.get(key), str) and data[key].strip(): + name = data[key].strip() + break + elif "[interface]" in text.lower(): + if container: + raise ConfigError("--container only applies to a vpn:// link") + config = _apply_awg3_mtu_default(text + "\n") + else: + raise ConfigError("expected an AmneziaWG .conf or a vpn:// link") + validate_config(config) + endpoints = section_values(config, "peer", "endpoint") + endpoint = endpoints[0] if endpoints else "" + if not name and endpoint: + name = endpoint.rsplit(":", 1)[0].strip("[]") + return config, {"name": name, "endpoint": endpoint} + + def write_private(path: str, content: str) -> None: destination = Path(path) destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700) @@ -782,6 +812,18 @@ def main() -> int: action="store_true", help="write Endpoint names as the addresses they resolve to here", ) + parser.add_argument( + "--import", + dest="import_", + metavar="SOURCE", + help="normalize a .conf or vpn:// link (a path, or - for stdin), hooks refused", + ) + parser.add_argument("--container", help="with --import: which container of a vpn:// export") + parser.add_argument( + "--describe", + action="store_true", + help="with --import: print the name and endpoint it carries as JSON", + ) parser.add_argument( "--inspect", metavar="CONFIG", @@ -795,6 +837,25 @@ def main() -> int: config = _read_limited(args.inspect) print(transport_implementation(config), probe_address(config), rekey_after_time(config)) return 0 + if args.import_ is not None: + if args.manifest is not None or args.config is not None: + raise ConfigError("--import cannot be combined with --manifest or --config") + if args.output is None and not args.describe: + raise ConfigError("--import needs --output, --describe or both") + if args.import_ == "-": + text = sys.stdin.read(MAX_INPUT_BYTES + 1) + if len(text) > MAX_INPUT_BYTES: + raise ConfigError(f"input exceeds {MAX_INPUT_BYTES} bytes") + else: + text = _read_limited(args.import_) + config, described = import_source(text, args.container) + if args.output is not None: + write_private(args.output, config) + if args.describe: + print(json.dumps(described)) + return 0 + if args.container is not None or args.describe: + raise ConfigError("--container and --describe only apply to --import") 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" @@ -815,7 +876,7 @@ def main() -> int: if args.resolve_endpoints: config = resolve_endpoints(config) write_private(args.output, config) - except (ConfigError, KeyError, OSError, json.JSONDecodeError) as exc: + except (ConfigError, KeyError, OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: parser.exit(1, f"amneziawg-config: {exc}\n") return 0 diff --git a/scripts/test-amneziawg-config.py b/scripts/test-amneziawg-config.py index 8a696aa..f99d8ef 100644 --- a/scripts/test-amneziawg-config.py +++ b/scripts/test-amneziawg-config.py @@ -536,6 +536,62 @@ class AmneziaWgConfigTests(unittest.TestCase): unmarked = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700") self.assertEqual(amneziawg_config.section_values(unmarked, "interface", "fwmark"), []) + def import_cli(self, text, *args): + return subprocess.run( + [sys.executable, amneziawg_config.__file__, "--import", "-", *args], + input=text, + capture_output=True, + text=True, + ) + + def test_import_conf_and_vpn_links(self): + conf = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1") + config, described = amneziawg_config.import_source(conf) + self.assertIn("MTU = 1280", config) + self.assertEqual(described, {"name": "vpn.example.com", "endpoint": "vpn.example.com:51820"}) + + data = vpn_data(("amnezia-awg", "awg", BASE_CONFIG)) + data["description"] = "Home server" + config, described = amneziawg_config.import_source(encode_vpn(data)) + self.assertIn("DNS = 1.1.1.1,8.8.8.8", config) + self.assertEqual(described["name"], "Home server") + + direct = "vpn://" + base64.urlsafe_b64encode(conf.encode()).decode() + self.assertIn("[Peer]", amneziawg_config.import_source(direct)[0]) + + def test_import_picks_a_container_and_refuses_hooks(self): + data = vpn_data( + ("amnezia-awg", "awg", BASE_CONFIG), + ("amnezia-awg2", "awg", BASE_CONFIG.replace("10.8.0.2", "10.9.0.2")), + ) + data["defaultContainer"] = "not-awg" + with self.assertRaisesRegex(ConfigError, "multiple AmneziaWG"): + amneziawg_config.import_source(encode_vpn(data)) + self.assertIn("10.9.0.2", amneziawg_config.import_source(encode_vpn(data), "amnezia-awg2")[0]) + conf = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1") + with self.assertRaisesRegex(ConfigError, "only applies"): + amneziawg_config.import_source(conf, "amnezia-awg") + with self.assertRaisesRegex(ConfigError, "privileged"): + amneziawg_config.import_source(conf.replace("Address =", "PostUp = id\nAddress =")) + with self.assertRaisesRegex(ConfigError, "expected"): + amneziawg_config.import_source("vless://nope") + + def test_import_cli_writes_a_private_conf_and_describes_it(self): + conf = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1") + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "home.conf" + result = self.import_cli(conf, "--describe", "--output", str(output)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["name"], "vpn.example.com") + self.assertEqual(output.stat().st_mode & 0o777, 0o600) + self.assertIn("[Interface]", output.read_text()) + hooked = self.import_cli(conf.replace("Address =", "PreUp = id\nAddress ="), "--output", str(output)) + self.assertEqual(hooked.returncode, 1) + self.assertIn("privileged", hooked.stderr) + # A refused import leaves what was there. + self.assertIn("[Interface]", output.read_text()) + self.assertEqual(self.import_cli(conf).returncode, 1) + if __name__ == "__main__": unittest.main()