diff --git a/docs/options/amneziaWg.md b/docs/options/amneziaWg.md
index 5ae0f68..e218d01 100644
--- a/docs/options/amneziaWg.md
+++ b/docs/options/amneziaWg.md
@@ -103,6 +103,11 @@ null or package
Named AmneziaWG client profiles\. Only one global profile can be active\.
+A profile moves to a new source port, keeping its routes, when a handshake goes
+unanswered: every 5 seconds while it starts (it gives up after 20), and when
+proxy-suite-awg-NAME-watchdog sees a rekey not getting through\. settings\.listenPort
+pins the port and turns that off\.
+
*Type:*
attribute set of (submodule)
diff --git a/docs/options/index.md b/docs/options/index.md
index f585cef..0d09572 100644
--- a/docs/options/index.md
+++ b/docs/options/index.md
@@ -213,7 +213,7 @@ services.proxy-suite = {
port = 22;
user = null;
};
- serviceUser = null;
+ serviceUser = "proxy-suite-daemon";
strictHostKeyChecking = "accept-new";
};
tgWsProxy = {
@@ -258,6 +258,7 @@ services.proxy-suite = {
asOutbound = false;
configFile = null;
enable = false;
+ generatorUrl = null;
};
zapret = {
cidrExemption = {
diff --git a/docs/options/sshProxy.md b/docs/options/sshProxy.md
index adfc184..e686c4b 100644
--- a/docs/options/sshProxy.md
+++ b/docs/options/sshProxy.md
@@ -147,7 +147,7 @@ null
## services\.proxy-suite\.sshProxy\.identityFile
-Runtime path to the private key\. Null uses the agent or OpenSSH defaults\.
+Runtime path to the private key; it may stay root-only, as the daemons get a copy they can read\. Null uses the agent or OpenSSH defaults\.
*Type:*
null or string
@@ -269,7 +269,7 @@ null
## services\.proxy-suite\.sshProxy\.serviceUser
-Unix user running the OpenSSH unit\.
+Unix user running the OpenSSH unit\. The default, proxy-suite-daemon, runs sandboxed and keeps accepted host keys in /var/lib/proxy-suite/ssh; null runs it as root\.
*Type:*
null or string matching the pattern \[^\[:space:]]+
@@ -277,7 +277,7 @@ null or string matching the pattern \[^\[:space:]]+
*Default:*
```nix
-null
+"proxy-suite-daemon"
```
*Example:*
diff --git a/docs/options/tgWsProxy.md b/docs/options/tgWsProxy.md
index 0343366..13228be 100644
--- a/docs/options/tgWsProxy.md
+++ b/docs/options/tgWsProxy.md
@@ -221,7 +221,7 @@ Listen port\.
## services\.proxy-suite\.tgWsProxy\.log\.file
-Rotating log file\. Null logs to stderr\.
+Rotating log file, written as the proxy-suite-daemon user; /var/log/proxy-suite-tg-ws-proxy is created for it\. Null logs to stderr\.
*Type:*
null or string
@@ -235,7 +235,7 @@ null
*Example:*
```nix
-"/var/log/tg-ws-proxy.log"
+"/var/log/proxy-suite-tg-ws-proxy/tg-ws-proxy.log"
```
diff --git a/docs/options/warp.md b/docs/options/warp.md
index 4b938f2..fff7907 100644
--- a/docs/options/warp.md
+++ b/docs/options/warp.md
@@ -9,6 +9,7 @@ Part of the [proxy-suite options reference](./index.md).
- [asAmneziaWg](#services-proxy-suite-warp-asamneziawg)
- [asOutbound](#services-proxy-suite-warp-asoutbound)
- [configFile](#services-proxy-suite-warp-configfile)
+ - [generatorUrl](#services-proxy-suite-warp-generatorurl)
## services\.proxy-suite\.warp\.enable
@@ -33,7 +34,8 @@ true
## services\.proxy-suite\.warp\.asAmneziaWg
-Add an AmneziaWG profile named “warp” (` proxy-ctl awg on warp `)\. Requires amneziaWg\.enable\.
+Add an AmneziaWG profile named “warp” (` proxy-ctl awg on warp `)\. Requires amneziaWg\.enable,
+and excludes asOutbound: both would use the same WARP key\.
*Type:*
boolean
@@ -48,8 +50,9 @@ false
## services\.proxy-suite\.warp\.asOutbound
Add WARP as an outbound tagged “warp”: a SOCKS hop to proxy-suite-warp-tunnel, which
-runs WARP as a sing-box WireGuard endpoint on 127\.0\.0\.1:18538 and restarts it on a new
-source port when the handshake stops being answered\.
+runs WARP as a sing-box WireGuard endpoint on 127\.0\.0\.1:18538, as the proxy-suite-daemon user\.
+The tunnel starts again on a new source port when WARP does not answer within 15 seconds
+of a start, or misses three probes later on, unless the uplink itself is down\.
*Type:*
boolean
@@ -64,7 +67,7 @@ false
## services\.proxy-suite\.warp\.configFile
Runtime path to a WireGuard profile for WARP, as written by ` wgcf register && wgcf generate `\.
-Junk-packet lines (Jc, Jmin, Jmax) are honoured by the AmneziaWG profile only\.
+AmneziaWG lines (Jc, S1-S4, H1-H4, I1-I5, AWG 3 timing) are honoured by the AmneziaWG profile only\.
When null, proxy-suite-warp registers a device with wgcf (accepting Cloudflare’s terms)
into /var/lib/proxy-suite/warp, through the local proxy when proxy\.enable is set, and
@@ -84,3 +87,27 @@ null
```nix
"/run/secrets/wgcf-profile.conf"
```
+
+
+## services\.proxy-suite\.warp\.generatorUrl
+
+HTTPS URL of a WARP profile generator, fetched directly when wgcf registration fails
+(e\.g\. the Cloudflare API is blocked and there is no local proxy)\. It must return a
+WireGuard profile, or JSON with the base64 profile in ` .content `\.
+
+The generator registers the device, so its operator sees the private key\.
+
+*Type:*
+null or string
+
+*Default:*
+
+```nix
+null
+```
+
+*Example:*
+
+```nix
+"https://valokda-amnezia.vercel.app/api/warp?mode=awg2"
+```
diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix
index 112be9b..0ba2526 100644
--- a/modules/proxy-suite/amnezia-wg.nix
+++ b/modules/proxy-suite/amnezia-wg.nix
@@ -25,38 +25,37 @@ let
profile.settings
]
);
- inlineVpnFile = name: profile: pkgs.writeText "proxy-suite-awg" profile.vpn;
- sourceKind =
+ source =
profile:
if profile.configFile != null then
- "configFile"
+ {
+ kind = "configFile";
+ path = profile.configFile;
+ }
else if profile.vpnFile != null then
- "vpnFile"
+ {
+ kind = "vpnFile";
+ path = profile.vpnFile;
+ }
else if profile.vpn != null then
- "vpn"
+ {
+ kind = "vpn";
+ path = pkgs.writeText "proxy-suite-awg" profile.vpn;
+ }
else
- "settings";
- sourcePath =
- name: profile:
- if profile.configFile != null then
- profile.configFile
- else if profile.vpnFile != null then
- profile.vpnFile
- else if profile.vpn != null then
- inlineVpnFile name profile
- else
- null;
+ {
+ kind = "settings";
+ inherit (profile) settings;
+ };
manifestFor =
- name: profile:
+ profile:
pkgs.writeText "proxy-suite-awg" (
builtins.toJSON (
{
- kind = sourceKind profile;
allowConfigHooks = profile.allowConfigHooks;
vpnContainer = profile.vpnContainer;
}
- // lib.optionalAttrs (sourcePath name profile != null) { path = sourcePath name profile; }
- // lib.optionalAttrs (profile.settings != null) { settings = profile.settings; }
+ // source profile
)
);
configTool = "${
@@ -69,11 +68,42 @@ let
runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf";
# Keep proxy backend sockets (proxyMark) out of AWG's default-route table.
proxyBypassRulePriority = 8998;
+ bypassRule =
+ family: action:
+ "${pkgs.iproute2}/bin/ip ${family} rule ${action} pref ${toString proxyBypassRulePriority} fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main";
+ clearBypassRules = lib.concatMapStrings (family: ''
+ while ${bypassRule family "del"} 2>/dev/null; do :; done
+ '') [ "-4" "-6" ];
+
+ # Some lines drop a share of fresh flows for good, handshakes included. A new source port
+ # is a new flow, and moving the interface to one keeps its routes, so traffic never leaks
+ # past the tunnel while it tries again. A pinned ListenPort is left alone.
+ mkHandshakeHelpers = profile: ''
+ awg=${awgCfg.toolsPackage}/bin/awg
+ interface=${lib.escapeShellArg profile.interfaceName}
+
+ # Seconds since the newest handshake of any peer; a large number before the first.
+ handshake_age() {
+ local latest
+ latest=$("$awg" show "$interface" latest-handshakes 2>/dev/null \
+ | ${pkgs.gawk}/bin/awk '$2 > max { max = $2 } END { print max + 0 }')
+ if (( latest == 0 )); then echo 1000000; else echo $(( $(${pkgs.coreutils}/bin/date +%s) - latest )); fi
+ }
+
+ new_source_port() {
+ ${
+ if profile.settings != null && profile.settings.listenPort != null then
+ ":"
+ else
+ ''"$awg" set "$interface" listen-port 0 || true''
+ }
+ }
+ '';
mkService =
name: profile:
let
- manifest = manifestFor name profile;
+ manifest = manifestFor profile;
configPath = runtimeConfig name profile;
prepare = pkgs.writeShellScript "proxy-suite-awg" ''
set -euo pipefail
@@ -83,36 +113,17 @@ let
'';
proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" ''
set -euo pipefail
-
- add_bypass_rule() {
- local family="$1"
- while ${pkgs.iproute2}/bin/ip "$family" rule del \
- pref ${toString proxyBypassRulePriority} \
- fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done
- if ! ${pkgs.iproute2}/bin/ip "$family" rule add \
- pref ${toString proxyBypassRulePriority} \
- fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; then
- # IPv4 is required, or the proxy backend is captured by AWG; IPv6 is best-
- # effort.
- if [ "$family" = "-4" ]; then
- echo "proxy-suite: unable to install the AWG proxy-backend bypass rule" >&2
- return 1
- fi
- fi
- }
-
- add_bypass_rule -4
- add_bypass_rule -6
+ ${clearBypassRules}
+ # IPv4 is required, or the proxy backend is captured by AWG; IPv6 is best-effort.
+ if ! ${bypassRule "-4" "add"} 2>/dev/null; then
+ echo "proxy-suite: unable to install the AWG proxy-backend bypass rule" >&2
+ exit 1
+ fi
+ ${bypassRule "-6" "add"} 2>/dev/null || true
'';
proxyBypassDown = pkgs.writeShellScript "proxy-suite-awg" ''
set +e
-
- while ${pkgs.iproute2}/bin/ip -4 rule del \
- pref ${toString proxyBypassRulePriority} \
- fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done
- while ${pkgs.iproute2}/bin/ip -6 rule del \
- pref ${toString proxyBypassRulePriority} \
- fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done
+ ${clearBypassRules}
'';
start = pkgs.writeShellScript "proxy-suite-awg" ''
set -Eeuo pipefail
@@ -149,8 +160,8 @@ let
${pkgs.kmod}/bin/modprobe amneziawg 2>/dev/null || true
''}
- implementation="$(${pkgs.python3}/bin/python3 ${configTool} \
- --transport-implementation ${lib.escapeShellArg configPath})"
+ read -r implementation probe _ < <(${pkgs.python3}/bin/python3 ${configTool} \
+ --inspect ${lib.escapeShellArg configPath})
# The 3.1 kernel module dropped RandomTrailers packets with ranged H1-H3 (seen on 20260812);
# userspace carries the fix.
if [[ "$implementation" == userspace ]]; then
@@ -162,14 +173,17 @@ let
${awgCfg.toolsPackage}/bin/awg-quick up ${lib.escapeShellArg configPath}
fi
- probe="$(${pkgs.python3}/bin/python3 ${configTool} --probe-address ${lib.escapeShellArg configPath})"
- for _ in $(${pkgs.coreutils}/bin/seq 1 15); do
+ ${mkHandshakeHelpers profile}
+ # A handshake is retried every 5 seconds: each retry after the first gets a new port.
+ for attempt in $(${pkgs.coreutils}/bin/seq 1 20); do
${pkgs.iputils}/bin/ping -n -c 1 -W 1 "$probe" >/dev/null 2>&1 || true
- if ${awgCfg.toolsPackage}/bin/awg show ${lib.escapeShellArg profile.interfaceName} latest-handshakes 2>/dev/null \
- | ${pkgs.gawk}/bin/awk '$2 + 0 > 0 { found = 1 } END { exit !found }'; then
+ if (( $(handshake_age) < 1000000 )); then
trap - ERR
exit 0
fi
+ if (( attempt % 5 == 0 )); then
+ new_source_port
+ fi
done
echo "proxy-suite: AmneziaWG profile '${name}' did not complete a handshake; rolling back routes" >&2
@@ -232,6 +246,63 @@ let
};
};
+ # 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
+ # a new port.
+ mkWatchdog =
+ name: profile:
+ let
+ watchdog = pkgs.writeShellScript "proxy-suite-awg" ''
+ set -uo pipefail
+ read -r _ probe rekey < <(${pkgs.python3}/bin/python3 ${configTool} \
+ --inspect ${lib.escapeShellArg (runtimeConfig name profile)}) || exit 1
+ if (( rekey == 0 )); then
+ echo "proxy-suite: AmneziaWG profile '${name}' never rekeys; nothing to watch" >&2
+ exec ${pkgs.coreutils}/bin/sleep infinity
+ fi
+ ${mkHandshakeHelpers profile}
+ stale=0
+ while sleep 15; do
+ ${pkgs.iputils}/bin/ping -n -c 1 -W 2 "$probe" >/dev/null 2>&1 || true
+ 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
+ new_source_port
+ stale=0
+ fi
+ done
+ '';
+ in
+ {
+ description = "proxy-suite AmneziaWG client profile ${name} watchdog";
+ bindsTo = [ "${serviceName name}.service" ];
+ after = [ "${serviceName name}.service" ];
+ wantedBy = [ "${serviceName name}.service" ];
+ serviceConfig = {
+ ExecStart = watchdog;
+ Restart = "on-failure";
+ RestartSec = 5;
+ CapabilityBoundingSet = [
+ "CAP_NET_ADMIN"
+ "CAP_NET_RAW"
+ ];
+ NoNewPrivileges = true;
+ PrivateTmp = true;
+ ProtectSystem = "full";
+ ProtectHome = true;
+ ProtectClock = true;
+ ProtectControlGroups = true;
+ ProtectHostname = true;
+ ProtectKernelLogs = true;
+ ProtectKernelModules = true;
+ RestrictRealtime = true;
+ RestrictSUIDSGID = true;
+ LockPersonality = true;
+ };
+ };
+
profileAssertions = lib.concatMap (
name:
let
@@ -268,8 +339,8 @@ let
{
assertion =
obfuscation == null
- || ((obfuscation.headerProtectionKey != null) != (obfuscation.headerProtectionKeyFile != null))
- || (obfuscation.headerProtectionKey == null && obfuscation.headerProtectionKeyFile == null);
+ || obfuscation.headerProtectionKey == null
+ || obfuscation.headerProtectionKeyFile == null;
message = "proxy-suite: AmneziaWG profile '${name}': set at most one header-protection key source";
}
]
@@ -299,6 +370,9 @@ in
(lib.mapAttrs' (
name: profile: lib.nameValuePair (serviceName name) (mkService name profile)
) profiles)
+ (lib.mapAttrs' (
+ name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile)
+ ) profiles)
(lib.mkIf cfg.proxy.tun.enable {
proxy-suite-tun.conflicts = map (name: "${name}.service") serviceNames;
})
diff --git a/modules/proxy-suite/autoproxy-render.nix b/modules/proxy-suite/autoproxy-render.nix
index 61bf37d..1f208c1 100644
--- a/modules/proxy-suite/autoproxy-render.nix
+++ b/modules/proxy-suite/autoproxy-render.nix
@@ -23,6 +23,8 @@ pkgs.writeShellScript "proxy-suite-autoproxy" ''
[(.domains // {}) | to_entries[] | select(.value.exit == $t) | .key] as $d
| {version: 1, rules: (if ($d | length) > 0 then [{domain_suffix: $d}] else [] end)}
' "$2" > "$path.tmp"
+ # sing-box reads it as proxy-suite-daemon through the 0751 state dir.
+ chmod 644 "$path.tmp"
mv -f "$path.tmp" "$path"
done
''
diff --git a/modules/proxy-suite/autoproxy.nix b/modules/proxy-suite/autoproxy.nix
index 630e591..4e8835c 100644
--- a/modules/proxy-suite/autoproxy.nix
+++ b/modules/proxy-suite/autoproxy.nix
@@ -52,7 +52,7 @@ let
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
exit 0
fi
- install -d -m 0750 "$state_dir"
+ install -d -m 0751 "$state_dir"
# Eleven snapshots a second apart: ten one-second deltas per connection.
lines=$(
@@ -86,7 +86,7 @@ let
echo "no probe listeners - is proxy-suite-socks running with autoProxy on?"
exit 0
fi
- install -d -m 0750 "$state_dir"
+ install -d -m 0751 "$state_dir"
# Timer runs and learn requests take turns on the state.
exec 9> "$state_dir/lock"
@@ -114,7 +114,7 @@ let
echo "could not update $state; it is left as it was" >&2
return 1
fi
- # mktemp makes it 0600; the state dir is 0750, so group-readable is enough.
+ # mktemp makes it 0600; the state dir is 0751, so group-readable is enough.
chmod 0640 "$tmp"
mv -f "$tmp" "$state"
}
@@ -396,7 +396,10 @@ let
# declares the directory - systemd re-applies the ownership on each start.
stateDirConfig = {
StateDirectory = "proxy-suite/autoproxy";
- StateDirectoryMode = "0750";
+ # 0751 and a 027 umask: sing-box (proxy-suite) can open the rule-sets, which are
+ # made 0644, and nothing else.
+ StateDirectoryMode = "0751";
+ UMask = "0027";
}
// lib.optionalAttrs (cfg.userControl.allow != [ ]) { Group = cfg.userControl.group; };
diff --git a/modules/proxy-suite/default.nix b/modules/proxy-suite/default.nix
index 7c6c355..b780332 100644
--- a/modules/proxy-suite/default.nix
+++ b/modules/proxy-suite/default.nix
@@ -141,14 +141,15 @@ in
)
(lib.mkIf cfg.tgWsProxy.enable (
- import ./tg-ws-proxy.nix {
+ (import ./tg-ws-proxy.nix {
inherit
lib
pkgs
packages
cfg
+ derived
;
- }
+ }).config
))
# SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH
@@ -159,6 +160,7 @@ in
lib
pkgs
cfg
+ derived
;
}
))
diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix
index b99e143..b63f4aa 100644
--- a/modules/proxy-suite/derived.nix
+++ b/modules/proxy-suite/derived.nix
@@ -44,6 +44,8 @@ let
"/var/lib/proxy-suite/warp/wgcf-profile.conf";
# Loopback SOCKS listener of proxy-suite-warp-tunnel, which the "warp" outbound dials.
tunnelPort = 18538;
+ # Its "direct-in" listener, which tells a blocked WARP from a dead uplink.
+ directPort = 18539;
};
warpOutboundTag = "warp";
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound;
@@ -148,6 +150,47 @@ let
zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds;
userControlEnabled = userControlCfg.allow != [ ];
constants = {
+ # Daemons (sing-box, XRay, the WARP tunnel, OpenSSH, tg-ws-proxy, wgcf) run as this
+ # user. Its group is not the userControl group: backend configs hold credentials. Start
+ # scripts still read secrets and program routing as root, then exec the daemon through
+ # runAsServiceUser with only the capabilities it needs.
+ serviceUser = "proxy-suite-daemon";
+ runAsServiceUser =
+ pkgs: caps:
+ let
+ keep = lib.concatMapStrings (cap: ",+${cap}") caps;
+ in
+ "${pkgs.util-linux}/bin/setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon --clear-groups"
+ + " --inh-caps=-all${keep} --ambient-caps=-all${keep} --bounding-set=-all${keep} --no-new-privs --";
+ # The same for a unit that needs no root at all; "+" ExecStartPre/ExecStopPost
+ # commands still run privileged.
+ unprivilegedServiceConfig =
+ caps:
+ let
+ systemdCaps = map (cap: "CAP_${lib.toUpper cap}") caps;
+ in
+ {
+ User = "proxy-suite-daemon";
+ Group = "proxy-suite-daemon";
+ AmbientCapabilities = systemdCaps;
+ CapabilityBoundingSet = systemdCaps;
+ NoNewPrivileges = true;
+ PrivateTmp = true;
+ ProtectSystem = "full";
+ ProtectHome = true;
+ ProtectKernelModules = true;
+ ProtectKernelLogs = true;
+ ProtectControlGroups = true;
+ RestrictSUIDSGID = true;
+ LockPersonality = true;
+ };
+ # Socket marks and IP_TRANSPARENT, TUN and auto_redirect, listeners below 1024, ICMP.
+ backendCaps = [
+ "net_admin"
+ "net_bind_service"
+ "net_raw"
+ ];
+
zapret2StateDir = "/var/lib/proxy-suite/zapret2";
zapret2CutoffDir = "/var/lib/proxy-suite/zapret2/cutoff";
# Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone.
diff --git a/modules/proxy-suite/options/amnezia-wg.nix b/modules/proxy-suite/options/amnezia-wg.nix
index 9604907..e5d32b1 100644
--- a/modules/proxy-suite/options/amnezia-wg.nix
+++ b/modules/proxy-suite/options/amnezia-wg.nix
@@ -39,7 +39,14 @@ in
profiles = mkOption {
type = types.attrsOf t.profileType;
default = { };
- description = "Named AmneziaWG client profiles. Only one global profile can be active.";
+ description = ''
+ Named AmneziaWG client profiles. Only one global profile can be active.
+
+ A profile moves to a new source port, keeping its routes, when a handshake goes
+ unanswered: every 5 seconds while it starts (it gives up after 20), and when
+ proxy-suite-awg-NAME-watchdog sees a rekey not getting through. settings.listenPort
+ pins the port and turns that off.
+ '';
};
};
}
diff --git a/modules/proxy-suite/options/ssh-proxy.nix b/modules/proxy-suite/options/ssh-proxy.nix
index f6ce61b..a71c9ae 100644
--- a/modules/proxy-suite/options/ssh-proxy.nix
+++ b/modules/proxy-suite/options/ssh-proxy.nix
@@ -47,7 +47,7 @@ in
'';
};
- identityFile = path "Runtime path to the private key. Null uses the agent or OpenSSH defaults." "/run/secrets/proxy-suite-ssh-key";
+ identityFile = path "Runtime path to the private key; it may stay root-only, as the daemons get a copy they can read. Null uses the agent or OpenSSH defaults." "/run/secrets/proxy-suite-ssh-key";
hostKey = mkOption {
type = types.listOf types.str;
@@ -92,8 +92,8 @@ in
serviceUser = mkOption {
type = token;
- default = null;
- description = "Unix user running the OpenSSH unit.";
+ default = "proxy-suite-daemon";
+ description = "Unix user running the OpenSSH unit. The default, proxy-suite-daemon, runs sandboxed and keeps accepted host keys in /var/lib/proxy-suite/ssh; null runs it as root.";
example = "proxy";
};
diff --git a/modules/proxy-suite/options/tg-ws-proxy.nix b/modules/proxy-suite/options/tg-ws-proxy.nix
index 6d9e0b2..05a946c 100644
--- a/modules/proxy-suite/options/tg-ws-proxy.nix
+++ b/modules/proxy-suite/options/tg-ws-proxy.nix
@@ -109,8 +109,8 @@ in
file = mkOption {
type = types.nullOr types.str;
default = null;
- description = "Rotating log file. Null logs to stderr.";
- example = "/var/log/tg-ws-proxy.log";
+ description = "Rotating log file, written as the proxy-suite-daemon user; /var/log/proxy-suite-tg-ws-proxy is created for it. Null logs to stderr.";
+ example = "/var/log/proxy-suite-tg-ws-proxy/tg-ws-proxy.log";
};
maxSizeMiB = mkOption {
diff --git a/modules/proxy-suite/options/warp.nix b/modules/proxy-suite/options/warp.nix
index 317daf8..e827991 100644
--- a/modules/proxy-suite/options/warp.nix
+++ b/modules/proxy-suite/options/warp.nix
@@ -39,8 +39,9 @@ in
default = false;
description = ''
Add WARP as an outbound tagged "warp": a SOCKS hop to proxy-suite-warp-tunnel, which
- runs WARP as a sing-box WireGuard endpoint on 127.0.0.1:18538 and restarts it on a new
- source port when the handshake stops being answered.
+ runs WARP as a sing-box WireGuard endpoint on 127.0.0.1:18538, as the proxy-suite-daemon user.
+ The tunnel starts again on a new source port when WARP does not answer within 15 seconds
+ of a start, or misses three probes later on, unless the uplink itself is down.
'';
};
@@ -48,7 +49,8 @@ in
type = types.bool;
default = false;
description = ''
- Add an AmneziaWG profile named "warp" (`proxy-ctl awg on warp`). Requires amneziaWg.enable.
+ Add an AmneziaWG profile named "warp" (`proxy-ctl awg on warp`). Requires amneziaWg.enable,
+ and excludes asOutbound: both would use the same WARP key.
'';
};
};
diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix
index 0736bee..c547300 100644
--- a/modules/proxy-suite/service-assertions.nix
+++ b/modules/proxy-suite/service-assertions.nix
@@ -76,6 +76,14 @@ let
(mkAssertion (
!cfg.warp.enable || cfg.warp.asOutbound || cfg.warp.asAmneziaWg
) "proxy-suite: warp.enable = true needs warp.asOutbound or warp.asAmneziaWg")
+ # One key, one session: the second peer on a WARP key takes the session over.
+ (mkAssertion (!(cfg.warp.enable && cfg.warp.asOutbound && cfg.warp.asAmneziaWg))
+ "proxy-suite: warp.asOutbound and warp.asAmneziaWg share one WARP key and would knock each other off; enable one"
+ )
+ # Daemon configs are readable by the service group; users must not share it.
+ (mkAssertion (cfg.userControl.group != derived.constants.serviceUser)
+ "proxy-suite: userControl.group must not be ${derived.constants.serviceUser}, the group that can read backend configs"
+ )
(requireEnabled derived.warpOutboundEnabled proxyEnabled
"proxy-suite: warp.asOutbound requires proxy.enable = true"
)
diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix
index 03a0b57..5d6e48b 100644
--- a/modules/proxy-suite/service/default.nix
+++ b/modules/proxy-suite/service/default.nix
@@ -134,6 +134,15 @@ let
in
lib.mkMerge [
autoProxyUnits
+ {
+ # See constants.serviceUser.
+ users.users.${constants.serviceUser} = {
+ isSystemUser = true;
+ group = constants.serviceUser;
+ description = "proxy-suite daemons";
+ };
+ users.groups.${constants.serviceUser} = { };
+ }
{
environment.systemPackages = [
control.proxyCtl
diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix
index 8686925..5b9f7bb 100644
--- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix
+++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix
@@ -29,6 +29,8 @@ let
subscriptionsFile = "${runtimeDir}/subscriptions.json";
subsCfg = proxyInboundsCfg.subscriptions;
xray = "${proxyInboundsCfg.package}/bin/xray";
+ # Only listeners: no marks, no transparent sockets.
+ runXray = constants.runAsServiceUser pkgs [ "net_bind_service" ];
needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled;
@@ -144,13 +146,39 @@ let
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
= [{user:$user,pass:$password}]
else . end' \
- ${proxyInboundsFile} > "$RUNTIME_DIR/config.json"
- chmod 600 "$RUNTIME_DIR/config.json"
+ ${proxyInboundsFile} > "$RUNTIME_DIR/config.json.tmp"
+
+ # XRay runs as ${constants.serviceUser}. A certificate or key it cannot read (an ACME
+ # key, say) is copied in, which means a renewal needs a restart; give the user read
+ # access to keep XRay's own reload.
+ CERT_DIR="$RUNTIME_DIR/tls"
+ rm -rf "$CERT_DIR"
+ index=0
+ while IFS= read -r source; do
+ [ -n "$source" ] || continue
+ if ! ${runXray} ${pkgs.coreutils}/bin/test -r "$source"; then
+ [ -d "$CERT_DIR" ] || install -d -m 0750 -g ${constants.serviceUser} "$CERT_DIR"
+ index=$((index + 1))
+ copy="$CERT_DIR/$index-$(basename "$source")"
+ install -m 0640 -g ${constants.serviceUser} "$source" "$copy"
+ echo "proxy-suite: ${constants.serviceUser} cannot read $source; XRay uses a copy until the next restart" >&2
+ ${jq} --arg from "$source" --arg to "$copy" '
+ (.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile)
+ | select(. == $from)) = $to
+ ' "$RUNTIME_DIR/config.json.tmp" > "$RUNTIME_DIR/config.json.next"
+ mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json.tmp"
+ fi
+ done < <(${jq} -r '[.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile) | strings]
+ | unique[]' "$RUNTIME_DIR/config.json.tmp")
+
+ ${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"
+ chmod 640 "$RUNTIME_DIR/config.json.tmp"
+ mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json"
${writeLinksBlock}
${writeSubscriptionsBlock}
- exec ${xray} run -c "$RUNTIME_DIR/config.json"
+ exec ${runXray} ${xray} run -c "$RUNTIME_DIR/config.json"
'';
# Adds XRay's per-user counters to the daily totals, read and reset in one call.
diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix
index 33e640e..e2ea69d 100644
--- a/modules/proxy-suite/service/script-blocks/outbounds.nix
+++ b/modules/proxy-suite/service/script-blocks/outbounds.nix
@@ -5,6 +5,7 @@
proxyCfg,
sshProxyCfg,
warpCfg,
+ constants,
pureXrayEnabled,
hybridEnabled,
collapseNamedOutbounds,
@@ -305,9 +306,6 @@ let
server_port = sshProxyCfg.server.port;
user = sshProxyCfg.server.user;
}
- // lib.optionalAttrs (sshProxyCfg.identityFile != null) {
- private_key_path = sshProxyCfg.identityFile;
- }
// lib.optionalAttrs (sshProxyCfg.hostKey != [ ]) {
host_key = sshProxyCfg.hostKey;
}
@@ -355,6 +353,13 @@ let
''
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
+ ${lib.optionalString (!pureXrayEnabled && sshProxyCfg.identityFile != null) ''
+ # sing-box opens the key as ${constants.serviceUser}, which cannot read a key in a
+ # home directory: it gets a copy only root and its group can read.
+ SSH_IDENTITY="$RUNTIME_DIR/ssh-identity"
+ install -m 0640 -g ${constants.serviceUser} ${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY"
+ OB_JSON=$(${jq} --arg key "$SSH_IDENTITY" '.private_key_path = $key' <<< "$OB_JSON")
+ ''}
${hostKeyFileBlock}
${
if hybridEnabled then
diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix
index a3a31c3..4e90c26 100644
--- a/modules/proxy-suite/service/scripts.nix
+++ b/modules/proxy-suite/service/scripts.nix
@@ -111,6 +111,7 @@ let
proxyCfg
sshProxyCfg
warpCfg
+ constants
pureXrayEnabled
hybridEnabled
collapseNamedOutbounds
diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix
index 3bf3996..805433d 100644
--- a/modules/proxy-suite/service/start-scripts.nix
+++ b/modules/proxy-suite/service/start-scripts.nix
@@ -40,6 +40,7 @@ let
;
autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; };
+ runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
routeModeBlacklistTail =
if pureXrayEnabled then
@@ -205,7 +206,8 @@ let
AUTOPROXY_RULES_JSON='[]'
${lib.optionalString enableAutoProxy ''
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
- install -d -m 0750 "$AUTOPROXY_DIR"
+ # 0751: sing-box, running as ${constants.serviceUser}, reads the rule-sets inside.
+ install -d -m 0751 "$AUTOPROXY_DIR"
[ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json"
# direct is always exit 0; state is keyed by tag, so shifting indices are
@@ -312,6 +314,7 @@ let
CUTOFF_RULE_SET=${lib.escapeShellArg "${constants.zapret2CutoffDir}/proxy.json"}
install -d -m 0755 "$(dirname "$CUTOFF_RULE_SET")"
[ -s "$CUTOFF_RULE_SET" ] || echo '{"version":1,"rules":[]}' > "$CUTOFF_RULE_SET"
+ chmod 644 "$CUTOFF_RULE_SET"
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$CUTOFF_RULE_SET" \
'. + [{type: "local", format: "source", tag: "zapret-cutoff", path: $p}]' <<< "$AUTOPROXY_RULE_SETS_JSON")
AUTOPROXY_RULES_JSON=$(${jq} -c '. + [{rule_set: ["zapret-cutoff"], outbound: "proxy"}]' <<< "$AUTOPROXY_RULES_JSON")
@@ -340,9 +343,12 @@ let
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
-f "$BACKEND_JQ_FILTER" \
"${configFile}" > "$RUNTIME_DIR/config.json"
- ${lib.optionalString enableLocalProxyAuth ''
- chmod 600 "$RUNTIME_DIR/config.json"
- ''}
+ # The backend runs as ${constants.serviceUser}: its configs are group-readable.
+ for backend_config in "$RUNTIME_DIR/config.json" "$RUNTIME_DIR/xray-sidecar.json"; do
+ [ -e "$backend_config" ] || continue
+ ${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$backend_config"
+ chmod ${if enableLocalProxyAuth then "640" else "g+r"} "$backend_config"
+ done
${
if hybridEnabled then
@@ -358,7 +364,7 @@ let
trap _proxy_suite_cleanup_xray_sidecar EXIT
trap 'exit 143' INT TERM
- ${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" &
+ ${runBackend} ${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" &
XRAY_SIDECAR_PID="$!"
${pkgs.coreutils}/bin/sleep 0.2
if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then
@@ -367,7 +373,7 @@ let
exit "$XRAY_SIDECAR_STATUS"
fi
- ${singBox} run -c "$RUNTIME_DIR/config.json" &
+ ${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json" &
SING_BOX_PID="$!"
# Either one going away breaks the outbounds: exit, and let systemd restart both.
SING_BOX_STATUS=0
@@ -375,11 +381,11 @@ let
exit "$(( SING_BOX_STATUS == 0 ? 1 : SING_BOX_STATUS ))"
fi
- exec ${singBox} run -c "$RUNTIME_DIR/config.json"
+ exec ${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json"
''
else
''
- exec ${backendBin} run -c "$RUNTIME_DIR/config.json"
+ exec ${runBackend} ${backendBin} run -c "$RUNTIME_DIR/config.json"
''
}
'';
diff --git a/modules/proxy-suite/ssh-proxy.nix b/modules/proxy-suite/ssh-proxy.nix
index 0bbe746..4be1eeb 100644
--- a/modules/proxy-suite/ssh-proxy.nix
+++ b/modules/proxy-suite/ssh-proxy.nix
@@ -3,12 +3,22 @@
lib,
pkgs,
cfg,
+ derived,
}:
let
s = cfg.sshProxy;
+ inherit (derived.constants) serviceUser unprivilegedServiceConfig;
destination = if s.server.user == null then s.server.host else "${s.server.user}@${s.server.host}";
extraArgs = lib.concatMapStrings (arg: " args+=(${lib.escapeShellArg arg})\n") s.extraArgs;
+ # The service user's home is /var/empty: accepted host keys are kept in the state dir.
+ knownHosts =
+ if s.knownHostsFile != null then
+ ''"$CREDENTIALS_DIRECTORY/known_hosts"''
+ else if s.serviceUser == serviceUser then
+ ''"$STATE_DIRECTORY/known_hosts"''
+ else
+ null;
startScript = pkgs.writeShellScript "proxy-suite-ssh-proxy" ''
set -euo pipefail
@@ -23,10 +33,8 @@ let
-D ${lib.escapeShellArg "${s.listener.address}:${toString s.listener.port}"}
)
${lib.optionalString (s.server.port != 22) "args+=(-p ${toString s.server.port})"}
- ${lib.optionalString (s.identityFile != null) "args+=(-i ${lib.escapeShellArg s.identityFile})"}
- ${lib.optionalString (
- s.knownHostsFile != null
- ) "args+=(-o ${lib.escapeShellArg "UserKnownHostsFile=${s.knownHostsFile}"})"}
+ ${lib.optionalString (s.identityFile != null) ''args+=(-i "$CREDENTIALS_DIRECTORY/identity")''}
+ ${lib.optionalString (knownHosts != null) ''args+=(-o UserKnownHostsFile=${knownHosts})''}
${extraArgs}
exec ${pkgs.openssh}/bin/ssh "''${args[@]}" ${lib.escapeShellArg destination}
'';
@@ -40,17 +48,25 @@ in
# Restart=always plus a server that refuses connections would otherwise hit
# the default 5-starts-in-10s limit and stay failed.
startLimitIntervalSec = 0;
- serviceConfig = {
- ExecStart = startScript;
- # `ssh -N` exits 0 when the server closes the connection cleanly, which
- # under on-failure left the tunnel down for good.
- Restart = "always";
- RestartSec = 5;
- # One fd per forwarded channel; the 1024 default is low for a relay.
- LimitNOFILE = 65536;
- }
- // lib.optionalAttrs (s.serviceUser != null) {
- User = s.serviceUser;
- };
+ serviceConfig =
+ lib.optionalAttrs (s.serviceUser == serviceUser) (unprivilegedServiceConfig [ "net_bind_service" ])
+ // {
+ ExecStart = startScript;
+ # Copies the service user can read, whoever owns the originals.
+ LoadCredential =
+ lib.optional (s.identityFile != null) "identity:${s.identityFile}"
+ ++ lib.optional (s.knownHostsFile != null) "known_hosts:${s.knownHostsFile}";
+ StateDirectory = "proxy-suite/ssh";
+ StateDirectoryMode = "0700";
+ # `ssh -N` exits 0 when the server closes the connection cleanly, which
+ # under on-failure left the tunnel down for good.
+ Restart = "always";
+ RestartSec = 5;
+ # One fd per forwarded channel; the 1024 default is low for a relay.
+ LimitNOFILE = 65536;
+ }
+ // lib.optionalAttrs (s.serviceUser != null && s.serviceUser != serviceUser) {
+ User = s.serviceUser;
+ };
};
}
diff --git a/modules/proxy-suite/tg-ws-proxy.nix b/modules/proxy-suite/tg-ws-proxy.nix
index 5a1f797..dd2ad6a 100644
--- a/modules/proxy-suite/tg-ws-proxy.nix
+++ b/modules/proxy-suite/tg-ws-proxy.nix
@@ -4,6 +4,7 @@
pkgs,
packages,
cfg,
+ derived,
}:
let
@@ -84,20 +85,32 @@ let
'';
in
{
- systemd.services.proxy-suite-tg-ws-proxy = {
+ # For the checks: ExecStartPre/ExecStopPost carry these behind "+".
+ inherit bypassUpScript bypassDownScript;
+
+ config.systemd.services.proxy-suite-tg-ws-proxy = {
description = "Telegram MTProto WebSocket proxy";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
- serviceConfig = {
- ExecStart = startScript;
- LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
- Restart = "on-failure";
- RestartSec = 5;
- }
- // lib.optionalAttrs transparentBypassEnabled {
- ExecStartPre = bypassUpScript;
- ExecStopPost = bypassDownScript;
- };
+ serviceConfig =
+ derived.constants.unprivilegedServiceConfig [
+ "net_bind_service"
+ ]
+ // {
+ ExecStart = startScript;
+ LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
+ Restart = "on-failure";
+ RestartSec = 5;
+ }
+ // lib.optionalAttrs (t.log.file != null) {
+ # A writable home for log.file.
+ LogsDirectory = "proxy-suite-tg-ws-proxy";
+ }
+ // lib.optionalAttrs transparentBypassEnabled {
+ # Policy routing and nftables: privileged.
+ ExecStartPre = "+${bypassUpScript}";
+ ExecStopPost = "+${bypassDownScript}";
+ };
};
}
diff --git a/modules/proxy-suite/warp.nix b/modules/proxy-suite/warp.nix
index 478ac2c..86ad16e 100644
--- a/modules/proxy-suite/warp.nix
+++ b/modules/proxy-suite/warp.nix
@@ -9,6 +9,7 @@
let
w = derived.warpCfg;
+ inherit (derived.constants) serviceUser runAsServiceUser unprivilegedServiceConfig;
listener = cfg.proxy.listener;
auth = listener.auth;
scriptsDir = builtins.path {
@@ -33,9 +34,10 @@ let
pkgs.writeText "proxy-suite-warp" auth.password
else
null;
- userinfo = lib.optionalString (auth.username != null && passwordSource != null) ''
+ withProxyAuth = auth.username != null && passwordSource != null;
+ userinfo = lib.optionalString withProxyAuth ''
userinfo=$(${pkgs.jq}/bin/jq -rn --arg u ${lib.escapeShellArg auth.username} \
- --rawfile p ${lib.escapeShellArg passwordSource} '"\($u | @uri):\($p | rtrimstr("\n") | @uri)@"')
+ --rawfile p "$CREDENTIALS_DIRECTORY/proxy-password" '"\($u | @uri):\($p | rtrimstr("\n") | @uri)@"')
'';
registerScript = pkgs.writeShellScript "proxy-suite-warp" ''
@@ -49,18 +51,22 @@ let
${lib.optionalString (w.generatorUrl != null) ''
# Fallback: a third-party generator registers from abroad and hands the profile back.
+ # curl follows HTTPS_PROXY when it is set.
generate() {
- body=$(${pkgs.curl}/bin/curl --noproxy '*' -fsS --max-time 60 -A proxy-suite \
+ body=$(${pkgs.curl}/bin/curl -fsS --max-time 60 -A proxy-suite \
${lib.escapeShellArg w.generatorUrl}) || return 1
case "$body" in
"[Interface]"*) printf '%s\n' "$body" ;;
*) ${pkgs.jq}/bin/jq -er '.content | @base64d' <<< "$body" ;;
- esac > wgcf-profile.conf.tmp || return 1
- grep -q '^PrivateKey' wgcf-profile.conf.tmp || return 1
+ esac > wgcf-profile.conf.tmp || { rm -f wgcf-profile.conf.tmp; return 1; }
+ grep -q '^PrivateKey' wgcf-profile.conf.tmp || { rm -f wgcf-profile.conf.tmp; return 1; }
mv wgcf-profile.conf.tmp wgcf-profile.conf
}
''}
${
+ let
+ fallbacks = lib.optionalString (w.generatorUrl != null) " || generate";
+ in
if cfg.proxy.enable then
''
# The API is blocked in some countries, so the local proxy goes first. It may
@@ -71,12 +77,15 @@ let
done
userinfo=
${userinfo}
- HTTPS_PROXY="socks5://''${userinfo}${hostPart}:${toString listener.port}" register || register${
- lib.optionalString (w.generatorUrl != null) " || generate"
+ proxied() {
+ HTTPS_PROXY="socks5://''${userinfo}${hostPart}:${toString listener.port}" "$@"
+ }
+ proxied register || register${fallbacks}${
+ lib.optionalString (w.generatorUrl != null) " || proxied generate"
}
''
else
- "register${lib.optionalString (w.generatorUrl != null) " || generate"}"
+ "register${fallbacks}"
}
'';
@@ -88,10 +97,50 @@ let
server = cfg.proxy.dns.local.address;
server_port = cfg.proxy.dns.local.port;
};
+ mark = cfg.proxy.tproxy.proxyMark;
+ probe = port: url: ''
+ ${pkgs.curl}/bin/curl -s --noproxy "" -x socks5h://127.0.0.1:${toString port} -m "$timeout" \
+ -o /dev/null ${url}'';
# Some lines drop a share of fresh WARP handshakes for good, and sing-box retries on the
- # same source port forever. A new process binds a new port, so the probe exits after
- # repeated failures and systemd starts the tunnel again.
+ # same source port forever. A new process binds a new port, so the watchdog exits when
+ # WARP stops answering and systemd starts the tunnel again. A healthy WARP handshake takes
+ # a fraction of a second, so a start gets 15 seconds; a running tunnel gets three misses.
+ # The "direct-in" listener reaches Cloudflare through the uplink with the backend's mark (not
+ # urlTest.url, which is picked to be blocked here): when that fails too, WARP could not work
+ # from a new port either.
+ watchdogScript = pkgs.writeShellScript "proxy-suite-warp" ''
+ set -uo pipefail
+ ${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json" &
+ singbox=$!
+
+ healthy=0
+ failures=0
+ uplink_down=0
+ since=0
+ while sleep $(( healthy ? 10 : 2 )); do
+ kill -0 "$singbox" 2>/dev/null || { wait "$singbox"; exit 1; }
+ timeout=$(( healthy ? 10 : 4 ))
+ if ${probe w.tunnelPort "-f ${lib.escapeShellArg cfg.proxy.urlTest.url}"}; then
+ (( healthy )) || echo "proxy-suite: WARP is answering" >&2
+ healthy=1 failures=0 uplink_down=0
+ continue
+ fi
+ if ! ${probe w.directPort "https://1.1.1.1/cdn-cgi/trace"}; then
+ (( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging WARP" >&2
+ uplink_down=1 failures=0 since=$SECONDS
+ continue
+ fi
+ uplink_down=0
+ if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then
+ echo "proxy-suite: WARP is not answering; restarting the tunnel on a new source port" >&2
+ kill "$singbox"
+ wait "$singbox"
+ exit 1
+ fi
+ done
+ '';
+
tunnelScript = pkgs.writeShellScript "proxy-suite-warp" ''
set -euo pipefail
profile=${lib.escapeShellArg w.profilePath}
@@ -100,29 +149,27 @@ let
until [ -s "$profile" ]; do sleep 5; done
fi
- # The profile is a secret, so it is converted here rather than baked into the store.
- endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag warp --routing-mark ${toString cfg.proxy.tproxy.proxyMark} < "$profile")
- ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{
+ # The profile is a secret, so it is converted here, as root, rather than baked into
+ # the store; sing-box itself runs as ${serviceUser}.
+ endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag warp --routing-mark ${toString mark} < "$profile")
+ (umask 027 && ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{
log: {level: "warn"},
dns: {servers: [${builtins.toJSON dnsServer}]},
- route: {default_domain_resolver: "local", final: "warp"},
- inbounds: [{type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString w.tunnelPort}}],
+ route: {
+ default_domain_resolver: "local",
+ rules: [{inbound: ["direct-in"], outbound: "direct"}],
+ final: "warp"
+ },
+ inbounds: [
+ {type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString w.tunnelPort}},
+ {type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString w.directPort}}
+ ],
+ outbounds: [{type: "direct", tag: "direct", routing_mark: ${toString mark}}],
endpoints: [$ep]
- }' > "$RUNTIME_DIRECTORY/config.json"
+ }' > "$RUNTIME_DIRECTORY/config.json")
+ ${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/config.json"
- ${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json" &
- singbox=$!
-
- failures=0
- while sleep 10; do
- kill -0 "$singbox" 2>/dev/null || { wait "$singbox"; exit 1; }
- if ${pkgs.curl}/bin/curl -sf --noproxy "" -x socks5h://127.0.0.1:${toString w.tunnelPort} -m 10 -o /dev/null ${lib.escapeShellArg cfg.proxy.urlTest.url}; then
- failures=0
- elif (( ++failures >= 3 )); then
- echo "proxy-suite: WARP stopped answering; restarting the tunnel on a new source port" >&2
- exit 1
- fi
- done
+ exec ${runAsServiceUser pkgs [ "net_admin" ]} ${watchdogScript}
'';
in
{
@@ -145,7 +192,7 @@ in
Restart = "always";
RestartSec = 2;
RuntimeDirectory = "proxy-suite-warp-tunnel";
- RuntimeDirectoryMode = "0700";
+ RuntimeDirectoryMode = "0750";
UMask = "0077";
};
};
@@ -161,7 +208,7 @@ in
# Retried until it registers. Not a oneshot: a slow or failed registration must not
# hold up or fail a switch.
startLimitIntervalSec = 0;
- serviceConfig = {
+ serviceConfig = unprivilegedServiceConfig [ ] // {
Type = "simple";
RemainAfterExit = true;
Restart = "on-failure";
@@ -170,6 +217,7 @@ in
StateDirectoryMode = "0700";
WorkingDirectory = "/var/lib/proxy-suite/warp";
UMask = "0077";
+ LoadCredential = lib.optional (cfg.proxy.enable && withProxyAuth) "proxy-password:${passwordSource}";
ExecStart = registerScript;
};
};
diff --git a/nix/checks/amnezia-wg.nix b/nix/checks/amnezia-wg.nix
index 68daa8e..f7fb7e6 100644
--- a/nix/checks/amnezia-wg.nix
+++ b/nix/checks/amnezia-wg.nix
@@ -70,6 +70,9 @@ let
homeService = awgOnly.config.systemd.services.proxy-suite-awg-home;
workService = awgOnly.config.systemd.services.proxy-suite-awg-work;
ctl = mkProxyCtlDerived awgOnly;
+ homeWatchdog = awgOnly.config.systemd.services.proxy-suite-awg-home-watchdog;
+ homeWatchdogScript = generated.readDerivation homeWatchdog.serviceConfig.ExecStart;
+ homeStart = generated.readDerivation homeService.serviceConfig.ExecStart;
sourceFixture = evalProxySuite [
{
@@ -190,6 +193,12 @@ in
assert homeService.serviceConfig.NoNewPrivileges;
assert builtins.length 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;
+ assert pkgs.lib.hasInfix "--inspect" homeStart;
+ assert homeWatchdog.bindsTo == [ "proxy-suite-awg-home.service" ];
+ assert homeWatchdog.wantedBy == [ "proxy-suite-awg-home.service" ];
+ assert pkgs.lib.hasInfix "rekey + 10" homeWatchdogScript;
true
)
(
diff --git a/nix/checks/local-proxy-auth.nix b/nix/checks/local-proxy-auth.nix
index 7a18300..dbdb180 100644
--- a/nix/checks/local-proxy-auth.nix
+++ b/nix/checks/local-proxy-auth.nix
@@ -104,7 +104,11 @@ in
assert pkgs.lib.hasInfix ''--arg password "$LOCAL_PROXY_PASSWORD"'' localProxyAuthStartScript;
assert pkgs.lib.hasInfix ''select(.type == "mixed" and .tag == "mixed-in") | .users''
localProxyAuthBackendJqFilter;
- assert pkgs.lib.hasInfix ''chmod 600 "$RUNTIME_DIR/config.json"'' localProxyAuthStartScript;
+ # The password is in the config: root and the backend's group only.
+ assert pkgs.lib.hasInfix ''chgrp proxy-suite-daemon "$backend_config"'' localProxyAuthStartScript;
+ assert pkgs.lib.hasInfix ''chmod 640 "$backend_config"'' localProxyAuthStartScript;
+ # The backend itself runs unprivileged.
+ assert pkgs.lib.hasInfix "setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon" localProxyAuthStartScript;
true
)
diff --git a/nix/checks/ssh-proxy.nix b/nix/checks/ssh-proxy.nix
index f1898f7..a774927 100644
--- a/nix/checks/ssh-proxy.nix
+++ b/nix/checks/ssh-proxy.nix
@@ -53,7 +53,6 @@ let
server = "ssh.example.com";
server_port = 22;
user = "root";
- private_key_path = "/run/secrets/ssh-key";
host_key = [ testHostKey ];
routing_mark = markOf sshNativeSingBox;
};
@@ -367,6 +366,9 @@ let
)
(
assert pkgs.lib.hasInfix expectedNativeSingBoxOutbound sshNativeSingBoxStart;
+ # The daemon cannot read the key where it lives: it gets a group-readable copy.
+ assert pkgs.lib.hasInfix "install -m 0640 -g proxy-suite-daemon /run/secrets/ssh-key \"$SSH_IDENTITY\"" sshNativeSingBoxStart;
+ assert pkgs.lib.hasInfix "'.private_key_path = $key'" sshNativeSingBoxStart;
true
)
# The global local-resolve route rule is gone; the native outbound resolves.
@@ -441,7 +443,16 @@ let
true
)
(
- assert pkgs.lib.hasInfix "UserKnownHostsFile=/run/secrets/ssh-known-hosts" standaloneStartScript;
+ assert pkgs.lib.hasInfix ''UserKnownHostsFile="$CREDENTIALS_DIRECTORY/known_hosts"'' standaloneStartScript;
+ true
+ )
+ # Secrets reach the unprivileged user as credentials.
+ (
+ assert
+ standaloneService.serviceConfig.LoadCredential == [
+ "identity:/run/secrets/ssh-key"
+ "known_hosts:/run/secrets/ssh-known-hosts"
+ ];
true
)
diff --git a/nix/checks/tg-ws-proxy.nix b/nix/checks/tg-ws-proxy.nix
index 51ccbae..e0e55f4 100644
--- a/nix/checks/tg-ws-proxy.nix
+++ b/nix/checks/tg-ws-proxy.nix
@@ -30,6 +30,7 @@ let
tgWithGlobalTunServiceConfig
tgWithGlobalTunBypassUp
tgWithGlobalTunBypassDown
+ tgWithGlobalTunModule
tgWithGlobalTunRules
tgWithGlobalTproxyNft
invalidTgWsProxyAssertions
@@ -81,6 +82,10 @@ in
# Global TUN/TProxy bypass mark keeps relay traffic out of transparent capture.
(
assert !(tgWithGlobalTunServiceConfig ? SocketMark);
+ # The relay runs as the service user; only the bypass scripts are privileged.
+ assert tgWithGlobalTunServiceConfig.User == "proxy-suite-daemon";
+ assert tgWithGlobalTunServiceConfig.ExecStartPre == "+${tgWithGlobalTunModule.bypassUpScript}";
+ assert tgWithGlobalTunServiceConfig.ExecStopPost == "+${tgWithGlobalTunModule.bypassDownScript}";
assert pkgs.lib.hasInfix "\"system.slice/proxy-suite-tg-ws-proxy.service\" meta mark set 4" tgWithGlobalTunBypassUp;
assert pkgs.lib.hasInfix "delete table inet proxy_suite_tg_ws_proxy" tgWithGlobalTunBypassDown;
assert pkgs.lib.hasInfix "rule add pref 8999 fwmark 4 lookup main" tgWithGlobalTunBypassUp;
diff --git a/nix/checks/tg-ws-proxy/fixtures.nix b/nix/checks/tg-ws-proxy/fixtures.nix
index a0ae4d0..fb0b057 100644
--- a/nix/checks/tg-ws-proxy/fixtures.nix
+++ b/nix/checks/tg-ws-proxy/fixtures.nix
@@ -66,8 +66,19 @@ let
];
tgWithGlobalTunServiceConfig =
tgWithGlobalTun.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig;
- tgWithGlobalTunBypassUp = generated.readDerivation tgWithGlobalTunServiceConfig.ExecStartPre;
- tgWithGlobalTunBypassDown = generated.readDerivation tgWithGlobalTunServiceConfig.ExecStopPost;
+ tgWithGlobalTunModule =
+ let
+ inherit (tgWithGlobalTun) pkgs;
+ cfg = tgWithGlobalTun.config.services.proxy-suite;
+ in
+ import ../../../modules/proxy-suite/tg-ws-proxy.nix {
+ inherit (pkgs) lib;
+ inherit pkgs cfg;
+ packages = import ../../../pkgs/default.nix { inherit pkgs; };
+ derived = import ../../../modules/proxy-suite/derived.nix { inherit (pkgs) lib; inherit cfg; };
+ };
+ tgWithGlobalTunBypassUp = generated.readDerivation tgWithGlobalTunModule.bypassUpScript;
+ tgWithGlobalTunBypassDown = generated.readDerivation tgWithGlobalTunModule.bypassDownScript;
tgWithGlobalTunRules = mkRoutingRules tgWithGlobalTun;
tgWithGlobalTproxy = evalProxySuite [
@@ -134,6 +145,7 @@ in
tgWithGlobalTunServiceConfig
tgWithGlobalTunBypassUp
tgWithGlobalTunBypassDown
+ tgWithGlobalTunModule
tgWithGlobalTunRules
tgWithGlobalTproxyNft
invalidTgWsProxyAssertions
diff --git a/nix/checks/warp.nix b/nix/checks/warp.nix
index 5151bbd..90f89da 100644
--- a/nix/checks/warp.nix
+++ b/nix/checks/warp.nix
@@ -109,6 +109,18 @@ let
asAmneziaWg = true;
};
}
+ # Both modes at once: two sessions on one WARP key.
+ {
+ enable = true;
+ amneziaWg.enable = true;
+ warp = {
+ enable = true;
+ configFile = profile;
+ asOutbound = true;
+ asAmneziaWg = true;
+ };
+ proxy.enable = true;
+ }
# Tag collision with a declared outbound.
{
enable = true;
@@ -203,6 +215,23 @@ in
&& !(hasInfix "generate()" autoRegister);
true
)
+ # Registration runs as the service user; the generator is tried through the proxy last.
+ (
+ assert
+ auto.config.systemd.services."proxy-suite-warp".serviceConfig.User == "proxy-suite-daemon"
+ && hasInfix "register || register || generate || proxied generate" generatorRegister;
+ true
+ )
+ # sing-box runs as the service user with only net_admin, under a watchdog that can tell a
+ # dead uplink (the marked direct-in listener) from a silent WARP.
+ (
+ assert
+ hasInfix "--reuid=proxy-suite-daemon" singBoxTunnel
+ && hasInfix "--ambient-caps=-all,+net_admin --bounding-set" singBoxTunnel
+ && hasInfix ''{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: 18539}'' singBoxTunnel
+ && hasInfix ''{type: "direct", tag: "direct", routing_mark: ${markOf singBox}}'' singBoxTunnel;
+ true
+ )
(
assert amneziaWg.config.services.proxy-suite.amneziaWg.profiles.warp.configFile == profile;
true
diff --git a/scripts/amneziawg_config.py b/scripts/amneziawg_config.py
index 21bf9c7..8eda655 100644
--- a/scripts/amneziawg_config.py
+++ b/scripts/amneziawg_config.py
@@ -284,17 +284,38 @@ def _set_interface_value(config: str, key: str, value: str) -> str:
return "\n".join(lines) + "\n"
-def _interface_keys(config: str) -> set[str]:
- keys: set[str] = set()
- in_interface = False
+def conf_sections(config: str) -> list[tuple[str, list[tuple[str, str]]]]:
+ """Each [Section] of a WireGuard .conf, lowercased, with its key = value lines in order.
+
+ Keys are lowercased; comments (# or ;) and lines outside a section are dropped.
+ """
+ sections: list[tuple[str, list[tuple[str, str]]]] = []
for line in config.splitlines():
stripped = line.split("#", 1)[0].split(";", 1)[0].strip()
if stripped.startswith("[") and stripped.endswith("]"):
- in_interface = stripped.lower() == "[interface]"
- continue
- if in_interface and "=" in stripped:
- key = stripped.split("=", 1)[0].strip()
- keys.add(re.sub(r"[^a-z0-9]", "", key.lower()))
+ sections.append((stripped[1:-1].strip().lower(), []))
+ elif "=" in stripped and sections:
+ key, value = (part.strip() for part in stripped.split("=", 1))
+ sections[-1][1].append((key.lower(), value))
+ return sections
+
+
+def section_values(config: str, section: str, key: str) -> list[str]:
+ """Every value of `key` in every `section`, in file order."""
+ return [
+ value
+ for name, pairs in conf_sections(config)
+ if name == section
+ for found, value in pairs
+ if found == key
+ ]
+
+
+def _interface_keys(config: str) -> set[str]:
+ keys: set[str] = set()
+ for name, pairs in conf_sections(config):
+ if name == "interface":
+ keys.update(re.sub(r"[^a-z0-9]", "", key) for key, _ in pairs)
return keys
@@ -443,39 +464,15 @@ def render_settings(settings: dict[str, Any]) -> str:
lines.append(f"{target} = {settings[source]}")
obfuscation = _merge_obfuscation(settings)
- obfuscation_map = {
- "jc": "Jc",
- "jmin": "Jmin",
- "jmax": "Jmax",
- "s1": "S1",
- "s2": "S2",
- "s3": "S3",
- "s4": "S4",
- "h1": "H1",
- "h2": "H2",
- "h3": "H3",
- "h4": "H4",
- "i1": "I1",
- "i2": "I2",
- "i3": "I3",
- "i4": "I4",
- "i5": "I5",
- "contentPaddingAddition": "ContentPaddingAddition",
- "rekeyAfterTime": "RekeyAfterTime",
- "rekeyTimeout": "RekeyTimeout",
- "rejectAfterTime": "RejectAfterTime",
- "keepaliveTimeout": "KeepaliveTimeout",
- "maxHandshakeAttempts": "MaxHandshakeAttempts",
- }
- for source, target in obfuscation_map.items():
- if obfuscation.get(source) is not None:
- lines.append(f"{target} = {obfuscation[source]}")
- for source, target in {
- "randomTrailers": "RandomTrailers",
- "disableCookies": "DisableCookies",
- }.items():
- if obfuscation.get(source) is not None:
- lines.append(f"{target} = {'on' if obfuscation[source] else 'off'}")
+ # Option names are the config keys in camelCase; the key comes last, from its secret.
+ values = {key.lower(): value for key, value in obfuscation.items()}
+ for normalized, target in VPN_INTERFACE_FIELDS.items():
+ value = values.get(normalized)
+ if normalized == "headerprotectionkey" or value is None:
+ continue
+ if isinstance(value, bool):
+ value = "on" if value else "off"
+ lines.append(f"{target} = {value}")
if obfuscation.get("headerProtectionKey") is not None or obfuscation.get(
"headerProtectionKeyFile"
) is not None:
@@ -531,17 +528,7 @@ def validate_config(config: str, allow_hooks: bool = False) -> None:
def probe_address(config: str) -> str:
"""Return an address covered by a peer route without exposing credentials."""
networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network] = []
- in_peer = False
- for line in config.splitlines():
- stripped = line.split("#", 1)[0].split(";", 1)[0].strip()
- if stripped.startswith("[") and stripped.endswith("]"):
- in_peer = stripped.lower() == "[peer]"
- continue
- if not in_peer or "=" not in stripped:
- continue
- key, value = (part.strip() for part in stripped.split("=", 1))
- if key.lower() != "allowedips":
- continue
+ for value in section_values(config, "peer", "allowedips"):
for item in value.split(","):
try:
networks.append(ipaddress.ip_network(item.strip(), strict=False))
@@ -561,25 +548,26 @@ def probe_address(config: str) -> str:
def transport_implementation(config: str) -> str:
"""Select userspace for the upstream RandomTrailers/ranged-header defect."""
- random_trailers = False
- ranged_handshake_header = False
- in_interface = False
- for line in config.splitlines():
- stripped = line.split("#", 1)[0].split(";", 1)[0].strip()
- if stripped.startswith("[") and stripped.endswith("]"):
- in_interface = stripped.lower() == "[interface]"
- continue
- if not in_interface or "=" not in stripped:
- continue
- key, value = (part.strip() for part in stripped.split("=", 1))
- normalized_key = key.lower()
- if normalized_key == "randomtrailers":
- random_trailers = value.lower() in {"on", "true", "yes", "1"}
- elif normalized_key in {"h1", "h2", "h3"}:
- ranged_handshake_header |= re.fullmatch(r"[0-9]+\s*-\s*[0-9]+", value) is not None
+ trailers = section_values(config, "interface", "randomtrailers")
+ random_trailers = bool(trailers) and trailers[-1].lower() in {"on", "true", "yes", "1"}
+ ranged_handshake_header = any(
+ re.fullmatch(r"[0-9]+\s*-\s*[0-9]+", value) is not None
+ for key in ("h1", "h2", "h3")
+ for value in section_values(config, "interface", key)
+ )
return "userspace" if random_trailers and ranged_handshake_header else "auto"
+def rekey_after_time(config: str) -> int:
+ """Longest wait between rekeys, in seconds; 0 when rekeying is off."""
+ values = section_values(config, "interface", "rekeyaftertime")
+ if not values:
+ return 120
+ if values[-1] == "(off)":
+ return 0
+ return int(values[-1].split("-")[-1])
+
+
def prepare(manifest: dict[str, Any]) -> str:
kind = manifest.get("kind")
if kind == "configFile":
@@ -619,25 +607,18 @@ def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest")
parser.add_argument("--output")
- parser.add_argument("--probe-address")
- parser.add_argument("--transport-implementation")
+ parser.add_argument(
+ "--inspect",
+ metavar="CONFIG",
+ help="print the transport implementation, a probe address and the rekey interval",
+ )
args = parser.parse_args()
try:
- if args.probe_address is not None:
- if (
- args.manifest is not None
- or args.output is not None
- or args.transport_implementation is not None
- ):
- raise ConfigError("--probe-address cannot be combined with rendering options")
- print(probe_address(_read_limited(args.probe_address)))
- return 0
- if args.transport_implementation is not None:
+ if args.inspect is not None:
if args.manifest is not None or args.output is not None:
- raise ConfigError(
- "--transport-implementation cannot be combined with rendering options"
- )
- print(transport_implementation(_read_limited(args.transport_implementation)))
+ raise ConfigError("--inspect cannot be combined with rendering options")
+ config = _read_limited(args.inspect)
+ print(transport_implementation(config), probe_address(config), rekey_after_time(config))
return 0
if args.manifest is None or args.output is None:
raise ConfigError("--manifest and --output are required when rendering a configuration")
diff --git a/scripts/test-amneziawg-config.py b/scripts/test-amneziawg-config.py
index 00c36c2..6cfca8f 100644
--- a/scripts/test-amneziawg-config.py
+++ b/scripts/test-amneziawg-config.py
@@ -10,12 +10,14 @@ import zlib
from pathlib import Path
from unittest.mock import patch
+import amneziawg_config
from amneziawg_config import (
ConfigError,
decode_vpn_link,
extract_vpn_config,
prepare,
probe_address,
+ rekey_after_time,
render_settings,
transport_implementation,
validate_config,
@@ -415,6 +417,25 @@ class AmneziaWgConfigTests(unittest.TestCase):
)
self.assertEqual(probe_address(config), "10.23.42.1")
+ def test_rekey_after_time_takes_the_upper_bound(self):
+ config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
+ self.assertEqual(rekey_after_time(config.replace("[Peer]", "RekeyAfterTime = 100-300\n[Peer]")), 300)
+ self.assertEqual(rekey_after_time(config.replace("[Peer]", "RekeyAfterTime = (off)\n[Peer]")), 0)
+ # Only [Interface] counts, and WireGuard's own 120 is the default.
+ self.assertEqual(rekey_after_time(config + "RekeyAfterTime = 999\n"), 120)
+
+ def test_inspect_prints_what_the_start_script_reads(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "awg.conf"
+ path.write_text(BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1"))
+ result = subprocess.run(
+ [sys.executable, amneziawg_config.__file__, "--inspect", str(path)],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ self.assertEqual(result.stdout, "auto 1.1.1.1 120\n")
+
def test_random_trailers_with_ranged_handshake_headers_forces_userspace(self):
config = BASE_CONFIG.replace(
"ContentPaddingAddition = 8-16",
diff --git a/scripts/warp_outbound.py b/scripts/warp_outbound.py
index 7d5c590..f9bfc3e 100644
--- a/scripts/warp_outbound.py
+++ b/scripts/warp_outbound.py
@@ -8,23 +8,14 @@ import json
import sys
from typing import Any
-
-class ConfigError(ValueError):
- pass
+from amneziawg_config import ConfigError, conf_sections
def parse_conf(text: str) -> tuple[dict[str, str], dict[str, str]]:
"""Return the [Interface] section and the first [Peer], keys lowercased."""
- sections: list[tuple[str, dict[str, str]]] = []
- for line in text.splitlines():
- stripped = line.split("#", 1)[0].strip()
- if stripped.startswith("[") and stripped.endswith("]"):
- sections.append((stripped[1:-1].strip().lower(), {}))
- elif "=" in stripped and sections:
- key, value = (part.strip() for part in stripped.split("=", 1))
- sections[-1][1][key.lower()] = value
- interface = next((s for name, s in sections if name == "interface"), None)
- peer = next((s for name, s in sections if name == "peer"), None)
+ sections = conf_sections(text)
+ interface = next((dict(pairs) for name, pairs in sections if name == "interface"), None)
+ peer = next((dict(pairs) for name, pairs in sections if name == "peer"), None)
if interface is None or peer is None:
raise ConfigError("configuration requires [Interface] and [Peer] sections")
for section, key in ((interface, "privatekey"), (interface, "address"), (peer, "publickey"), (peer, "endpoint")):
@@ -78,7 +69,7 @@ def main() -> int:
args = parser.parse_args()
try:
print(json.dumps(build(sys.stdin.read(), args.tag, args.routing_mark)))
- except (ConfigError, ValueError) as error:
+ except ValueError as error:
print(f"proxy-suite: warp: {error}", file=sys.stderr)
return 1
return 0