fix: hardening and fixes
This commit is contained in:
32 files changed
+619
-256
No files matched your search
@@ -103,6 +103,11 @@ null or package
|
|||||||
|
|
||||||
Named AmneziaWG client profiles\. Only one global profile can be active\.
|
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:*
|
*Type:*
|
||||||
attribute set of (submodule)
|
attribute set of (submodule)
|
||||||
|
|
||||||
|
|||||||
@@ -213,7 +213,7 @@ services.proxy-suite = {
|
|||||||
port = 22;
|
port = 22;
|
||||||
user = null;
|
user = null;
|
||||||
};
|
};
|
||||||
serviceUser = null;
|
serviceUser = "proxy-suite-daemon";
|
||||||
strictHostKeyChecking = "accept-new";
|
strictHostKeyChecking = "accept-new";
|
||||||
};
|
};
|
||||||
tgWsProxy = {
|
tgWsProxy = {
|
||||||
@@ -258,6 +258,7 @@ services.proxy-suite = {
|
|||||||
asOutbound = false;
|
asOutbound = false;
|
||||||
configFile = null;
|
configFile = null;
|
||||||
enable = false;
|
enable = false;
|
||||||
|
generatorUrl = null;
|
||||||
};
|
};
|
||||||
zapret = {
|
zapret = {
|
||||||
cidrExemption = {
|
cidrExemption = {
|
||||||
|
|||||||
@@ -147,7 +147,7 @@ null
|
|||||||
<a id="services-proxy-suite-sshproxy-identityfile"></a>
|
<a id="services-proxy-suite-sshproxy-identityfile"></a>
|
||||||
## services\.proxy-suite\.sshProxy\.identityFile
|
## 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:*
|
*Type:*
|
||||||
null or string
|
null or string
|
||||||
@@ -269,7 +269,7 @@ null
|
|||||||
<a id="services-proxy-suite-sshproxy-serviceuser"></a>
|
<a id="services-proxy-suite-sshproxy-serviceuser"></a>
|
||||||
## services\.proxy-suite\.sshProxy\.serviceUser
|
## 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:*
|
*Type:*
|
||||||
null or string matching the pattern \[^\[:space:]]+
|
null or string matching the pattern \[^\[:space:]]+
|
||||||
@@ -277,7 +277,7 @@ null or string matching the pattern \[^\[:space:]]+
|
|||||||
*Default:*
|
*Default:*
|
||||||
|
|
||||||
```nix
|
```nix
|
||||||
null
|
"proxy-suite-daemon"
|
||||||
```
|
```
|
||||||
|
|
||||||
*Example:*
|
*Example:*
|
||||||
|
|||||||
@@ -221,7 +221,7 @@ Listen port\.
|
|||||||
<a id="services-proxy-suite-tgwsproxy-log-file"></a>
|
<a id="services-proxy-suite-tgwsproxy-log-file"></a>
|
||||||
## services\.proxy-suite\.tgWsProxy\.log\.file
|
## 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:*
|
*Type:*
|
||||||
null or string
|
null or string
|
||||||
@@ -235,7 +235,7 @@ null
|
|||||||
*Example:*
|
*Example:*
|
||||||
|
|
||||||
```nix
|
```nix
|
||||||
"/var/log/tg-ws-proxy.log"
|
"/var/log/proxy-suite-tg-ws-proxy/tg-ws-proxy.log"
|
||||||
```
|
```
|
||||||
|
|
||||||
<a id="services-proxy-suite-tgwsproxy-log-keep"></a>
|
<a id="services-proxy-suite-tgwsproxy-log-keep"></a>
|
||||||
|
|||||||
+31
-4
@@ -9,6 +9,7 @@ Part of the [proxy-suite options reference](./index.md).
|
|||||||
- [asAmneziaWg](#services-proxy-suite-warp-asamneziawg)
|
- [asAmneziaWg](#services-proxy-suite-warp-asamneziawg)
|
||||||
- [asOutbound](#services-proxy-suite-warp-asoutbound)
|
- [asOutbound](#services-proxy-suite-warp-asoutbound)
|
||||||
- [configFile](#services-proxy-suite-warp-configfile)
|
- [configFile](#services-proxy-suite-warp-configfile)
|
||||||
|
- [generatorUrl](#services-proxy-suite-warp-generatorurl)
|
||||||
|
|
||||||
<a id="services-proxy-suite-warp-enable"></a>
|
<a id="services-proxy-suite-warp-enable"></a>
|
||||||
## services\.proxy-suite\.warp\.enable
|
## services\.proxy-suite\.warp\.enable
|
||||||
@@ -33,7 +34,8 @@ true
|
|||||||
<a id="services-proxy-suite-warp-asamneziawg"></a>
|
<a id="services-proxy-suite-warp-asamneziawg"></a>
|
||||||
## services\.proxy-suite\.warp\.asAmneziaWg
|
## 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:*
|
*Type:*
|
||||||
boolean
|
boolean
|
||||||
@@ -48,8 +50,9 @@ false
|
|||||||
## services\.proxy-suite\.warp\.asOutbound
|
## services\.proxy-suite\.warp\.asOutbound
|
||||||
|
|
||||||
Add WARP as an outbound tagged “warp”: a SOCKS hop to proxy-suite-warp-tunnel, which
|
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
|
runs WARP as a sing-box WireGuard endpoint on 127\.0\.0\.1:18538, as the proxy-suite-daemon user\.
|
||||||
source port when the handshake stops being answered\.
|
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:*
|
*Type:*
|
||||||
boolean
|
boolean
|
||||||
@@ -64,7 +67,7 @@ false
|
|||||||
## services\.proxy-suite\.warp\.configFile
|
## services\.proxy-suite\.warp\.configFile
|
||||||
|
|
||||||
Runtime path to a WireGuard profile for WARP, as written by ` wgcf register && wgcf generate `\.
|
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)
|
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
|
into /var/lib/proxy-suite/warp, through the local proxy when proxy\.enable is set, and
|
||||||
@@ -84,3 +87,27 @@ null
|
|||||||
```nix
|
```nix
|
||||||
"/run/secrets/wgcf-profile.conf"
|
"/run/secrets/wgcf-profile.conf"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
<a id="services-proxy-suite-warp-generatorurl"></a>
|
||||||
|
## 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"
|
||||||
|
```
|
||||||
@@ -25,38 +25,37 @@ let
|
|||||||
profile.settings
|
profile.settings
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
inlineVpnFile = name: profile: pkgs.writeText "proxy-suite-awg" profile.vpn;
|
source =
|
||||||
sourceKind =
|
|
||||||
profile:
|
profile:
|
||||||
if profile.configFile != null then
|
if profile.configFile != null then
|
||||||
"configFile"
|
{
|
||||||
|
kind = "configFile";
|
||||||
|
path = profile.configFile;
|
||||||
|
}
|
||||||
else if profile.vpnFile != null then
|
else if profile.vpnFile != null then
|
||||||
"vpnFile"
|
{
|
||||||
|
kind = "vpnFile";
|
||||||
|
path = profile.vpnFile;
|
||||||
|
}
|
||||||
else if profile.vpn != null then
|
else if profile.vpn != null then
|
||||||
"vpn"
|
{
|
||||||
|
kind = "vpn";
|
||||||
|
path = pkgs.writeText "proxy-suite-awg" profile.vpn;
|
||||||
|
}
|
||||||
else
|
else
|
||||||
"settings";
|
{
|
||||||
sourcePath =
|
kind = "settings";
|
||||||
name: profile:
|
inherit (profile) settings;
|
||||||
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;
|
|
||||||
manifestFor =
|
manifestFor =
|
||||||
name: profile:
|
profile:
|
||||||
pkgs.writeText "proxy-suite-awg" (
|
pkgs.writeText "proxy-suite-awg" (
|
||||||
builtins.toJSON (
|
builtins.toJSON (
|
||||||
{
|
{
|
||||||
kind = sourceKind profile;
|
|
||||||
allowConfigHooks = profile.allowConfigHooks;
|
allowConfigHooks = profile.allowConfigHooks;
|
||||||
vpnContainer = profile.vpnContainer;
|
vpnContainer = profile.vpnContainer;
|
||||||
}
|
}
|
||||||
// lib.optionalAttrs (sourcePath name profile != null) { path = sourcePath name profile; }
|
// source profile
|
||||||
// lib.optionalAttrs (profile.settings != null) { settings = profile.settings; }
|
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
configTool = "${
|
configTool = "${
|
||||||
@@ -69,11 +68,42 @@ let
|
|||||||
runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf";
|
runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf";
|
||||||
# Keep proxy backend sockets (proxyMark) out of AWG's default-route table.
|
# Keep proxy backend sockets (proxyMark) out of AWG's default-route table.
|
||||||
proxyBypassRulePriority = 8998;
|
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 =
|
mkService =
|
||||||
name: profile:
|
name: profile:
|
||||||
let
|
let
|
||||||
manifest = manifestFor name profile;
|
manifest = manifestFor profile;
|
||||||
configPath = runtimeConfig name profile;
|
configPath = runtimeConfig name profile;
|
||||||
prepare = pkgs.writeShellScript "proxy-suite-awg" ''
|
prepare = pkgs.writeShellScript "proxy-suite-awg" ''
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -83,36 +113,17 @@ let
|
|||||||
'';
|
'';
|
||||||
proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" ''
|
proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" ''
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
${clearBypassRules}
|
||||||
add_bypass_rule() {
|
# IPv4 is required, or the proxy backend is captured by AWG; IPv6 is best-effort.
|
||||||
local family="$1"
|
if ! ${bypassRule "-4" "add"} 2>/dev/null; then
|
||||||
while ${pkgs.iproute2}/bin/ip "$family" rule del \
|
echo "proxy-suite: unable to install the AWG proxy-backend bypass rule" >&2
|
||||||
pref ${toString proxyBypassRulePriority} \
|
exit 1
|
||||||
fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done
|
fi
|
||||||
if ! ${pkgs.iproute2}/bin/ip "$family" rule add \
|
${bypassRule "-6" "add"} 2>/dev/null || true
|
||||||
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
|
|
||||||
'';
|
'';
|
||||||
proxyBypassDown = pkgs.writeShellScript "proxy-suite-awg" ''
|
proxyBypassDown = pkgs.writeShellScript "proxy-suite-awg" ''
|
||||||
set +e
|
set +e
|
||||||
|
${clearBypassRules}
|
||||||
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
|
|
||||||
'';
|
'';
|
||||||
start = pkgs.writeShellScript "proxy-suite-awg" ''
|
start = pkgs.writeShellScript "proxy-suite-awg" ''
|
||||||
set -Eeuo pipefail
|
set -Eeuo pipefail
|
||||||
@@ -149,8 +160,8 @@ let
|
|||||||
${pkgs.kmod}/bin/modprobe amneziawg 2>/dev/null || true
|
${pkgs.kmod}/bin/modprobe amneziawg 2>/dev/null || true
|
||||||
''}
|
''}
|
||||||
|
|
||||||
implementation="$(${pkgs.python3}/bin/python3 ${configTool} \
|
read -r implementation probe _ < <(${pkgs.python3}/bin/python3 ${configTool} \
|
||||||
--transport-implementation ${lib.escapeShellArg configPath})"
|
--inspect ${lib.escapeShellArg configPath})
|
||||||
# The 3.1 kernel module dropped RandomTrailers packets with ranged H1-H3 (seen on 20260812);
|
# The 3.1 kernel module dropped RandomTrailers packets with ranged H1-H3 (seen on 20260812);
|
||||||
# userspace carries the fix.
|
# userspace carries the fix.
|
||||||
if [[ "$implementation" == userspace ]]; then
|
if [[ "$implementation" == userspace ]]; then
|
||||||
@@ -162,14 +173,17 @@ let
|
|||||||
${awgCfg.toolsPackage}/bin/awg-quick up ${lib.escapeShellArg configPath}
|
${awgCfg.toolsPackage}/bin/awg-quick up ${lib.escapeShellArg configPath}
|
||||||
fi
|
fi
|
||||||
|
|
||||||
probe="$(${pkgs.python3}/bin/python3 ${configTool} --probe-address ${lib.escapeShellArg configPath})"
|
${mkHandshakeHelpers profile}
|
||||||
for _ in $(${pkgs.coreutils}/bin/seq 1 15); do
|
# 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
|
${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 \
|
if (( $(handshake_age) < 1000000 )); then
|
||||||
| ${pkgs.gawk}/bin/awk '$2 + 0 > 0 { found = 1 } END { exit !found }'; then
|
|
||||||
trap - ERR
|
trap - ERR
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
if (( attempt % 5 == 0 )); then
|
||||||
|
new_source_port
|
||||||
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
echo "proxy-suite: AmneziaWG profile '${name}' did not complete a handshake; rolling back routes" >&2
|
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 (
|
profileAssertions = lib.concatMap (
|
||||||
name:
|
name:
|
||||||
let
|
let
|
||||||
@@ -268,8 +339,8 @@ let
|
|||||||
{
|
{
|
||||||
assertion =
|
assertion =
|
||||||
obfuscation == null
|
obfuscation == null
|
||||||
|| ((obfuscation.headerProtectionKey != null) != (obfuscation.headerProtectionKeyFile != null))
|
|| obfuscation.headerProtectionKey == null
|
||||||
|| (obfuscation.headerProtectionKey == null && obfuscation.headerProtectionKeyFile == null);
|
|| obfuscation.headerProtectionKeyFile == null;
|
||||||
message = "proxy-suite: AmneziaWG profile '${name}': set at most one header-protection key source";
|
message = "proxy-suite: AmneziaWG profile '${name}': set at most one header-protection key source";
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -299,6 +370,9 @@ in
|
|||||||
(lib.mapAttrs' (
|
(lib.mapAttrs' (
|
||||||
name: profile: lib.nameValuePair (serviceName name) (mkService name profile)
|
name: profile: lib.nameValuePair (serviceName name) (mkService name profile)
|
||||||
) profiles)
|
) profiles)
|
||||||
|
(lib.mapAttrs' (
|
||||||
|
name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile)
|
||||||
|
) profiles)
|
||||||
(lib.mkIf cfg.proxy.tun.enable {
|
(lib.mkIf cfg.proxy.tun.enable {
|
||||||
proxy-suite-tun.conflicts = map (name: "${name}.service") serviceNames;
|
proxy-suite-tun.conflicts = map (name: "${name}.service") serviceNames;
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ pkgs.writeShellScript "proxy-suite-autoproxy" ''
|
|||||||
[(.domains // {}) | to_entries[] | select(.value.exit == $t) | .key] as $d
|
[(.domains // {}) | to_entries[] | select(.value.exit == $t) | .key] as $d
|
||||||
| {version: 1, rules: (if ($d | length) > 0 then [{domain_suffix: $d}] else [] end)}
|
| {version: 1, rules: (if ($d | length) > 0 then [{domain_suffix: $d}] else [] end)}
|
||||||
' "$2" > "$path.tmp"
|
' "$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"
|
mv -f "$path.tmp" "$path"
|
||||||
done
|
done
|
||||||
''
|
''
|
||||||
@@ -52,7 +52,7 @@ let
|
|||||||
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
|
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
install -d -m 0750 "$state_dir"
|
install -d -m 0751 "$state_dir"
|
||||||
|
|
||||||
# Eleven snapshots a second apart: ten one-second deltas per connection.
|
# Eleven snapshots a second apart: ten one-second deltas per connection.
|
||||||
lines=$(
|
lines=$(
|
||||||
@@ -86,7 +86,7 @@ let
|
|||||||
echo "no probe listeners - is proxy-suite-socks running with autoProxy on?"
|
echo "no probe listeners - is proxy-suite-socks running with autoProxy on?"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
install -d -m 0750 "$state_dir"
|
install -d -m 0751 "$state_dir"
|
||||||
|
|
||||||
# Timer runs and learn requests take turns on the state.
|
# Timer runs and learn requests take turns on the state.
|
||||||
exec 9> "$state_dir/lock"
|
exec 9> "$state_dir/lock"
|
||||||
@@ -114,7 +114,7 @@ let
|
|||||||
echo "could not update $state; it is left as it was" >&2
|
echo "could not update $state; it is left as it was" >&2
|
||||||
return 1
|
return 1
|
||||||
fi
|
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"
|
chmod 0640 "$tmp"
|
||||||
mv -f "$tmp" "$state"
|
mv -f "$tmp" "$state"
|
||||||
}
|
}
|
||||||
@@ -396,7 +396,10 @@ let
|
|||||||
# declares the directory - systemd re-applies the ownership on each start.
|
# declares the directory - systemd re-applies the ownership on each start.
|
||||||
stateDirConfig = {
|
stateDirConfig = {
|
||||||
StateDirectory = "proxy-suite/autoproxy";
|
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; };
|
// lib.optionalAttrs (cfg.userControl.allow != [ ]) { Group = cfg.userControl.group; };
|
||||||
|
|
||||||
|
|||||||
@@ -141,14 +141,15 @@ in
|
|||||||
)
|
)
|
||||||
|
|
||||||
(lib.mkIf cfg.tgWsProxy.enable (
|
(lib.mkIf cfg.tgWsProxy.enable (
|
||||||
import ./tg-ws-proxy.nix {
|
(import ./tg-ws-proxy.nix {
|
||||||
inherit
|
inherit
|
||||||
lib
|
lib
|
||||||
pkgs
|
pkgs
|
||||||
packages
|
packages
|
||||||
cfg
|
cfg
|
||||||
|
derived
|
||||||
;
|
;
|
||||||
}
|
}).config
|
||||||
))
|
))
|
||||||
|
|
||||||
# SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH
|
# SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH
|
||||||
@@ -159,6 +160,7 @@ in
|
|||||||
lib
|
lib
|
||||||
pkgs
|
pkgs
|
||||||
cfg
|
cfg
|
||||||
|
derived
|
||||||
;
|
;
|
||||||
}
|
}
|
||||||
))
|
))
|
||||||
|
|||||||
@@ -44,6 +44,8 @@ let
|
|||||||
"/var/lib/proxy-suite/warp/wgcf-profile.conf";
|
"/var/lib/proxy-suite/warp/wgcf-profile.conf";
|
||||||
# Loopback SOCKS listener of proxy-suite-warp-tunnel, which the "warp" outbound dials.
|
# Loopback SOCKS listener of proxy-suite-warp-tunnel, which the "warp" outbound dials.
|
||||||
tunnelPort = 18538;
|
tunnelPort = 18538;
|
||||||
|
# Its "direct-in" listener, which tells a blocked WARP from a dead uplink.
|
||||||
|
directPort = 18539;
|
||||||
};
|
};
|
||||||
warpOutboundTag = "warp";
|
warpOutboundTag = "warp";
|
||||||
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound;
|
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound;
|
||||||
@@ -148,6 +150,47 @@ let
|
|||||||
zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds;
|
zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds;
|
||||||
userControlEnabled = userControlCfg.allow != [ ];
|
userControlEnabled = userControlCfg.allow != [ ];
|
||||||
constants = {
|
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";
|
zapret2StateDir = "/var/lib/proxy-suite/zapret2";
|
||||||
zapret2CutoffDir = "/var/lib/proxy-suite/zapret2/cutoff";
|
zapret2CutoffDir = "/var/lib/proxy-suite/zapret2/cutoff";
|
||||||
# Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone.
|
# Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone.
|
||||||
|
|||||||
@@ -39,7 +39,14 @@ in
|
|||||||
profiles = mkOption {
|
profiles = mkOption {
|
||||||
type = types.attrsOf t.profileType;
|
type = types.attrsOf t.profileType;
|
||||||
default = { };
|
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.
|
||||||
|
'';
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -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 {
|
hostKey = mkOption {
|
||||||
type = types.listOf types.str;
|
type = types.listOf types.str;
|
||||||
@@ -92,8 +92,8 @@ in
|
|||||||
|
|
||||||
serviceUser = mkOption {
|
serviceUser = mkOption {
|
||||||
type = token;
|
type = token;
|
||||||
default = null;
|
default = "proxy-suite-daemon";
|
||||||
description = "Unix user running the OpenSSH unit.";
|
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";
|
example = "proxy";
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -109,8 +109,8 @@ in
|
|||||||
file = mkOption {
|
file = mkOption {
|
||||||
type = types.nullOr types.str;
|
type = types.nullOr types.str;
|
||||||
default = null;
|
default = null;
|
||||||
description = "Rotating log file. Null logs to stderr.";
|
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/tg-ws-proxy.log";
|
example = "/var/log/proxy-suite-tg-ws-proxy/tg-ws-proxy.log";
|
||||||
};
|
};
|
||||||
|
|
||||||
maxSizeMiB = mkOption {
|
maxSizeMiB = mkOption {
|
||||||
|
|||||||
@@ -39,8 +39,9 @@ in
|
|||||||
default = false;
|
default = false;
|
||||||
description = ''
|
description = ''
|
||||||
Add WARP as an outbound tagged "warp": a SOCKS hop to proxy-suite-warp-tunnel, which
|
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
|
runs WARP as a sing-box WireGuard endpoint on 127.0.0.1:18538, as the proxy-suite-daemon user.
|
||||||
source port when the handshake stops being answered.
|
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;
|
type = types.bool;
|
||||||
default = false;
|
default = false;
|
||||||
description = ''
|
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.
|
||||||
'';
|
'';
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -76,6 +76,14 @@ let
|
|||||||
(mkAssertion (
|
(mkAssertion (
|
||||||
!cfg.warp.enable || cfg.warp.asOutbound || cfg.warp.asAmneziaWg
|
!cfg.warp.enable || cfg.warp.asOutbound || cfg.warp.asAmneziaWg
|
||||||
) "proxy-suite: warp.enable = true needs warp.asOutbound or 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
|
(requireEnabled derived.warpOutboundEnabled proxyEnabled
|
||||||
"proxy-suite: warp.asOutbound requires proxy.enable = true"
|
"proxy-suite: warp.asOutbound requires proxy.enable = true"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -134,6 +134,15 @@ let
|
|||||||
in
|
in
|
||||||
lib.mkMerge [
|
lib.mkMerge [
|
||||||
autoProxyUnits
|
autoProxyUnits
|
||||||
|
{
|
||||||
|
# See constants.serviceUser.
|
||||||
|
users.users.${constants.serviceUser} = {
|
||||||
|
isSystemUser = true;
|
||||||
|
group = constants.serviceUser;
|
||||||
|
description = "proxy-suite daemons";
|
||||||
|
};
|
||||||
|
users.groups.${constants.serviceUser} = { };
|
||||||
|
}
|
||||||
{
|
{
|
||||||
environment.systemPackages = [
|
environment.systemPackages = [
|
||||||
control.proxyCtl
|
control.proxyCtl
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ let
|
|||||||
subscriptionsFile = "${runtimeDir}/subscriptions.json";
|
subscriptionsFile = "${runtimeDir}/subscriptions.json";
|
||||||
subsCfg = proxyInboundsCfg.subscriptions;
|
subsCfg = proxyInboundsCfg.subscriptions;
|
||||||
xray = "${proxyInboundsCfg.package}/bin/xray";
|
xray = "${proxyInboundsCfg.package}/bin/xray";
|
||||||
|
# Only listeners: no marks, no transparent sockets.
|
||||||
|
runXray = constants.runAsServiceUser pkgs [ "net_bind_service" ];
|
||||||
|
|
||||||
needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled;
|
needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled;
|
||||||
|
|
||||||
@@ -144,13 +146,39 @@ let
|
|||||||
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
|
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
|
||||||
= [{user:$user,pass:$password}]
|
= [{user:$user,pass:$password}]
|
||||||
else . end' \
|
else . end' \
|
||||||
${proxyInboundsFile} > "$RUNTIME_DIR/config.json"
|
${proxyInboundsFile} > "$RUNTIME_DIR/config.json.tmp"
|
||||||
chmod 600 "$RUNTIME_DIR/config.json"
|
|
||||||
|
# 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}
|
${writeLinksBlock}
|
||||||
${writeSubscriptionsBlock}
|
${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.
|
# Adds XRay's per-user counters to the daily totals, read and reset in one call.
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
proxyCfg,
|
proxyCfg,
|
||||||
sshProxyCfg,
|
sshProxyCfg,
|
||||||
warpCfg,
|
warpCfg,
|
||||||
|
constants,
|
||||||
pureXrayEnabled,
|
pureXrayEnabled,
|
||||||
hybridEnabled,
|
hybridEnabled,
|
||||||
collapseNamedOutbounds,
|
collapseNamedOutbounds,
|
||||||
@@ -305,9 +306,6 @@ let
|
|||||||
server_port = sshProxyCfg.server.port;
|
server_port = sshProxyCfg.server.port;
|
||||||
user = sshProxyCfg.server.user;
|
user = sshProxyCfg.server.user;
|
||||||
}
|
}
|
||||||
// lib.optionalAttrs (sshProxyCfg.identityFile != null) {
|
|
||||||
private_key_path = sshProxyCfg.identityFile;
|
|
||||||
}
|
|
||||||
// lib.optionalAttrs (sshProxyCfg.hostKey != [ ]) {
|
// lib.optionalAttrs (sshProxyCfg.hostKey != [ ]) {
|
||||||
host_key = sshProxyCfg.hostKey;
|
host_key = sshProxyCfg.hostKey;
|
||||||
}
|
}
|
||||||
@@ -355,6 +353,13 @@ let
|
|||||||
''
|
''
|
||||||
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
|
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
|
||||||
OB_JSON=$(cat "${jsonFile}")
|
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}
|
${hostKeyFileBlock}
|
||||||
${
|
${
|
||||||
if hybridEnabled then
|
if hybridEnabled then
|
||||||
|
|||||||
@@ -111,6 +111,7 @@ let
|
|||||||
proxyCfg
|
proxyCfg
|
||||||
sshProxyCfg
|
sshProxyCfg
|
||||||
warpCfg
|
warpCfg
|
||||||
|
constants
|
||||||
pureXrayEnabled
|
pureXrayEnabled
|
||||||
hybridEnabled
|
hybridEnabled
|
||||||
collapseNamedOutbounds
|
collapseNamedOutbounds
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ let
|
|||||||
;
|
;
|
||||||
|
|
||||||
autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; };
|
autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; };
|
||||||
|
runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
|
||||||
|
|
||||||
routeModeBlacklistTail =
|
routeModeBlacklistTail =
|
||||||
if pureXrayEnabled then
|
if pureXrayEnabled then
|
||||||
@@ -205,7 +206,8 @@ let
|
|||||||
AUTOPROXY_RULES_JSON='[]'
|
AUTOPROXY_RULES_JSON='[]'
|
||||||
${lib.optionalString enableAutoProxy ''
|
${lib.optionalString enableAutoProxy ''
|
||||||
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
|
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"
|
[ -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
|
# 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"}
|
CUTOFF_RULE_SET=${lib.escapeShellArg "${constants.zapret2CutoffDir}/proxy.json"}
|
||||||
install -d -m 0755 "$(dirname "$CUTOFF_RULE_SET")"
|
install -d -m 0755 "$(dirname "$CUTOFF_RULE_SET")"
|
||||||
[ -s "$CUTOFF_RULE_SET" ] || echo '{"version":1,"rules":[]}' > "$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" \
|
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$CUTOFF_RULE_SET" \
|
||||||
'. + [{type: "local", format: "source", tag: "zapret-cutoff", path: $p}]' <<< "$AUTOPROXY_RULE_SETS_JSON")
|
'. + [{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")
|
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} \
|
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
|
||||||
-f "$BACKEND_JQ_FILTER" \
|
-f "$BACKEND_JQ_FILTER" \
|
||||||
"${configFile}" > "$RUNTIME_DIR/config.json"
|
"${configFile}" > "$RUNTIME_DIR/config.json"
|
||||||
${lib.optionalString enableLocalProxyAuth ''
|
# The backend runs as ${constants.serviceUser}: its configs are group-readable.
|
||||||
chmod 600 "$RUNTIME_DIR/config.json"
|
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
|
if hybridEnabled then
|
||||||
@@ -358,7 +364,7 @@ let
|
|||||||
trap _proxy_suite_cleanup_xray_sidecar EXIT
|
trap _proxy_suite_cleanup_xray_sidecar EXIT
|
||||||
trap 'exit 143' INT TERM
|
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="$!"
|
XRAY_SIDECAR_PID="$!"
|
||||||
${pkgs.coreutils}/bin/sleep 0.2
|
${pkgs.coreutils}/bin/sleep 0.2
|
||||||
if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then
|
if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then
|
||||||
@@ -367,7 +373,7 @@ let
|
|||||||
exit "$XRAY_SIDECAR_STATUS"
|
exit "$XRAY_SIDECAR_STATUS"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
${singBox} run -c "$RUNTIME_DIR/config.json" &
|
${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json" &
|
||||||
SING_BOX_PID="$!"
|
SING_BOX_PID="$!"
|
||||||
# Either one going away breaks the outbounds: exit, and let systemd restart both.
|
# Either one going away breaks the outbounds: exit, and let systemd restart both.
|
||||||
SING_BOX_STATUS=0
|
SING_BOX_STATUS=0
|
||||||
@@ -375,11 +381,11 @@ let
|
|||||||
exit "$(( SING_BOX_STATUS == 0 ? 1 : SING_BOX_STATUS ))"
|
exit "$(( SING_BOX_STATUS == 0 ? 1 : SING_BOX_STATUS ))"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
|
exec ${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json"
|
||||||
''
|
''
|
||||||
else
|
else
|
||||||
''
|
''
|
||||||
exec ${backendBin} run -c "$RUNTIME_DIR/config.json"
|
exec ${runBackend} ${backendBin} run -c "$RUNTIME_DIR/config.json"
|
||||||
''
|
''
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
|
|||||||
@@ -3,12 +3,22 @@
|
|||||||
lib,
|
lib,
|
||||||
pkgs,
|
pkgs,
|
||||||
cfg,
|
cfg,
|
||||||
|
derived,
|
||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
s = cfg.sshProxy;
|
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}";
|
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;
|
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" ''
|
startScript = pkgs.writeShellScript "proxy-suite-ssh-proxy" ''
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
@@ -23,10 +33,8 @@ let
|
|||||||
-D ${lib.escapeShellArg "${s.listener.address}:${toString s.listener.port}"}
|
-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.server.port != 22) "args+=(-p ${toString s.server.port})"}
|
||||||
${lib.optionalString (s.identityFile != null) "args+=(-i ${lib.escapeShellArg s.identityFile})"}
|
${lib.optionalString (s.identityFile != null) ''args+=(-i "$CREDENTIALS_DIRECTORY/identity")''}
|
||||||
${lib.optionalString (
|
${lib.optionalString (knownHosts != null) ''args+=(-o UserKnownHostsFile=${knownHosts})''}
|
||||||
s.knownHostsFile != null
|
|
||||||
) "args+=(-o ${lib.escapeShellArg "UserKnownHostsFile=${s.knownHostsFile}"})"}
|
|
||||||
${extraArgs}
|
${extraArgs}
|
||||||
exec ${pkgs.openssh}/bin/ssh "''${args[@]}" ${lib.escapeShellArg destination}
|
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
|
# Restart=always plus a server that refuses connections would otherwise hit
|
||||||
# the default 5-starts-in-10s limit and stay failed.
|
# the default 5-starts-in-10s limit and stay failed.
|
||||||
startLimitIntervalSec = 0;
|
startLimitIntervalSec = 0;
|
||||||
serviceConfig = {
|
serviceConfig =
|
||||||
ExecStart = startScript;
|
lib.optionalAttrs (s.serviceUser == serviceUser) (unprivilegedServiceConfig [ "net_bind_service" ])
|
||||||
# `ssh -N` exits 0 when the server closes the connection cleanly, which
|
// {
|
||||||
# under on-failure left the tunnel down for good.
|
ExecStart = startScript;
|
||||||
Restart = "always";
|
# Copies the service user can read, whoever owns the originals.
|
||||||
RestartSec = 5;
|
LoadCredential =
|
||||||
# One fd per forwarded channel; the 1024 default is low for a relay.
|
lib.optional (s.identityFile != null) "identity:${s.identityFile}"
|
||||||
LimitNOFILE = 65536;
|
++ lib.optional (s.knownHostsFile != null) "known_hosts:${s.knownHostsFile}";
|
||||||
}
|
StateDirectory = "proxy-suite/ssh";
|
||||||
// lib.optionalAttrs (s.serviceUser != null) {
|
StateDirectoryMode = "0700";
|
||||||
User = s.serviceUser;
|
# `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;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
pkgs,
|
pkgs,
|
||||||
packages,
|
packages,
|
||||||
cfg,
|
cfg,
|
||||||
|
derived,
|
||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
@@ -84,20 +85,32 @@ let
|
|||||||
'';
|
'';
|
||||||
in
|
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";
|
description = "Telegram MTProto WebSocket proxy";
|
||||||
after = [ "network-online.target" ];
|
after = [ "network-online.target" ];
|
||||||
wants = [ "network-online.target" ];
|
wants = [ "network-online.target" ];
|
||||||
wantedBy = [ "multi-user.target" ];
|
wantedBy = [ "multi-user.target" ];
|
||||||
serviceConfig = {
|
serviceConfig =
|
||||||
ExecStart = startScript;
|
derived.constants.unprivilegedServiceConfig [
|
||||||
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
|
"net_bind_service"
|
||||||
Restart = "on-failure";
|
]
|
||||||
RestartSec = 5;
|
// {
|
||||||
}
|
ExecStart = startScript;
|
||||||
// lib.optionalAttrs transparentBypassEnabled {
|
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
|
||||||
ExecStartPre = bypassUpScript;
|
Restart = "on-failure";
|
||||||
ExecStopPost = bypassDownScript;
|
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}";
|
||||||
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
|
|
||||||
let
|
let
|
||||||
w = derived.warpCfg;
|
w = derived.warpCfg;
|
||||||
|
inherit (derived.constants) serviceUser runAsServiceUser unprivilegedServiceConfig;
|
||||||
listener = cfg.proxy.listener;
|
listener = cfg.proxy.listener;
|
||||||
auth = listener.auth;
|
auth = listener.auth;
|
||||||
scriptsDir = builtins.path {
|
scriptsDir = builtins.path {
|
||||||
@@ -33,9 +34,10 @@ let
|
|||||||
pkgs.writeText "proxy-suite-warp" auth.password
|
pkgs.writeText "proxy-suite-warp" auth.password
|
||||||
else
|
else
|
||||||
null;
|
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} \
|
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" ''
|
registerScript = pkgs.writeShellScript "proxy-suite-warp" ''
|
||||||
@@ -49,18 +51,22 @@ let
|
|||||||
${lib.optionalString (w.generatorUrl != null) ''
|
${lib.optionalString (w.generatorUrl != null) ''
|
||||||
|
|
||||||
# Fallback: a third-party generator registers from abroad and hands the profile back.
|
# Fallback: a third-party generator registers from abroad and hands the profile back.
|
||||||
|
# curl follows HTTPS_PROXY when it is set.
|
||||||
generate() {
|
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
|
${lib.escapeShellArg w.generatorUrl}) || return 1
|
||||||
case "$body" in
|
case "$body" in
|
||||||
"[Interface]"*) printf '%s\n' "$body" ;;
|
"[Interface]"*) printf '%s\n' "$body" ;;
|
||||||
*) ${pkgs.jq}/bin/jq -er '.content | @base64d' <<< "$body" ;;
|
*) ${pkgs.jq}/bin/jq -er '.content | @base64d' <<< "$body" ;;
|
||||||
esac > 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 || 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
|
mv wgcf-profile.conf.tmp wgcf-profile.conf
|
||||||
}
|
}
|
||||||
''}
|
''}
|
||||||
${
|
${
|
||||||
|
let
|
||||||
|
fallbacks = lib.optionalString (w.generatorUrl != null) " || generate";
|
||||||
|
in
|
||||||
if cfg.proxy.enable then
|
if cfg.proxy.enable then
|
||||||
''
|
''
|
||||||
# The API is blocked in some countries, so the local proxy goes first. It may
|
# The API is blocked in some countries, so the local proxy goes first. It may
|
||||||
@@ -71,12 +77,15 @@ let
|
|||||||
done
|
done
|
||||||
userinfo=
|
userinfo=
|
||||||
${userinfo}
|
${userinfo}
|
||||||
HTTPS_PROXY="socks5://''${userinfo}${hostPart}:${toString listener.port}" register || register${
|
proxied() {
|
||||||
lib.optionalString (w.generatorUrl != null) " || generate"
|
HTTPS_PROXY="socks5://''${userinfo}${hostPart}:${toString listener.port}" "$@"
|
||||||
|
}
|
||||||
|
proxied register || register${fallbacks}${
|
||||||
|
lib.optionalString (w.generatorUrl != null) " || proxied generate"
|
||||||
}
|
}
|
||||||
''
|
''
|
||||||
else
|
else
|
||||||
"register${lib.optionalString (w.generatorUrl != null) " || generate"}"
|
"register${fallbacks}"
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
|
|
||||||
@@ -88,10 +97,50 @@ let
|
|||||||
server = cfg.proxy.dns.local.address;
|
server = cfg.proxy.dns.local.address;
|
||||||
server_port = cfg.proxy.dns.local.port;
|
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
|
# 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
|
# same source port forever. A new process binds a new port, so the watchdog exits when
|
||||||
# repeated failures and systemd starts the tunnel again.
|
# 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" ''
|
tunnelScript = pkgs.writeShellScript "proxy-suite-warp" ''
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
profile=${lib.escapeShellArg w.profilePath}
|
profile=${lib.escapeShellArg w.profilePath}
|
||||||
@@ -100,29 +149,27 @@ let
|
|||||||
until [ -s "$profile" ]; do sleep 5; done
|
until [ -s "$profile" ]; do sleep 5; done
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# The profile is a secret, so it is converted here rather than baked into the store.
|
# The profile is a secret, so it is converted here, as root, rather than baked into
|
||||||
endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag warp --routing-mark ${toString cfg.proxy.tproxy.proxyMark} < "$profile")
|
# the store; sing-box itself runs as ${serviceUser}.
|
||||||
${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{
|
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"},
|
log: {level: "warn"},
|
||||||
dns: {servers: [${builtins.toJSON dnsServer}]},
|
dns: {servers: [${builtins.toJSON dnsServer}]},
|
||||||
route: {default_domain_resolver: "local", final: "warp"},
|
route: {
|
||||||
inbounds: [{type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString w.tunnelPort}}],
|
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]
|
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" &
|
exec ${runAsServiceUser pkgs [ "net_admin" ]} ${watchdogScript}
|
||||||
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
|
|
||||||
'';
|
'';
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
@@ -145,7 +192,7 @@ in
|
|||||||
Restart = "always";
|
Restart = "always";
|
||||||
RestartSec = 2;
|
RestartSec = 2;
|
||||||
RuntimeDirectory = "proxy-suite-warp-tunnel";
|
RuntimeDirectory = "proxy-suite-warp-tunnel";
|
||||||
RuntimeDirectoryMode = "0700";
|
RuntimeDirectoryMode = "0750";
|
||||||
UMask = "0077";
|
UMask = "0077";
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -161,7 +208,7 @@ in
|
|||||||
# Retried until it registers. Not a oneshot: a slow or failed registration must not
|
# Retried until it registers. Not a oneshot: a slow or failed registration must not
|
||||||
# hold up or fail a switch.
|
# hold up or fail a switch.
|
||||||
startLimitIntervalSec = 0;
|
startLimitIntervalSec = 0;
|
||||||
serviceConfig = {
|
serviceConfig = unprivilegedServiceConfig [ ] // {
|
||||||
Type = "simple";
|
Type = "simple";
|
||||||
RemainAfterExit = true;
|
RemainAfterExit = true;
|
||||||
Restart = "on-failure";
|
Restart = "on-failure";
|
||||||
@@ -170,6 +217,7 @@ in
|
|||||||
StateDirectoryMode = "0700";
|
StateDirectoryMode = "0700";
|
||||||
WorkingDirectory = "/var/lib/proxy-suite/warp";
|
WorkingDirectory = "/var/lib/proxy-suite/warp";
|
||||||
UMask = "0077";
|
UMask = "0077";
|
||||||
|
LoadCredential = lib.optional (cfg.proxy.enable && withProxyAuth) "proxy-password:${passwordSource}";
|
||||||
ExecStart = registerScript;
|
ExecStart = registerScript;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -70,6 +70,9 @@ let
|
|||||||
homeService = awgOnly.config.systemd.services.proxy-suite-awg-home;
|
homeService = awgOnly.config.systemd.services.proxy-suite-awg-home;
|
||||||
workService = awgOnly.config.systemd.services.proxy-suite-awg-work;
|
workService = awgOnly.config.systemd.services.proxy-suite-awg-work;
|
||||||
ctl = mkProxyCtlDerived awgOnly;
|
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 [
|
sourceFixture = evalProxySuite [
|
||||||
{
|
{
|
||||||
@@ -190,6 +193,12 @@ in
|
|||||||
assert homeService.serviceConfig.NoNewPrivileges;
|
assert homeService.serviceConfig.NoNewPrivileges;
|
||||||
assert builtins.length homeService.serviceConfig.ExecStartPre == 1;
|
assert builtins.length homeService.serviceConfig.ExecStartPre == 1;
|
||||||
assert !(homeService.serviceConfig ? ExecStopPost);
|
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
|
true
|
||||||
)
|
)
|
||||||
(
|
(
|
||||||
|
|||||||
@@ -104,7 +104,11 @@ in
|
|||||||
assert pkgs.lib.hasInfix ''--arg password "$LOCAL_PROXY_PASSWORD"'' localProxyAuthStartScript;
|
assert pkgs.lib.hasInfix ''--arg password "$LOCAL_PROXY_PASSWORD"'' localProxyAuthStartScript;
|
||||||
assert pkgs.lib.hasInfix ''select(.type == "mixed" and .tag == "mixed-in") | .users''
|
assert pkgs.lib.hasInfix ''select(.type == "mixed" and .tag == "mixed-in") | .users''
|
||||||
localProxyAuthBackendJqFilter;
|
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
|
true
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -53,7 +53,6 @@ let
|
|||||||
server = "ssh.example.com";
|
server = "ssh.example.com";
|
||||||
server_port = 22;
|
server_port = 22;
|
||||||
user = "root";
|
user = "root";
|
||||||
private_key_path = "/run/secrets/ssh-key";
|
|
||||||
host_key = [ testHostKey ];
|
host_key = [ testHostKey ];
|
||||||
routing_mark = markOf sshNativeSingBox;
|
routing_mark = markOf sshNativeSingBox;
|
||||||
};
|
};
|
||||||
@@ -367,6 +366,9 @@ let
|
|||||||
)
|
)
|
||||||
(
|
(
|
||||||
assert pkgs.lib.hasInfix expectedNativeSingBoxOutbound sshNativeSingBoxStart;
|
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
|
true
|
||||||
)
|
)
|
||||||
# The global local-resolve route rule is gone; the native outbound resolves.
|
# The global local-resolve route rule is gone; the native outbound resolves.
|
||||||
@@ -441,7 +443,16 @@ let
|
|||||||
true
|
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
|
true
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ let
|
|||||||
tgWithGlobalTunServiceConfig
|
tgWithGlobalTunServiceConfig
|
||||||
tgWithGlobalTunBypassUp
|
tgWithGlobalTunBypassUp
|
||||||
tgWithGlobalTunBypassDown
|
tgWithGlobalTunBypassDown
|
||||||
|
tgWithGlobalTunModule
|
||||||
tgWithGlobalTunRules
|
tgWithGlobalTunRules
|
||||||
tgWithGlobalTproxyNft
|
tgWithGlobalTproxyNft
|
||||||
invalidTgWsProxyAssertions
|
invalidTgWsProxyAssertions
|
||||||
@@ -81,6 +82,10 @@ in
|
|||||||
# Global TUN/TProxy bypass mark keeps relay traffic out of transparent capture.
|
# Global TUN/TProxy bypass mark keeps relay traffic out of transparent capture.
|
||||||
(
|
(
|
||||||
assert !(tgWithGlobalTunServiceConfig ? SocketMark);
|
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 "\"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 "delete table inet proxy_suite_tg_ws_proxy" tgWithGlobalTunBypassDown;
|
||||||
assert pkgs.lib.hasInfix "rule add pref 8999 fwmark 4 lookup main" tgWithGlobalTunBypassUp;
|
assert pkgs.lib.hasInfix "rule add pref 8999 fwmark 4 lookup main" tgWithGlobalTunBypassUp;
|
||||||
|
|||||||
@@ -66,8 +66,19 @@ let
|
|||||||
];
|
];
|
||||||
tgWithGlobalTunServiceConfig =
|
tgWithGlobalTunServiceConfig =
|
||||||
tgWithGlobalTun.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig;
|
tgWithGlobalTun.config.systemd.services."proxy-suite-tg-ws-proxy".serviceConfig;
|
||||||
tgWithGlobalTunBypassUp = generated.readDerivation tgWithGlobalTunServiceConfig.ExecStartPre;
|
tgWithGlobalTunModule =
|
||||||
tgWithGlobalTunBypassDown = generated.readDerivation tgWithGlobalTunServiceConfig.ExecStopPost;
|
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;
|
tgWithGlobalTunRules = mkRoutingRules tgWithGlobalTun;
|
||||||
|
|
||||||
tgWithGlobalTproxy = evalProxySuite [
|
tgWithGlobalTproxy = evalProxySuite [
|
||||||
@@ -134,6 +145,7 @@ in
|
|||||||
tgWithGlobalTunServiceConfig
|
tgWithGlobalTunServiceConfig
|
||||||
tgWithGlobalTunBypassUp
|
tgWithGlobalTunBypassUp
|
||||||
tgWithGlobalTunBypassDown
|
tgWithGlobalTunBypassDown
|
||||||
|
tgWithGlobalTunModule
|
||||||
tgWithGlobalTunRules
|
tgWithGlobalTunRules
|
||||||
tgWithGlobalTproxyNft
|
tgWithGlobalTproxyNft
|
||||||
invalidTgWsProxyAssertions
|
invalidTgWsProxyAssertions
|
||||||
|
|||||||
@@ -109,6 +109,18 @@ let
|
|||||||
asAmneziaWg = true;
|
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.
|
# Tag collision with a declared outbound.
|
||||||
{
|
{
|
||||||
enable = true;
|
enable = true;
|
||||||
@@ -203,6 +215,23 @@ in
|
|||||||
&& !(hasInfix "generate()" autoRegister);
|
&& !(hasInfix "generate()" autoRegister);
|
||||||
true
|
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;
|
assert amneziaWg.config.services.proxy-suite.amneziaWg.profiles.warp.configFile == profile;
|
||||||
true
|
true
|
||||||
|
|||||||
+65
-84
@@ -284,17 +284,38 @@ def _set_interface_value(config: str, key: str, value: str) -> str:
|
|||||||
return "\n".join(lines) + "\n"
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
|
||||||
def _interface_keys(config: str) -> set[str]:
|
def conf_sections(config: str) -> list[tuple[str, list[tuple[str, str]]]]:
|
||||||
keys: set[str] = set()
|
"""Each [Section] of a WireGuard .conf, lowercased, with its key = value lines in order.
|
||||||
in_interface = False
|
|
||||||
|
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():
|
for line in config.splitlines():
|
||||||
stripped = line.split("#", 1)[0].split(";", 1)[0].strip()
|
stripped = line.split("#", 1)[0].split(";", 1)[0].strip()
|
||||||
if stripped.startswith("[") and stripped.endswith("]"):
|
if stripped.startswith("[") and stripped.endswith("]"):
|
||||||
in_interface = stripped.lower() == "[interface]"
|
sections.append((stripped[1:-1].strip().lower(), []))
|
||||||
continue
|
elif "=" in stripped and sections:
|
||||||
if in_interface and "=" in stripped:
|
key, value = (part.strip() for part in stripped.split("=", 1))
|
||||||
key = stripped.split("=", 1)[0].strip()
|
sections[-1][1].append((key.lower(), value))
|
||||||
keys.add(re.sub(r"[^a-z0-9]", "", key.lower()))
|
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
|
return keys
|
||||||
|
|
||||||
|
|
||||||
@@ -443,39 +464,15 @@ def render_settings(settings: dict[str, Any]) -> str:
|
|||||||
lines.append(f"{target} = {settings[source]}")
|
lines.append(f"{target} = {settings[source]}")
|
||||||
|
|
||||||
obfuscation = _merge_obfuscation(settings)
|
obfuscation = _merge_obfuscation(settings)
|
||||||
obfuscation_map = {
|
# Option names are the config keys in camelCase; the key comes last, from its secret.
|
||||||
"jc": "Jc",
|
values = {key.lower(): value for key, value in obfuscation.items()}
|
||||||
"jmin": "Jmin",
|
for normalized, target in VPN_INTERFACE_FIELDS.items():
|
||||||
"jmax": "Jmax",
|
value = values.get(normalized)
|
||||||
"s1": "S1",
|
if normalized == "headerprotectionkey" or value is None:
|
||||||
"s2": "S2",
|
continue
|
||||||
"s3": "S3",
|
if isinstance(value, bool):
|
||||||
"s4": "S4",
|
value = "on" if value else "off"
|
||||||
"h1": "H1",
|
lines.append(f"{target} = {value}")
|
||||||
"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'}")
|
|
||||||
if obfuscation.get("headerProtectionKey") is not None or obfuscation.get(
|
if obfuscation.get("headerProtectionKey") is not None or obfuscation.get(
|
||||||
"headerProtectionKeyFile"
|
"headerProtectionKeyFile"
|
||||||
) is not None:
|
) is not None:
|
||||||
@@ -531,17 +528,7 @@ def validate_config(config: str, allow_hooks: bool = False) -> None:
|
|||||||
def probe_address(config: str) -> str:
|
def probe_address(config: str) -> str:
|
||||||
"""Return an address covered by a peer route without exposing credentials."""
|
"""Return an address covered by a peer route without exposing credentials."""
|
||||||
networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network] = []
|
networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network] = []
|
||||||
in_peer = False
|
for value in section_values(config, "peer", "allowedips"):
|
||||||
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 item in value.split(","):
|
for item in value.split(","):
|
||||||
try:
|
try:
|
||||||
networks.append(ipaddress.ip_network(item.strip(), strict=False))
|
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:
|
def transport_implementation(config: str) -> str:
|
||||||
"""Select userspace for the upstream RandomTrailers/ranged-header defect."""
|
"""Select userspace for the upstream RandomTrailers/ranged-header defect."""
|
||||||
random_trailers = False
|
trailers = section_values(config, "interface", "randomtrailers")
|
||||||
ranged_handshake_header = False
|
random_trailers = bool(trailers) and trailers[-1].lower() in {"on", "true", "yes", "1"}
|
||||||
in_interface = False
|
ranged_handshake_header = any(
|
||||||
for line in config.splitlines():
|
re.fullmatch(r"[0-9]+\s*-\s*[0-9]+", value) is not None
|
||||||
stripped = line.split("#", 1)[0].split(";", 1)[0].strip()
|
for key in ("h1", "h2", "h3")
|
||||||
if stripped.startswith("[") and stripped.endswith("]"):
|
for value in section_values(config, "interface", key)
|
||||||
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
|
|
||||||
return "userspace" if random_trailers and ranged_handshake_header else "auto"
|
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:
|
def prepare(manifest: dict[str, Any]) -> str:
|
||||||
kind = manifest.get("kind")
|
kind = manifest.get("kind")
|
||||||
if kind == "configFile":
|
if kind == "configFile":
|
||||||
@@ -619,25 +607,18 @@ def main() -> int:
|
|||||||
parser = argparse.ArgumentParser(description=__doc__)
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
parser.add_argument("--manifest")
|
parser.add_argument("--manifest")
|
||||||
parser.add_argument("--output")
|
parser.add_argument("--output")
|
||||||
parser.add_argument("--probe-address")
|
parser.add_argument(
|
||||||
parser.add_argument("--transport-implementation")
|
"--inspect",
|
||||||
|
metavar="CONFIG",
|
||||||
|
help="print the transport implementation, a probe address and the rekey interval",
|
||||||
|
)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
try:
|
try:
|
||||||
if args.probe_address is not None:
|
if args.inspect 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.manifest is not None or args.output is not None:
|
if args.manifest is not None or args.output is not None:
|
||||||
raise ConfigError(
|
raise ConfigError("--inspect cannot be combined with rendering options")
|
||||||
"--transport-implementation cannot be combined with rendering options"
|
config = _read_limited(args.inspect)
|
||||||
)
|
print(transport_implementation(config), probe_address(config), rekey_after_time(config))
|
||||||
print(transport_implementation(_read_limited(args.transport_implementation)))
|
|
||||||
return 0
|
return 0
|
||||||
if args.manifest is None or args.output is None:
|
if args.manifest is None or args.output is None:
|
||||||
raise ConfigError("--manifest and --output are required when rendering a configuration")
|
raise ConfigError("--manifest and --output are required when rendering a configuration")
|
||||||
|
|||||||
@@ -10,12 +10,14 @@ import zlib
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import amneziawg_config
|
||||||
from amneziawg_config import (
|
from amneziawg_config import (
|
||||||
ConfigError,
|
ConfigError,
|
||||||
decode_vpn_link,
|
decode_vpn_link,
|
||||||
extract_vpn_config,
|
extract_vpn_config,
|
||||||
prepare,
|
prepare,
|
||||||
probe_address,
|
probe_address,
|
||||||
|
rekey_after_time,
|
||||||
render_settings,
|
render_settings,
|
||||||
transport_implementation,
|
transport_implementation,
|
||||||
validate_config,
|
validate_config,
|
||||||
@@ -415,6 +417,25 @@ class AmneziaWgConfigTests(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.assertEqual(probe_address(config), "10.23.42.1")
|
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):
|
def test_random_trailers_with_ranged_handshake_headers_forces_userspace(self):
|
||||||
config = BASE_CONFIG.replace(
|
config = BASE_CONFIG.replace(
|
||||||
"ContentPaddingAddition = 8-16",
|
"ContentPaddingAddition = 8-16",
|
||||||
|
|||||||
@@ -8,23 +8,14 @@ import json
|
|||||||
import sys
|
import sys
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from amneziawg_config import ConfigError, conf_sections
|
||||||
class ConfigError(ValueError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def parse_conf(text: str) -> tuple[dict[str, str], dict[str, str]]:
|
def parse_conf(text: str) -> tuple[dict[str, str], dict[str, str]]:
|
||||||
"""Return the [Interface] section and the first [Peer], keys lowercased."""
|
"""Return the [Interface] section and the first [Peer], keys lowercased."""
|
||||||
sections: list[tuple[str, dict[str, str]]] = []
|
sections = conf_sections(text)
|
||||||
for line in text.splitlines():
|
interface = next((dict(pairs) for name, pairs in sections if name == "interface"), None)
|
||||||
stripped = line.split("#", 1)[0].strip()
|
peer = next((dict(pairs) for name, pairs in sections if name == "peer"), None)
|
||||||
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)
|
|
||||||
if interface is None or peer is None:
|
if interface is None or peer is None:
|
||||||
raise ConfigError("configuration requires [Interface] and [Peer] sections")
|
raise ConfigError("configuration requires [Interface] and [Peer] sections")
|
||||||
for section, key in ((interface, "privatekey"), (interface, "address"), (peer, "publickey"), (peer, "endpoint")):
|
for section, key in ((interface, "privatekey"), (interface, "address"), (peer, "publickey"), (peer, "endpoint")):
|
||||||
@@ -78,7 +69,7 @@ def main() -> int:
|
|||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
try:
|
try:
|
||||||
print(json.dumps(build(sys.stdin.read(), args.tag, args.routing_mark)))
|
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)
|
print(f"proxy-suite: warp: {error}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
Reference in new issue
Block a user