feat/wip: better awg to outbounds config

This commit is contained in:
fufsob committed 2026-09-15 10:34:42 +00:00
1 parent a82417a2bd
commit 9c9658baa7
26 files changed
+805 -218

No files matched your search

+108 -35
View File
@@ -4,17 +4,23 @@
lib,
pkgs,
cfg,
derived,
}:
let
awgCfg = cfg.amneziaWg;
profiles = awgCfg.profiles;
profileNames = builtins.attrNames profiles;
globalProfileNames = builtins.attrNames derived.awgGlobalProfiles;
singBoxOutbounds = builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds;
serviceName = name: "proxy-suite-awg-${name}";
serviceNames = map serviceName profileNames;
globalServiceNames = map serviceName globalProfileNames;
allProfileConflicts =
name:
map (other: "${serviceName other}.service") (builtins.filter (other: other != name) profileNames);
map (other: "${serviceName other}.service") (
builtins.filter (other: other != name) globalProfileNames
);
inherit (import ./wg-tunnel.nix { inherit lib pkgs cfg derived; }) mkTunnel;
sourceCount =
profile:
builtins.length (
@@ -100,16 +106,31 @@ let
}
'';
# `ping` for the handshake probe. An outbound interface has no route to the probe address, so
# the probe is bound to it.
pingVia =
profile:
"${pkgs.iputils}/bin/ping -n -c 1"
+ lib.optionalString (profile.asOutbound == "interface") " -I ${lib.escapeShellArg profile.interfaceName}";
# An outbound interface keeps the host's routes and resolver, and marks its packets so TUN and
# TProxy let them past.
prepareCommand = profile: output: ''
${pkgs.python3}/bin/python3 ${configTool} \
--manifest ${lib.escapeShellArg (toString (manifestFor profile))} \
--output ${output}${
lib.optionalString (profile.asOutbound == "interface") " --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}"
}
'';
mkService =
name: profile:
let
manifest = manifestFor profile;
outbound = profile.asOutbound == "interface";
configPath = runtimeConfig name profile;
prepare = pkgs.writeShellScript "proxy-suite-awg" ''
set -euo pipefail
${pkgs.python3}/bin/python3 ${configTool} \
--manifest ${lib.escapeShellArg (toString manifest)} \
--output ${lib.escapeShellArg configPath}
${prepareCommand profile (lib.escapeShellArg configPath)}
'';
proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" ''
set -euo pipefail
@@ -176,7 +197,7 @@ let
${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
${pingVia profile} -W 1 "$probe" >/dev/null 2>&1 || true
if (( $(handshake_age) < 1000000 )); then
trap - ERR
exit 0
@@ -194,24 +215,38 @@ let
exec ${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath}
'';
in
{
description = "proxy-suite AmneziaWG client profile ${name}";
# Start the local proxy before AWG takes the default route, so HTTP_PROXY clients
# do not race it.
after = [
"network-online.target"
"proxy-suite-zapret.service"
]
++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
wantedBy = lib.optionals profile.autostart [ "multi-user.target" ];
conflicts = allProfileConflicts name ++ [
"proxy-suite-tun.service"
"proxy-suite-tproxy.service"
"proxy-suite-zapret.service"
"proxy-suite-per-app-zapret.service"
"proxy-suite-zapret-vm-exempt.service"
];
(
if outbound then
{
description = "proxy-suite AmneziaWG interface behind the ${name} outbound";
# Nothing waits for it: a slow handshake must not hold up the proxy.
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
startLimitIntervalSec = 0;
}
else
{
description = "proxy-suite AmneziaWG client profile ${name}";
# Start the local proxy before AWG takes the default route, so HTTP_PROXY clients
# do not race it.
after = [
"network-online.target"
"proxy-suite-zapret.service"
]
++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
wantedBy = lib.optionals profile.autostart [ "multi-user.target" ];
conflicts = allProfileConflicts name ++ [
"proxy-suite-tun.service"
"proxy-suite-tproxy.service"
"proxy-suite-zapret.service"
"proxy-suite-per-app-zapret.service"
"proxy-suite-zapret-vm-exempt.service"
];
}
)
// {
path = [
awgCfg.toolsPackage
awgCfg.userspacePackage
@@ -237,15 +272,35 @@ let
ProtectKernelLogs = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
ExecStartPre = [ prepare ] ++ lib.optionals cfg.proxy.enable [ proxyBypassUp ];
ExecStartPre = [ prepare ] ++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ];
ExecStart = start;
ExecStop = stop;
}
// lib.optionalAttrs cfg.proxy.enable {
// lib.optionalAttrs (cfg.proxy.enable && !outbound) {
ExecStopPost = proxyBypassDown;
}
# A failed handshake leaves no routes behind here, so try again later.
// lib.optionalAttrs outbound {
Restart = "on-failure";
RestartSec = 30;
};
};
mkSingBoxService =
ob:
let
profile = profiles.${ob.name};
in
mkTunnel {
description = "proxy-suite AmneziaWG tunnel behind the ${ob.name} outbound";
unit = serviceName ob.name;
inherit (ob) tag tunnelPort directPort;
profile = ''
profile="$RUNTIME_DIRECTORY/profile.conf"
${prepareCommand profile ''"$profile"''}
'';
};
# 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
@@ -264,7 +319,7 @@ let
${mkHandshakeHelpers profile}
stale=0
while sleep 15; do
${pkgs.iputils}/bin/ping -n -c 1 -W 2 "$probe" >/dev/null 2>&1 || true
${pingVia profile} -W 2 "$probe" >/dev/null 2>&1 || true
if (( $(handshake_age) <= rekey + 10 )); then
stale=0
elif (( ++stale >= 2 )); then
@@ -323,6 +378,18 @@ let
assertion = profile.vpnContainer == null || profile.vpn != null || profile.vpnFile != null;
message = "proxy-suite: AmneziaWG profile '${name}': vpnContainer requires vpn or vpnFile";
}
{
assertion = profile.asOutbound == null || cfg.proxy.enable;
message = "proxy-suite: AmneziaWG profile '${name}': asOutbound requires proxy.enable = true";
}
{
assertion = profile.asOutbound == null || !profile.autostart;
message = "proxy-suite: AmneziaWG profile '${name}': an outbound always runs; leave autostart off";
}
{
assertion = profile.asOutbound != "interface" || settings == null || settings.table == null;
message = "proxy-suite: AmneziaWG profile '${name}': an outbound interface has no routes; leave settings.table unset";
}
{
assertion = settings == null || settings.addresses != [ ];
message = "proxy-suite: AmneziaWG profile '${name}': declarative settings require at least one address";
@@ -353,7 +420,7 @@ let
) profileNames;
interfaceNames = map (name: profiles.${name}.interfaceName) profileNames;
autostartProfiles = builtins.filter (name: profiles.${name}.autostart) profileNames;
autostartProfiles = builtins.filter (name: profiles.${name}.autostart) globalProfileNames;
globalAutostartCount = builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
in
{
@@ -366,18 +433,24 @@ in
awgCfg.kernelModulePackage
];
# Replies to the proxy's sockets come in on an interface the host has no route through.
networking.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: ''
iifname "${ob.interface}" accept
'') derived.awgInterfaceOutbounds;
systemd.services = lib.mkMerge [
(lib.mapAttrs' (
name: profile: lib.nameValuePair (serviceName name) (mkService name profile)
) profiles)
(lib.mapAttrs' (name: profile: lib.nameValuePair (serviceName name) (mkService name profile)) (
lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles
))
(lib.mapAttrs' (
name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile)
) profiles)
) (lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles))
(lib.listToAttrs (map (ob: lib.nameValuePair (serviceName ob.name) (mkSingBoxService ob)) singBoxOutbounds))
(lib.mkIf cfg.proxy.tun.enable {
proxy-suite-tun.conflicts = map (name: "${name}.service") serviceNames;
proxy-suite-tun.conflicts = map (name: "${name}.service") globalServiceNames;
})
(lib.mkIf cfg.proxy.tproxy.enable {
proxy-suite-tproxy.conflicts = map (name: "${name}.service") serviceNames;
proxy-suite-tproxy.conflicts = map (name: "${name}.service") globalServiceNames;
})
];
@@ -37,12 +37,21 @@ let
mkDnsConfig =
{
localDetour ? null,
useOutboundRoutingMark ? false,
}:
{
servers = [
(mkDnsServer "remote" proxyCfg.dns.remote "proxy")
(mkDnsServer "local" proxyCfg.dns.local localDetour)
];
]
++ map (
ob:
mkDnsServer (constants.awgDnsServerTag ob.tag) proxyCfg.dns.remote null
// {
bind_interface = ob.interface;
}
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
) derived.awgInterfaceOutbounds;
rules =
lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
rule_set = [ "geosite-google" ];
@@ -93,6 +102,7 @@ let
dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
inherit useOutboundRoutingMark;
};
inbounds =
+1
View File
@@ -183,6 +183,7 @@ in
lib
pkgs
cfg
derived
;
}
))
+35 -3
View File
@@ -48,7 +48,28 @@ let
directPort = 18539;
};
warpOutboundTag = "warp";
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound;
# The sing-box tunnel; asOutbound = "interface" comes in through the AmneziaWG profile list.
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound == "singBox";
# AmneziaWG profiles are either global (proxy-ctl awg on) or outbounds tagged with their name.
awgProfiles = lib.optionalAttrs cfg.amneziaWg.enable cfg.amneziaWg.profiles;
awgGlobalProfiles = lib.filterAttrs (_: profile: profile.asOutbound == null) awgProfiles;
awgOutbounds = lib.imap0 (
index: name:
let
profile = awgProfiles.${name};
in
{
inherit name;
tag = name;
kind = profile.asOutbound;
interface = profile.interfaceName;
# Loopback listeners of a "singBox" tunnel, as warpCfg.tunnelPort/directPort.
tunnelPort = 18540 + 2 * index;
directPort = 18541 + 2 * index;
}
) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles));
awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds;
proxyInboundsCfg = cfg.inbounds;
proxyInboundsEnabled = proxyInboundsCfg.enable;
@@ -130,13 +151,18 @@ let
effectiveOutboundTags =
outboundTags
++ lib.optional sshProxyOutboundEnabled sshProxyOutboundTag
++ lib.optional warpOutboundEnabled warpOutboundTag;
++ lib.optional warpOutboundEnabled warpOutboundTag
++ map (ob: ob.tag) awgOutbounds;
subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions;
hasStaticOutbounds = proxyCfg.outbounds != [ ];
hasSubscriptions = proxyCfg.subscriptions != [ ];
hasAvailableOutbounds =
hasStaticOutbounds || hasSubscriptions || sshProxyOutboundEnabled || warpOutboundEnabled;
hasStaticOutbounds
|| hasSubscriptions
|| sshProxyOutboundEnabled
|| warpOutboundEnabled
|| awgOutbounds != [ ];
collapseNamedOutbounds = selectionMode == "first";
# Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode.
clashApiEnabled = singBoxEnabled;
@@ -220,6 +246,9 @@ let
outboundTestPort = 18537;
inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json";
# sing-box DNS server resolving through an "interface" AmneziaWG outbound.
awgDnsServerTag = tag: "awg-dns-${tag}";
tunAutoRouteTableIndex = 2022;
tunAutoRouteRulePriority = 9000;
xrayTunPerAppTproxyRulePriority = 8996;
@@ -289,6 +318,9 @@ in
warpCfg
warpOutboundTag
warpOutboundEnabled
awgGlobalProfiles
awgOutbounds
awgInterfaceOutbounds
proxyInboundsCfg
proxyInboundsEnabled
proxyInbounds
@@ -269,6 +269,26 @@ let
default = false;
description = "Whether to start this profile at boot. At most one profile may autostart.";
};
asOutbound = mkOption {
type = types.nullOr (
types.enum [
"singBox"
"interface"
]
);
default = null;
description = ''
Make the profile a proxy outbound tagged with its name instead of a global profile. It then
always runs, leaves the host's routes and resolver alone, and is not listed by
`proxy-ctl awg`. Requires proxy.enable.
- "singBox": a WireGuard endpoint in its own sing-box process, reached as a loopback SOCKS
hop. sing-box speaks plain WireGuard: AmneziaWG obfuscation is dropped with a warning.
- "interface": the AmneziaWG interface comes up without routes (Table = off), and the
outbound binds to it, so obfuscation works. With the sing-box backend its DNS goes
through the interface too (proxy.dns.remote); XRay resolves as usual.
Either way the tunnel itself reaches the peer over the uplink, past TUN and TProxy.
'';
};
allowConfigHooks = mkOption {
type = types.bool;
default = false;
+16 -7
View File
@@ -12,7 +12,8 @@ in
default = null;
description = ''
Runtime path to a WireGuard profile for WARP, as written by `wgcf register && wgcf generate`.
AmneziaWG lines (Jc, S1-S4, H1-H4, I1-I5, AWG 3 timing) 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
(asAmneziaWg, asOutbound = "interface") only.
When null, proxy-suite-warp registers a device with wgcf (accepting Cloudflare's terms)
into /var/lib/proxy-suite/warp, through the local proxy when proxy.enable is set, and
@@ -35,13 +36,21 @@ in
};
asOutbound = mkOption {
type = types.bool;
default = false;
type = types.nullOr (
types.enum [
"singBox"
"interface"
]
);
default = null;
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, 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.
Add WARP as an outbound tagged "warp".
- "singBox": a SOCKS hop to proxy-suite-warp-tunnel, which 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.
- "interface": an AmneziaWG profile named "warp" with asOutbound = "interface", which honours
the AmneziaWG lines of the profile. Requires amneziaWg.enable.
'';
};
+6 -3
View File
@@ -74,19 +74,22 @@ let
"proxy-suite: sshProxy.asOutbound requires proxy.enable = true"
)
(mkAssertion (
!cfg.warp.enable || cfg.warp.asOutbound || cfg.warp.asAmneziaWg
!cfg.warp.enable || cfg.warp.asOutbound != null || 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))
(mkAssertion (!(cfg.warp.enable && cfg.warp.asOutbound != null && 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 (cfg.warp.enable && cfg.warp.asOutbound != null) proxyEnabled
"proxy-suite: warp.asOutbound requires proxy.enable = true"
)
(requireEnabled (
cfg.warp.enable && cfg.warp.asOutbound == "interface"
) cfg.amneziaWg.enable ''proxy-suite: warp.asOutbound = "interface" requires amneziaWg.enable = true'')
(requireEnabled (
cfg.warp.enable && cfg.warp.asAmneziaWg
) cfg.amneziaWg.enable "proxy-suite: warp.asAmneziaWg requires amneziaWg.enable = true")
+6 -1
View File
@@ -50,6 +50,7 @@ let
sshProxyOutboundEnabled
sshProxyUnitEnabled
warpCfg
awgOutbounds
proxyInboundsCfg
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
@@ -69,8 +70,11 @@ let
headBin = "${pkgs.coreutils}/bin/head";
seqBin = "${pkgs.coreutils}/bin/seq";
findBin = "${pkgs.findutils}/bin/find";
# `proxy-ctl awg` toggles global profiles; outbound ones always run and show up with the proxy.
amneziaWgProfileNamesFile = pkgs.writeText "proxy-suite-core" (
builtins.toJSON (builtins.attrNames cfg.amneziaWg.profiles)
builtins.toJSON (
builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles)
)
);
proxySuiteScriptsDir = builtins.path {
@@ -96,6 +100,7 @@ let
proxyCfg
sshProxyCfg
warpCfg
awgOutbounds
xrayEnabled
hybridEnabled
pureXrayEnabled
@@ -5,6 +5,7 @@
proxyCfg,
sshProxyCfg,
warpCfg,
awgOutbounds,
constants,
pureXrayEnabled,
hybridEnabled,
@@ -370,39 +371,72 @@ let
_proxy_suite_record_tag_source ${sshProxyTag} ssh
'';
# WARP runs in proxy-suite-warp-tunnel, which restarts it when the handshake stops being
# answered. Every backend reaches it as a loopback SOCKS hop.
mkWarpOutboundBlock =
let
outbound =
if pureXrayEnabled then
{
protocol = "socks";
tag = "warp";
settings = {
address = "127.0.0.1";
port = warpCfg.tunnelPort;
};
}
else
{
type = "socks";
tag = "warp";
server = "127.0.0.1";
server_port = warpCfg.tunnelPort;
# Outbounds whose JSON is known at build time: every backend takes it as is.
mkFixedOutboundBlock = comment: source: outbound: ''
# outbound: ${outbound.tag} (${comment})
OB_JSON=${lib.escapeShellArg (builtins.toJSON outbound)}
${
if hybridEnabled then
''_proxy_suite_add_sing_box_ob "$OB_JSON"''
else
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
}
_proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source}
'';
# WARP and "singBox" AmneziaWG profiles run in a tunnel unit, which restarts them when the
# handshake stops being answered. Every backend reaches it as a loopback SOCKS hop.
mkTunnelOutboundBlock =
unit: source: tag: port:
mkFixedOutboundBlock "SOCKS hop to ${unit}" source (
if pureXrayEnabled then
{
protocol = "socks";
inherit tag;
settings = {
address = "127.0.0.1";
inherit port;
};
in
''
# outbound: warp (SOCKS hop to proxy-suite-warp-tunnel)
OB_JSON=${lib.escapeShellArg (builtins.toJSON outbound)}
${
if hybridEnabled then
''_proxy_suite_add_sing_box_ob "$OB_JSON"''
else
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
}
_proxy_suite_record_tag_source warp warp
'';
}
else
{
type = "socks";
inherit tag;
server = "127.0.0.1";
server_port = port;
}
);
# An "interface" AmneziaWG profile: the outbound binds to the interface, which has no routes.
# sing-box resolves its destinations through it too; XRay resolves as usual.
mkInterfaceOutboundBlock =
routingMark: ob:
mkFixedOutboundBlock "bound to ${ob.interface}" "awg" (
if pureXrayEnabled then
{
protocol = "freedom";
inherit (ob) tag;
streamSettings.sockopt = {
inherit (ob) interface;
}
// lib.optionalAttrs (routingMark != null) { mark = routingMark; };
}
else
{
type = "direct";
inherit (ob) tag;
bind_interface = ob.interface;
domain_resolver = constants.awgDnsServerTag ob.tag;
}
// lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }
);
mkAwgOutboundBlock =
routingMark: ob:
if ob.kind == "interface" then
mkInterfaceOutboundBlock routingMark ob
else
mkTunnelOutboundBlock "proxy-suite-awg-${ob.name}" "awg" ob.tag ob.tunnelPort;
mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock;
@@ -464,7 +498,10 @@ let
) proxyCfg.subscriptions;
sshProxyBlock = lib.optionalString sshProxyCfg.asOutbound (mkSshProxyOutboundBlock routingMark);
warpBlock = lib.optionalString (warpCfg.enable && warpCfg.asOutbound) mkWarpOutboundBlock;
warpBlock = lib.optionalString (warpCfg.enable && warpCfg.asOutbound == "singBox") (
mkTunnelOutboundBlock "proxy-suite-warp-tunnel" "warp" "warp" warpCfg.tunnelPort
);
awgBlocks = lib.concatMapStrings (mkAwgOutboundBlock routingMark) awgOutbounds;
wrapperBlock =
if pureXrayEnabled && selectionMode == "urltest" then
@@ -534,6 +571,7 @@ let
+ runtimeOutboundsBlock
+ sshProxyBlock
+ warpBlock
+ awgBlocks
+ requireOutboundsBlock
+ pinBlock
+ inventoryBlock
+2
View File
@@ -6,6 +6,7 @@
proxyCfg,
sshProxyCfg,
warpCfg,
awgOutbounds,
xrayEnabled,
hybridEnabled,
pureXrayEnabled,
@@ -111,6 +112,7 @@ let
proxyCfg
sshProxyCfg
warpCfg
awgOutbounds
constants
pureXrayEnabled
hybridEnabled
+22 -108
View File
@@ -1,5 +1,5 @@
# Cloudflare WARP: the tunnel behind the "warp" outbound, the AmneziaWG profile and, without a
# configFile, wgcf registration.
# Cloudflare WARP: the sing-box tunnel or AmneziaWG profile behind the "warp" outbound, the global
# AmneziaWG profile and, without a configFile, wgcf registration.
{
lib,
pkgs,
@@ -9,13 +9,9 @@
let
w = derived.warpCfg;
inherit (derived.constants) serviceUser runAsServiceUser unprivilegedServiceConfig;
inherit (derived.constants) unprivilegedServiceConfig;
listener = cfg.proxy.listener;
auth = listener.auth;
scriptsDir = builtins.path {
name = "proxy-suite-scripts";
path = ../../scripts;
};
host =
if
builtins.elem listener.address [
@@ -89,112 +85,30 @@ let
}
'';
# sing-box's "local" server has no upstream on hosts behind systemd-resolved, so the tunnel
# resolves like the main config: the peer hostname and destinations go to proxy.dns.local.
dnsServer = {
tag = "local";
type = cfg.proxy.dns.local.type;
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 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}
if [ ! -s "$profile" ]; then
echo "proxy-suite: waiting for the WARP profile at $profile" >&2
until [ -s "$profile" ]; do sleep 5; done
fi
# 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",
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")
${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/config.json"
exec ${runAsServiceUser pkgs [ "net_admin" ]} ${watchdogScript}
'';
inherit (import ./wg-tunnel.nix { inherit lib pkgs cfg derived; }) mkTunnel;
in
{
services.proxy-suite.amneziaWg.profiles = lib.mkIf w.asAmneziaWg {
warp.configFile = w.profilePath;
services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") {
warp = {
configFile = w.profilePath;
asOutbound = lib.mkIf (w.asOutbound == "interface") "interface";
};
};
systemd.services = lib.mkMerge [
(lib.mkIf w.asOutbound {
proxy-suite-warp-tunnel = {
(lib.mkIf (w.asOutbound == "singBox") {
proxy-suite-warp-tunnel = mkTunnel {
description = "proxy-suite - Cloudflare WARP tunnel behind the warp outbound";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
# Probe-triggered restarts must not trip the start limit.
startLimitIntervalSec = 0;
serviceConfig = {
Type = "simple";
ExecStart = tunnelScript;
Restart = "always";
RestartSec = 2;
RuntimeDirectory = "proxy-suite-warp-tunnel";
RuntimeDirectoryMode = "0750";
UMask = "0077";
};
unit = "proxy-suite-warp-tunnel";
tag = "warp";
profile = ''
profile=${lib.escapeShellArg w.profilePath}
if [ ! -s "$profile" ]; then
echo "proxy-suite: waiting for the WARP profile at $profile" >&2
until [ -s "$profile" ]; do sleep 5; done
fi
'';
inherit (w) tunnelPort directPort;
};
})
@@ -223,7 +137,7 @@ in
};
# Only pulls registration in: a simple unit gives the profile no ordering guarantee.
proxy-suite-awg-warp = lib.mkIf w.asAmneziaWg {
proxy-suite-awg-warp = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") {
wants = [ "proxy-suite-warp.service" ];
};
})
+138
View File
@@ -0,0 +1,138 @@
# A WireGuard profile as a sing-box endpoint in its own process, behind a loopback SOCKS
# listener the proxy outbound dials: the WARP tunnel and AmneziaWG profiles with
# asOutbound = "singBox".
{
lib,
pkgs,
cfg,
derived,
}:
let
inherit (derived.constants) serviceUser runAsServiceUser;
scriptsDir = builtins.path {
name = "proxy-suite-scripts";
path = ../../scripts;
};
# sing-box's "local" server has no upstream on hosts behind systemd-resolved, so the tunnel
# resolves the peer hostname like the main config, with proxy.dns.local. Destinations are
# resolved through the tunnel itself, with proxy.dns.remote.
dnsServer = tag: upstream: {
inherit tag;
type = upstream.type;
server = upstream.address;
server_port = upstream.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 handshakes for good, and sing-box retries on the same
# source port forever. A new process binds a new port, so the watchdog exits when the peer
# stops answering and systemd starts the tunnel again. A healthy handshake takes a fraction
# of a second, so a start gets 15 seconds; a running tunnel gets three misses. The
# "direct-in" listener reaches Cloudflare through the uplink with the backend's mark (not
# urlTest.url, which is picked to be blocked here): when that fails too, the tunnel could
# not work from a new port either.
mkWatchdog =
{
tag,
tunnelPort,
directPort,
}:
pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
set -uo pipefail
${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json" &
singbox=$!
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 tunnelPort "-f ${lib.escapeShellArg cfg.proxy.urlTest.url}"}; then
(( healthy )) || echo "proxy-suite: ${tag} is answering" >&2
healthy=1 failures=0 uplink_down=0
continue
fi
if ! ${probe directPort "https://1.1.1.1/cdn-cgi/trace"}; then
(( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging ${tag}" >&2
uplink_down=1 failures=0 since=$SECONDS
continue
fi
uplink_down=0
if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then
echo "proxy-suite: ${tag} is not answering; restarting the tunnel on a new source port" >&2
kill "$singbox"
wait "$singbox"
exit 1
fi
done
'';
# `profile` is a shell snippet, run as root, that sets $profile to the WireGuard .conf.
mkTunnel =
{
description,
unit,
tag,
profile,
tunnelPort,
directPort,
}:
let
tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
set -euo pipefail
${profile}
# The profile is a secret, so it is converted here, as root, rather than baked into
# the store; sing-box itself runs as ${serviceUser}.
endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag} --routing-mark ${toString mark} < "$profile")
(umask 027 && ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{
log: {level: "warn"},
dns: {servers: [
${builtins.toJSON (dnsServer "local" cfg.proxy.dns.local)},
(${builtins.toJSON (dnsServer "remote" cfg.proxy.dns.remote)} + {detour: "${tag}", domain_resolver: "local"})
]},
route: {
default_domain_resolver: "remote",
rules: [{inbound: ["direct-in"], outbound: "direct"}],
final: "${tag}"
},
inbounds: [
{type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString tunnelPort}},
{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString directPort}}
],
outbounds: [{type: "direct", tag: "direct", routing_mark: ${toString mark}}],
endpoints: [$ep + {domain_resolver: "local"}]
}' > "$RUNTIME_DIRECTORY/config.json")
${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/config.json"
exec ${runAsServiceUser pkgs [ "net_admin" ]} ${mkWatchdog { inherit tag tunnelPort directPort; }}
'';
in
{
inherit description;
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
# Probe-triggered restarts must not trip the start limit.
startLimitIntervalSec = 0;
serviceConfig = {
Type = "simple";
ExecStart = tunnelScript;
Restart = "always";
RestartSec = 2;
RuntimeDirectory = unit;
RuntimeDirectoryMode = "0750";
UMask = "0077";
};
};
in
{
inherit mkTunnel;
}
+2 -1
View File
@@ -14,8 +14,9 @@ let
zapretCfg = cfg.zapret;
perAppZapretCfg = cfg.perAppRouting.zapret;
# Global AmneziaWG profiles only: an outbound one leaves the host's routes alone.
awgServiceNames = map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames cfg.amneziaWg.profiles
builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles)
);
zapretPackages = import ./zapret/packages.nix {
inherit
+2 -1
View File
@@ -17,8 +17,9 @@ let
perAppZapretCfg = cfg.perAppRouting.zapret;
cutoffCfg = zapretCfg.zapret2.cutoff;
inherit (import ./derived.nix { inherit lib cfg; }) constants;
# Global AmneziaWG profiles only: an outbound one leaves the host's routes alone.
awgServiceNames = map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames cfg.amneziaWg.profiles
builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles)
);
runtime = import ./zapret2/runtime.nix {