fix: hardening and fixes

This commit is contained in:
fufsob committed 2026-09-15 08:56:33 +00:00
1 parent aa19042ee5
commit a82417a2bd
32 files changed
+619 -256

No files matched your search

+130 -56
View File
@@ -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;
})
+2
View File
@@ -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
''
+7 -4
View File
@@ -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; };
+4 -2
View File
@@ -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
;
}
))
+43
View File
@@ -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.
+8 -1
View File
@@ -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.
'';
};
};
}
+3 -3
View File
@@ -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";
};
+2 -2
View File
@@ -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 {
+5 -3
View File
@@ -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.
'';
};
};
@@ -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"
)
+9
View File
@@ -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
@@ -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.
@@ -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
+1
View File
@@ -111,6 +111,7 @@ let
proxyCfg
sshProxyCfg
warpCfg
constants
pureXrayEnabled
hybridEnabled
collapseNamedOutbounds
+14 -8
View File
@@ -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"
''
}
'';
+32 -16
View File
@@ -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;
};
};
}
+24 -11
View File
@@ -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}";
};
};
}
+79 -31
View File
@@ -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;
};
};