feat: awg runtime add

This commit is contained in:
fufsob committed 2026-09-28 18:51:47 +00:00
1 parent cd3aa5a53f
commit 364bed8d51
39 files changed
+1581 -190

No files matched your search

+235 -55
View File
@@ -16,6 +16,11 @@ let
awgGlobalGroup
awgOutboundRulePriority
awgServerUdpRulePriority
runtimeAwgDir
runtimeOutboundsDir
awgRuntimeTunnelBasePort
awgRuntimeTunnelSlots
systemctl
;
killSwitchUnit = "proxy-suite-killswitch.service";
# Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick.
@@ -91,8 +96,63 @@ let
);
configTool = "${import ./lib/scripts-dir.nix { inherit lib; }}/amneziawg_config.py";
awgCommon = import ./awg-common.nix { inherit lib pkgs awgCfg; };
runtimeDir = name: "/run/${serviceName name}";
runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf";
# What a unit's scripts know of the profile they run. `init` is their first line and sets
# $profile_name; `runDir` is the runtime directory, as shell text; `source` the arguments
# amneziawg_config.py reads the profile with; `outbound` whether it is an "interface" one.
staticSpec = name: profile: {
inherit name profile;
template = false;
unit = serviceName name;
init = "profile_name=${lib.escapeShellArg name}";
runDir = "/run/${serviceName name}";
runtimeDirectory = serviceName name;
source = "--manifest ${lib.escapeShellArg (toString (manifestFor profile))}";
outbound = profile.asOutbound == "interface";
};
# Global profiles added with `proxy-ctl awg add`: instances of one template, the name
# passed in as $1 (%i), the .conf in runtimeAwgDir. They share an interface, and hooks are
# refused (--config), since whoever added one need not be root.
runtimeProfile = {
inherit (awgCfg.runtime) interfaceName;
asOutbound = null;
autostart = false;
settings = null;
};
runtimeSpec = {
name = "$profile_name";
profile = runtimeProfile;
template = true;
unit = "proxy-suite-awg@";
init = ''
profile_name=''${1:-}
if [[ ! $profile_name =~ ^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$ ]]; then
echo "proxy-suite: '$profile_name' is not an AmneziaWG profile name" >&2
exit 1
fi
'';
runDir = "/run/proxy-suite-awg-rt-$profile_name";
runtimeDirectory = "proxy-suite-awg-rt-%i";
source = ''--config "${runtimeAwgDir}/$profile_name.conf"'';
outbound = false;
};
specConfig = spec: "${spec.runDir}/${spec.profile.interfaceName}.conf";
# Runtime profiles cannot be named in Conflicts= at build time, and share one interface:
# starting any global profile stops the runtime ones still up. $1: its own instance, if one.
stopRuntimeProfiles = pkgs.writeShellScript "proxy-suite-awg" ''
set -uo pipefail
self="proxy-suite-awg@''${1:-}.service"
# A failed unit's line starts with a glyph: take the name wherever it is.
${systemctl} list-units --plain --no-legend --state=active,activating,reloading 'proxy-suite-awg@*.service' \
| ${pkgs.gnugrep}/bin/grep -o 'proxy-suite-awg@[^ ]*\.service' \
| while read -r unit; do
[[ $unit == "$self" ]] || ${systemctl} stop "$unit" || true
done
# grep finds nothing when none is up, which pipefail would make this script's failure.
exit 0
'';
# Keep proxy backend sockets (proxyMark) out of AWG's default-route table.
proxyBypassRulePriority = 8998;
bypassRule =
@@ -211,14 +271,15 @@ let
# awg-quick turns src_valid_mark on for a default route and never back off; left on, it
# changes how the kernel checks every marked packet's source. Put back as it was.
srcValidMark = "/proc/sys/net/ipv4/conf/all/src_valid_mark";
savedSrcValidMark = name: "${runtimeDir name}/src_valid_mark";
saveSrcValidMark = name: ''
[[ -e ${savedSrcValidMark name} ]] || cat ${srcValidMark} > ${savedSrcValidMark name}
# Unquoted: a runtime profile's name is checked against [A-Za-z0-9_-] first (runtimeSpec).
savedSrcValidMark = spec: "${spec.runDir}/src_valid_mark";
saveSrcValidMark = spec: ''
[[ -e ${savedSrcValidMark spec} ]] || cat ${srcValidMark} > ${savedSrcValidMark spec}
'';
restoreSrcValidMark = name: ''
if [[ -s ${savedSrcValidMark name} ]]; then
cat ${savedSrcValidMark name} > ${srcValidMark} || true
rm -f ${savedSrcValidMark name}
restoreSrcValidMark = spec: ''
if [[ -s ${savedSrcValidMark spec} ]]; then
cat ${savedSrcValidMark spec} > ${srcValidMark} || true
rm -f ${savedSrcValidMark spec}
fi
'';
@@ -233,15 +294,15 @@ let
# An outbound interface keeps the host's routes and resolver, and marks its packets so TUN and
# TProxy let them past. A global one under the kill switch marks them with a mark it knows.
prepareCommand = profile: output: ''
prepareCommand = spec: output: ''
${pkgs.python3}/bin/python3 ${configTool} \
--manifest ${lib.escapeShellArg (toString (manifestFor profile))} \
${spec.source} \
--output ${output}${
if profile.asOutbound == "interface" then
if spec.profile.asOutbound == "interface" then
" --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}"
else
lib.optionalString (
derived.killSwitchEnabled && profile.asOutbound == null
derived.killSwitchEnabled && spec.profile.asOutbound == null
) " --fwmark ${toString awgGlobalFwmark} --resolve-endpoints"
}
'';
@@ -259,19 +320,27 @@ let
exec "$@"
'';
# A global profile, or an "interface" outbound: a unit for a declared profile (staticSpec),
# or the template the runtime ones start from (runtimeSpec). `conflicts`: the global units
# it stops by starting.
mkService =
name: profile:
spec: conflicts:
let
outbound = profile.asOutbound == "interface";
configPath = runtimeConfig name profile;
prepare = pkgs.writeShellScript "proxy-suite-awg" ''
inherit (spec) name profile outbound;
configPath = specConfig spec;
# Every script: a template's instance name comes in as $1.
withInit = body: ''
${spec.init}
${body}
'';
prepare = pkgs.writeShellScript "proxy-suite-awg" (withInit ''
set -euo pipefail
${
lib.optionalString (
derived.killSwitchEnabled && !outbound
) "${pkgs.util-linux}/bin/unshare --mount ${ownLookups} "
}${prepareCommand profile (lib.escapeShellArg configPath)}
'';
}${prepareCommand spec ''"${configPath}"''}
'');
proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" ''
set -euo pipefail
${clearBypassRules}
@@ -286,12 +355,12 @@ let
set +e
${clearBypassRules}
'';
start = pkgs.writeShellScript "proxy-suite-awg" ''
start = pkgs.writeShellScript "proxy-suite-awg" (withInit ''
set -Eeuo pipefail
cleanup() {
set +e
${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath}
${awgCfg.toolsPackage}/bin/awg-quick down "${configPath}"
# Without the control socket awg-quick cannot find its fwmark; clean up this
# interface only.
@@ -318,7 +387,7 @@ let
if outbound then
outboundRuleCleanup name profile
else
repliesDown profile + restoreSrcValidMark name
repliesDown profile + restoreSrcValidMark spec
}
}
trap cleanup ERR
@@ -326,9 +395,9 @@ let
${awgCommon.modprobe}
read -r implementation probe _ < <(${pkgs.python3}/bin/python3 ${configTool} \
--inspect ${lib.escapeShellArg configPath})
${lib.optionalString (!outbound) (saveSrcValidMark name)}
${awgCommon.awgQuickUp "$implementation" (lib.escapeShellArg configPath)}
--inspect "${configPath}")
${lib.optionalString (!outbound) (saveSrcValidMark spec)}
${awgCommon.awgQuickUp "$implementation" ''"${configPath}"''}
${if outbound then outboundRoutesUp name profile else repliesUp profile}
${mkHandshakeHelpers profile}
@@ -344,21 +413,23 @@ let
fi
done
echo "proxy-suite: AmneziaWG profile '${name}' did not complete a handshake; rolling back routes" >&2
echo "proxy-suite: AmneziaWG profile '$profile_name' did not complete a handshake; rolling back routes" >&2
false
'';
stop = pkgs.writeShellScript "proxy-suite-awg" ''
'');
stop = pkgs.writeShellScript "proxy-suite-awg" (withInit ''
set -uo pipefail
status=0
${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath} || status=$?
${awgCfg.toolsPackage}/bin/awg-quick down "${configPath}" || status=$?
${
if outbound then
outboundRuleCleanup name profile
else
repliesDown profile + restoreSrcValidMark name
repliesDown profile + restoreSrcValidMark spec
}
exit "$status"
'';
'');
# A template's scripts get the instance name.
withArg = script: if spec.template then "${script} %i" else script;
in
(
if outbound then
@@ -372,7 +443,11 @@ let
}
else
{
description = "proxy-suite AmneziaWG client profile ${name}";
description =
if spec.template then
"proxy-suite AmneziaWG client profile %i (added at runtime)"
else
"proxy-suite AmneziaWG client profile ${name}";
# Start the local proxy before AWG takes the default route, so HTTP_PROXY clients
# do not race it.
after = [
@@ -386,7 +461,7 @@ let
++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"
++ lib.optional derived.killSwitchEnabled killSwitchUnit;
wantedBy = lib.optionals profile.autostart [ "multi-user.target" ];
conflicts = allProfileConflicts name ++ [
conflicts = conflicts ++ [
"proxy-suite-tun.service"
"proxy-suite-tproxy.service"
"proxy-suite-zapret.service"
@@ -410,7 +485,7 @@ let
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
RuntimeDirectory = serviceName name;
RuntimeDirectory = spec.runtimeDirectory;
RuntimeDirectoryMode = "0700";
UMask = "0077";
NoNewPrivileges = true;
@@ -421,9 +496,14 @@ let
ProtectKernelLogs = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
ExecStartPre = [ prepare ] ++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ];
ExecStart = start;
ExecStop = stop;
# Another profile stopping clears the bypass rules on its way out: before they go in.
ExecStartPre = [
(withArg prepare)
]
++ lib.optionals (!outbound && derived.awgRuntimeGlobal) [ (withArg stopRuntimeProfiles) ]
++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ];
ExecStart = withArg start;
ExecStop = withArg stop;
}
// lib.optionalAttrs (cfg.proxy.enable && !outbound) {
ExecStopPost = proxyBypassDown;
@@ -464,10 +544,81 @@ let
fi
''}
profile="$RUNTIME_DIRECTORY/profile.conf"
${prepareCommand profile ''"$profile"''}
${prepareCommand (staticSpec ob.name profile) ''"$profile"''}
'';
};
# Outbounds added with `proxy-ctl proxy outbounds add`: <tag>.awg in the runtime outbound
# spool, and the loopback port proxy-ctl gave it in <tag>.port. They run in wireproxy,
# which keeps the obfuscation; --config refuses hooks, as the spool is group-writable.
runtimeTunnelLastPort = awgRuntimeTunnelBasePort + awgRuntimeTunnelSlots - 1;
runtimeTunnelService = mkTunnel {
description = "proxy-suite AmneziaWG tunnel behind the %i outbound (added at runtime)";
unit = "proxy-suite-awg-tunnel@";
runtimeDirectory = "proxy-suite-awg-tunnel-%i";
engine = "userspace";
tag = "$TUNNEL_TAG";
tunnelPort = "$TUNNEL_PORT";
execArgs = " %i";
# The sync unit starts one per entry.
wantedBy = [ ];
# A removed entry exits cleanly, and stays stopped.
restart = "on-failure";
profile = ''
TUNNEL_TAG=''${1:-}
if [[ ! $TUNNEL_TAG =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then
echo "proxy-suite: '$TUNNEL_TAG' is not an outbound tag" >&2
exit 1
fi
profile="${runtimeOutboundsDir}/$TUNNEL_TAG.awg"
if [[ ! -s $profile ]]; then
echo "proxy-suite: no AmneziaWG outbound '$TUNNEL_TAG' in ${runtimeOutboundsDir}" >&2
exit 0
fi
TUNNEL_PORT=$(${pkgs.coreutils}/bin/head -n 1 "${runtimeOutboundsDir}/$TUNNEL_TAG.port" 2>/dev/null || true)
if [[ ! $TUNNEL_PORT =~ ^[0-9]+$ ]] || (( TUNNEL_PORT < ${toString awgRuntimeTunnelBasePort} || TUNNEL_PORT > ${toString runtimeTunnelLastPort} )); then
echo "proxy-suite: AmneziaWG outbound '$TUNNEL_TAG' needs a port in ${toString awgRuntimeTunnelBasePort}-${toString runtimeTunnelLastPort} in $TUNNEL_TAG.port" >&2
exit 1
fi
export TUNNEL_TAG TUNNEL_PORT
'';
};
# One tunnel per runtime AmneziaWG outbound, and none for an entry removed since: at boot,
# and with every proxy-suite-outbound-reload, which proxy-ctl starts after a change.
runtimeSyncService = {
description = "proxy-suite AmneziaWG outbounds added at runtime";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [
"multi-user.target"
"proxy-suite-outbound-reload.service"
];
serviceConfig = {
Type = "oneshot";
ExecStart = pkgs.writeShellScript "proxy-suite-awg" ''
set -uo pipefail
declare -A keep=()
for entry in "${runtimeOutboundsDir}"/*.awg; do
[[ -e $entry ]] || continue
tag=''${entry##*/}
tag=''${tag%.awg}
keep[$tag]=1
${systemctl} start --no-block "proxy-suite-awg-tunnel@$tag.service" || true
done
${systemctl} list-units --all --plain --no-legend 'proxy-suite-awg-tunnel@*.service' \
| ${pkgs.gnugrep}/bin/grep -o 'proxy-suite-awg-tunnel@[^ ]*\.service' \
| while read -r unit; do
tag=''${unit#proxy-suite-awg-tunnel@}
tag=''${tag%.service}
[[ -n ''${keep[$tag]:-} ]] || ${systemctl} stop --no-block "$unit" || true
done
# grep finds nothing when no tunnel is loaded, which pipefail would make a failure.
exit 0
'';
};
};
# Runs alongside a started profile. Its pings keep traffic flowing, and traffic makes
# WireGuard rekey every RekeyAfterTime (120 seconds by default); a handshake older than that
# on two checks in a row is a rekey that is not getting through, so the interface moves to
@@ -477,15 +628,18 @@ let
# peer can keep rekeying while carrying no traffic. After three misses the peer is re-added
# for a fresh session (a new port alone keeps the old one), at most once in five minutes.
mkWatchdog =
name: profile:
spec:
let
inherit (spec) profile;
egressProbe = profile.asOutbound == "interface";
unit = if spec.template then "proxy-suite-awg@%i.service" else "${spec.unit}.service";
watchdog = pkgs.writeShellScript "proxy-suite-awg" ''
${spec.init}
set -uo pipefail
read -r _ probe rekey < <(${pkgs.python3}/bin/python3 ${configTool} \
--inspect ${lib.escapeShellArg (runtimeConfig name profile)}) || exit 1
--inspect "${specConfig spec}") || exit 1
if (( rekey == 0 )); then
echo "proxy-suite: AmneziaWG profile '${name}' never rekeys; nothing to watch" >&2
echo "proxy-suite: AmneziaWG profile '$profile_name' never rekeys; nothing to watch" >&2
exec ${pkgs.coreutils}/bin/sleep infinity
fi
${mkHandshakeHelpers profile}
@@ -512,7 +666,7 @@ let
if (( $(handshake_age) <= rekey + 10 )); then
stale=0
elif (( ++stale >= 2 )); then
echo "proxy-suite: AmneziaWG profile '${name}' is not rekeying; moving to a new source port" >&2
echo "proxy-suite: AmneziaWG profile '$profile_name' is not rekeying; moving to a new source port" >&2
new_source_port
stale=0
${lib.optionalString egressProbe "continue"}
@@ -522,7 +676,7 @@ let
${lib.escapeShellArg cfg.proxy.urlTest.url}; then
misses=0
elif (( ++misses >= 3 && SECONDS - last_session >= 300 )); then
echo "proxy-suite: AmneziaWG profile '${name}' carries no IPv4 past its peer; starting a new session" >&2
echo "proxy-suite: AmneziaWG profile '$profile_name' carries no IPv4 past its peer; starting a new session" >&2
new_session
misses=0
last_session=$SECONDS
@@ -532,12 +686,15 @@ let
'';
in
{
description = "proxy-suite AmneziaWG client profile ${name} watchdog";
bindsTo = [ "${serviceName name}.service" ];
after = [ "${serviceName name}.service" ];
wantedBy = [ "${serviceName name}.service" ];
description = "proxy-suite AmneziaWG client profile ${
if spec.template then "%i" else spec.name
} watchdog";
bindsTo = [ unit ];
after = [ unit ];
# A template's instances are pulled in by the profile's own Wants=.
wantedBy = lib.optional (!spec.template) unit;
serviceConfig = {
ExecStart = watchdog;
ExecStart = if spec.template then "${watchdog} %i" else watchdog;
Restart = "on-failure";
RestartSec = 5;
CapabilityBoundingSet = [
@@ -620,7 +777,9 @@ let
)
) profileNames;
interfaceNames = map (name: profiles.${name}.interfaceName) profileNames;
interfaceNames =
map (name: profiles.${name}.interfaceName) profileNames
++ lib.optional derived.awgRuntimeGlobal awgCfg.runtime.interfaceName;
autostartProfiles = builtins.filter (name: profiles.${name}.autostart) globalProfileNames;
globalAutostartCount =
builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
@@ -630,10 +789,12 @@ in
awgCfg.toolsPackage
awgCfg.userspacePackage
]
++ lib.optional (builtins.any (ob: ob.kind == "userspace") tunnelOutbounds) awgCfg.wireproxyPackage;
++ lib.optional (
derived.awgRuntimeOutbounds || builtins.any (ob: ob.kind == "userspace") tunnelOutbounds
) awgCfg.wireproxyPackage;
services.proxy-suite.internal.groups = lib.optional (
derived.killSwitchEnabled && globalProfileNames != [ ]
derived.killSwitchEnabled && derived.awgGlobalAvailable
) awgGlobalGroup;
services.proxy-suite.internal.kernelModulePackages =
@@ -649,11 +810,30 @@ in
services.proxy-suite.internal.services = lib.mkMerge [
(lib.mapAttrs' (
name: profile: lib.nameValuePair (serviceName name) (mkService name profile)
name: profile:
lib.nameValuePair (serviceName name) (
mkService (staticSpec name profile) (allProfileConflicts name)
)
) interfaceProfiles)
(lib.mapAttrs' (
name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile)
name: profile:
lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog (staticSpec name profile))
) interfaceProfiles)
(lib.mkIf derived.awgRuntimeGlobal {
"proxy-suite-awg@" = lib.mkMerge [
(mkService runtimeSpec (map (other: "${serviceName other}.service") globalProfileNames))
{
wants = [ "proxy-suite-awg-watchdog@%i.service" ];
# The kill switch cannot order itself after instances it does not know.
before = [ killSwitchUnit ];
}
];
"proxy-suite-awg-watchdog@" = mkWatchdog runtimeSpec;
})
(lib.mkIf derived.awgRuntimeOutbounds {
"proxy-suite-awg-tunnel@" = runtimeTunnelService;
proxy-suite-awg-runtime-sync = runtimeSyncService;
})
(lib.listToAttrs (
map (ob: lib.nameValuePair (serviceName ob.name) (mkTunnelService ob)) tunnelOutbounds
))
@@ -667,8 +847,8 @@ in
assertions = profileAssertions ++ [
{
assertion = profiles != { };
message = "proxy-suite: amneziaWg.enable requires at least one profile";
assertion = profiles != { } || derived.awgRuntimeGlobal || derived.awgRuntimeOutbounds;
message = "proxy-suite: amneziaWg.enable needs a profile, or amneziaWg.runtime.enable for profiles added with proxy-ctl (global ones need a root host, outbounds proxy.enable)";
}
{
assertion = builtins.length interfaceNames == builtins.length (lib.unique interfaceNames);
+18 -1
View File
@@ -59,7 +59,7 @@ let
# Some global tunnel for it to guard.
killSwitchEnabled =
cfg.killSwitch.enable
&& (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalProfiles != { });
&& (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalAvailable);
perAppRoutingTun = cfg.perAppRouting.tun;
perAppRoutingTproxy = cfg.perAppRouting.tproxy;
zapretCfg = cfg.zapret;
@@ -158,6 +158,14 @@ let
}
) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles));
awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds;
# Added with proxy-ctl at runtime: global profiles (`awg add`), as template instances
# sharing runtime.interfaceName, need root; outbounds (`proxy outbounds add`) run in
# wireproxy template instances, which the supervisor cannot template.
awgRuntimeEnabled = cfg.amneziaWg.enable && cfg.amneziaWg.runtime.enable;
awgRuntimeGlobal = awgRuntimeEnabled && cfg.host.privileged;
awgRuntimeOutbounds = awgRuntimeEnabled && proxyEnabled && cfg.host.serviceManager != "supervisor";
# Some global profile may run: declared, or added at runtime.
awgGlobalAvailable = awgGlobalProfiles != { } || awgRuntimeGlobal;
# Profiles run behind a loopback SOCKS hop rather than an interface.
awgTunnelOutbounds = builtins.filter (ob: ob.kind != "interface") awgOutbounds;
@@ -442,6 +450,12 @@ let
awgOutboundRulePriority = 8991;
# A global AmneziaWG profile's rules keeping the host's UDP services on the main table.
awgServerUdpRulePriority = 8989;
# Global profiles and outbounds added with proxy-ctl: <name>.conf here, and
# <tag>.awg with <tag>.port in runtimeOutboundsDir.
runtimeAwgDir = "${stateDir}/amneziawg.d";
# Loopback SOCKS listeners of the runtime AmneziaWG outbounds, one per slot.
awgRuntimeTunnelBasePort = 18800;
awgRuntimeTunnelSlots = 32;
# sing-box's fake IP caches, one per TUN config; the start script hands it to the backend.
fakeIpCacheDir = "${stateDir}/fakeip";
# Downloaded proxy.routing.ruleSets, one file each, written by the service user.
@@ -550,6 +564,9 @@ in
torOnionInbounds
proxyInboundOnionCapable
awgGlobalProfiles
awgGlobalAvailable
awgRuntimeGlobal
awgRuntimeOutbounds
awgOutbounds
awgInterfaceOutbounds
awgTunnelOutbounds
+11 -4
View File
@@ -6,7 +6,12 @@
}:
let
inherit (import ./derived.nix { inherit lib cfg; }) constants awgGlobalProfiles;
inherit (import ./derived.nix { inherit lib cfg; })
constants
awgGlobalProfiles
awgGlobalAvailable
awgRuntimeGlobal
;
inherit (constants) serviceUser;
proxyCfg = cfg.proxy;
globalTproxy = proxyCfg.tproxy;
@@ -158,8 +163,10 @@ let
++ lib.optional perAppTun.enable perAppTun.fwmark
++ lib.optional perAppTproxy.enable perAppTproxy.fwmark
++ lib.optional tgWsProxyBypassEnabled tgWsProxyCfg.fwmark
++ lib.optional (awgGlobalProfiles != { }) constants.awgGlobalFwmark;
awgGlobalInterfaces = lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles;
++ lib.optional awgGlobalAvailable constants.awgGlobalFwmark;
awgGlobalInterfaces =
lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles
++ lib.optional awgRuntimeGlobal cfg.amneziaWg.runtime.interfaceName;
globalTunEnabled = proxyCfg.enable && proxyCfg.tun.enable;
killSwitchAllowLines = ''
ip daddr $RESERVED_IP accept
@@ -183,7 +190,7 @@ let
ip daddr ${proxyCfg.tun.address} accept
${lib.optionalString proxyCfg.ipv6 "ip6 daddr ${constants.globalTunIPv6Address} accept"}
''}
${lib.optionalString (awgGlobalProfiles != { }) ''
${lib.optionalString awgGlobalAvailable ''
oifname { ${lib.concatMapStringsSep ", " (i: ''"${i}"'') awgGlobalInterfaces} } accept
meta skgid "${constants.awgGlobalGroup}" accept
''}
@@ -66,6 +66,25 @@ in
];
};
runtime = {
enable = mkOption {
type = types.bool;
default = true;
description = ''
Let `proxy-ctl` add configs and `vpn://` links without a rebuild: `proxy-ctl awg add`
for a global profile (root hosts only), and `proxy-ctl proxy outbounds add` for an
outbound, which runs in wireproxy (needs `proxy.enable`). wg-quick hooks such as
`PostUp` are always refused in them. With this on, `profiles` may be empty.
'';
};
interfaceName = mkOption {
type = types.strMatching "^[A-Za-z0-9_.-]{1,15}$";
default = "awg-rt";
description = "Interface of the global profiles added at runtime. Only one of them runs at a time, so they share it.";
};
};
profiles = mkOption {
type = types.attrsOf t.profileType;
default = { };
+17
View File
@@ -30,6 +30,23 @@ in
example = "vpn.example.com";
};
serverAliases = mkOption {
type = types.listOf (types.strMatching "[^[:space:]]+");
default = [ ];
description = ''
Other names and IPs of this host that clients reach through the tunnel, such as a
TURN relay's name beside the site on `serverAddress`. Like `serverAddress`, they go
direct on the listener ports instead of looping back through `routing.via`, which
often cannot reach this host at all. List the IPs too: a client that resolves a name
itself hands XRay the address, which no name rule matches.
'';
example = [
"turn.example.com"
"203.0.113.10"
"2001:db8::10"
];
};
openFirewall = bool true "Open the firewall for every listener not on loopback.";
shareLinks = bool true "Generate client share links for `proxy-ctl inbounds link`. Readable by root, and by `userControl.group` with the secrets scope.";
@@ -25,6 +25,7 @@ in
"zapret"
"stats"
"whitelistBypass"
"amneziaWg"
]
);
default = [ ];
@@ -39,6 +40,9 @@ in
- "zapret": change zapret2's learned sites, and `zapret cutoff probe`.
- "stats": `inbounds stats`.
- "whitelistBypass": everything under `proxy-ctl wl`.
- "amneziaWg": add and remove global AmneziaWG profiles (`proxy-ctl awg add`, `awg rm`).
A global profile takes over the host's routes and DNS. Starting and stopping one is
"services"; an AmneziaWG outbound is "outbounds".
'';
example = [
"services"
+25 -23
View File
@@ -38,13 +38,15 @@ let
};
# The address clients dial must stay reachable even when blockRu covers it
# (a .ru domain or IP). After blockPrivate, so it cannot open the LAN.
serverAddressIsIp =
let
addr = proxyInboundsCfg.serverAddress;
in
addr != null
&& (lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null);
# (a .ru domain or IP). After blockPrivate, so it cannot open the LAN. Its aliases
# too: routing.via usually cannot loop back to this host, so they would fail there.
isIp =
addr: lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null;
serverAddresses =
lib.optional (proxyInboundsCfg.serverAddress != null) proxyInboundsCfg.serverAddress
++ proxyInboundsCfg.serverAliases;
serverIps = lib.unique (builtins.filter isIp serverAddresses);
serverNames = lib.unique (builtins.filter (addr: !isIp addr) serverAddresses);
# Only the ports clients dial there: the rest of this host (wildcard services the
# firewall keeps from the internet) must not be reachable through it.
@@ -59,23 +61,23 @@ let
]
);
# Names and IPs in rules of their own: XRay ANDs the fields of one rule.
mkServerAddressRule =
ruleTag: field: items:
lib.optional (items != [ ] && exceptionInboundTags != [ ]) {
type = "field";
inherit ruleTag;
${field} = items;
inboundTag = exceptionInboundTags;
port = lib.concatMapStringsSep "," toString serverAddressPorts;
outboundTag = "direct";
};
serverAddressRule =
lib.optional (proxyInboundsCfg.serverAddress != null && exceptionInboundTags != [ ])
(
{
type = "field";
ruleTag = "inbound-server-address-direct";
inboundTag = exceptionInboundTags;
port = lib.concatMapStringsSep "," toString serverAddressPorts;
outboundTag = "direct";
}
// (
if serverAddressIsIp then
{ ip = [ proxyInboundsCfg.serverAddress ]; }
else
{ domain = [ "full:${proxyInboundsCfg.serverAddress}" ]; }
)
);
mkServerAddressRule "inbound-server-address-direct" "domain" (
map (name: "full:${name}") serverNames
)
++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps;
blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [
{
+11 -4
View File
@@ -82,7 +82,12 @@ let
++ map (j: j.port) derived.whitelistBypassJoiners
++ lib.optionals derived.proxyInboundsEnabled (
map (listener: listener.internalPort) derived.proxyInboundsAwg
);
)
++ awgRuntimeTunnelPorts;
# The loopback listeners of AmneziaWG outbounds added at runtime, one per slot.
awgRuntimeTunnelPorts = lib.optionals derived.awgRuntimeOutbounds (
lib.genList (i: constants.awgRuntimeTunnelBasePort + i) constants.awgRuntimeTunnelSlots
);
# A rootless host (home-manager, nix-on-droid) runs everything as the user: nothing
# that programs routing, firewalls or interfaces, and no privileged ports.
@@ -274,7 +279,7 @@ let
(mkAssertion
(
!derived.killSwitchEnabled
|| derived.awgGlobalProfiles == { }
|| !derived.awgGlobalAvailable
|| !builtins.elem constants.awgGlobalFwmark (
[
globalTproxy.fwmark
@@ -461,11 +466,12 @@ let
!proxyInboundsEnabled
|| !lib.any (port: builtins.elem port derived.proxyInboundPorts) (
map (listener: listener.internalPort) derived.proxyInboundsAwg
++ awgRuntimeTunnelPorts
++ builtins.attrValues derived.constants.xrayDnsBridgePorts
++ lib.optionals hybridEnabled (builtins.attrValues derived.constants.xraySidecarPorts)
)
)
"proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, 18533-18535, or the hybrid XRay sidecar's 33080, 33180 and 33280)"
"proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, the runtime AmneziaWG outbounds' 18800-18831, 18533-18535, or the hybrid XRay sidecar's 33080, 33180 and 33280)"
)
# The prober opens one loopback listener per exit from probeBasePort; the WARP
# and AmneziaWG tunnels open two each from their own bases. They all bind
@@ -764,7 +770,8 @@ let
map (ib: ib.listener.amneziaWg.interfaceName) awgListeners
++ lib.optionals cfg.amneziaWg.enable (
lib.mapAttrsToList (_: profile: profile.interfaceName) cfg.amneziaWg.profiles
);
)
++ lib.optional derived.awgRuntimeGlobal cfg.amneziaWg.runtime.interfaceName;
otherInterfaces =
lib.optional (proxyEnabled && globalTun.enable) globalTun.interface
++ lib.optional (perAppRoutingCfg.enable && perAppRoutingTun.enable) perAppRoutingTun.interface;
+10
View File
@@ -22,6 +22,9 @@ let
proxyInboundsCfg
proxyInboundsEnabled
amneziaWgProfileNamesFile
awgRuntimeGlobal
awgRuntimeOutbounds
proxySuiteScriptsDir
ruleSets
pkgs
;
@@ -73,6 +76,13 @@ in
ROUTE_MODE_STATE_FILE = routeModeStateFile;
DEFAULT_ROUTE_MODE = if proxyCfg.routing.default == "proxy" then "blacklist" else "whitelist";
AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile;
# Profiles and outbounds added with `awg add` and `proxy outbounds add`.
AWG_RUNTIME_GLOBAL = flag awgRuntimeGlobal;
AWG_RUNTIME_OUTBOUNDS = flag awgRuntimeOutbounds;
AWG_RUNTIME_DIR = constants.runtimeAwgDir;
AWG_CONFIG_TOOL = "${proxySuiteScriptsDir}/amneziawg_config.py";
AWG_TUNNEL_BASE_PORT = toString constants.awgRuntimeTunnelBasePort;
AWG_TUNNEL_SLOTS = toString constants.awgRuntimeTunnelSlots;
WL_FILE = toString (
pkgs.writeText "proxy-suite-control" (
builtins.toJSON (
+27 -18
View File
@@ -175,24 +175,33 @@ lib.mkMerge [
# files proxy-ctl drops here inherit the group; without the outbounds scope
# only root writes them. tmpfiles rather than the start scripts, so the group can add an
# outbound before the proxy has ever run.
tmpfiles = lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlAllows "outbounds" then
"2770 root ${userControlCfg.group}"
else if constants.privileged then
"0700 root root"
else
"0700 - -"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
);
tmpfiles = lib.mkMerge [
(lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlAllows "outbounds" then
"2770 root ${userControlCfg.group}"
else if constants.privileged then
"0700 root root"
else
"0700 - -"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
))
# Global AmneziaWG profiles added at runtime. Listable, so the tray and TUI show
# their names to everyone; each file is 0600 (amneziawg_config.py writes it so).
(lib.mkIf (cfg.enable && derived.awgRuntimeGlobal) [
"d ${constants.runtimeAwgDir} ${
if userControlAllows "amneziaWg" then "2775 root ${userControlCfg.group}" else "0755 root root"
} -"
])
];
userServices = lib.mkMerge [
(mkNamedUnits userServiceEntries)
+4
View File
@@ -11,6 +11,10 @@ let
"proxy-suite-route-mode@" = "routing";
"proxy-suite-outbound-reload." = "outbounds";
"proxy-suite-subscription-update." = "outbounds";
# Tunnels of the AmneziaWG outbounds added at runtime; a global profile's own unit
# (proxy-suite-awg@) is "services", like the declared ones.
"proxy-suite-awg-tunnel@" = "outbounds";
"proxy-suite-awg-runtime-sync." = "outbounds";
"proxy-suite-autoproxy-learn." = "autoProxy";
"proxy-suite-zapret2-cutoff." = "zapret";
"proxy-suite-inbound-stats." = "stats";
@@ -8,6 +8,7 @@
torCfg,
whitelistBypassJoiners,
awgOutbounds,
awgRuntimeOutbounds ? false,
constants,
pureXrayEnabled,
hybridEnabled,
@@ -136,6 +137,27 @@ let
OUTBOUND_SOURCES_JSON=$(${jq} --arg t "$1" --arg s "$2" '.[$t] = $s' <<< "$OUTBOUND_SOURCES_JSON")
}
# $1 tag, $2 loopback SOCKS port, $3 source label: mkTunnelOutboundBlock, for a port
# only known at runtime (an AmneziaWG outbound added with proxy-ctl).
_proxy_suite_add_socks_hop() {
local ob
ob=$(${jq} -nc --arg t "$1" --argjson p "$2" ${
lib.escapeShellArg (
if pureXrayEnabled then
''{protocol: "socks", tag: $t, settings: {address: "127.0.0.1", port: $p}}''
else
''{type: "socks", tag: $t, server: "127.0.0.1", server_port: $p}''
)
}) || return 1
${
if hybridEnabled then
''_proxy_suite_add_sing_box_ob "$ob"''
else
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
}
_proxy_suite_record_tag_source "$1" "$3"
}
# $1 sub tag, $2 file holding its URL, $3 its links file (absent for a cache
# written before links existed: those entries share as JSON until the next update).
_proxy_suite_record_subscription_share() {
@@ -196,13 +218,14 @@ let
_proxy_suite_record_tag_source "$tag" "$source"
}
# Every runtime outbound, as "<tag>\t<file>" lines: <tag>.url or <tag>.json. proxy-ctl refuses
# Every runtime outbound, as "<tag>\t<file>" lines: <tag>.url, <tag>.json or <tag>.awg (an
# AmneziaWG config, behind a tunnel on the port in <tag>.port). proxy-ctl refuses
# the reserved names, but the spool is group-writable, so check again here:
# a second outbound tagged "proxy" would quietly shadow the real one.
_proxy_suite_runtime_outbounds() {
local f tag
[ -d "${runtimeOutboundsDir}" ] || return 0
for f in "${runtimeOutboundsDir}"/*.url "${runtimeOutboundsDir}"/*.json; do
for f in "${runtimeOutboundsDir}"/*.url "${runtimeOutboundsDir}"/*.json${lib.optionalString awgRuntimeOutbounds ''"${runtimeOutboundsDir}"/*.awg''}; do
[ -e "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.*}"
@@ -448,6 +471,8 @@ let
[ -n "$RUNTIME_OB_TAG" ] || continue
case "$RUNTIME_OB_SRC" in
*.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;;
# Its tunnel (proxy-suite-awg-tunnel@<tag>) checks the port again before listening.
*.awg) _proxy_suite_add_socks_hop "$RUNTIME_OB_TAG" "$(head -n 1 "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.port" 2>/dev/null)" runtime ;;
*) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime ;;
esac || { echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2; continue; }
if [ -s "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" ]; then
+1
View File
@@ -128,6 +128,7 @@ let
torCfg
whitelistBypassJoiners
awgOutbounds
awgRuntimeOutbounds
constants
pureXrayEnabled
hybridEnabled
+12 -5
View File
@@ -147,6 +147,9 @@ let
# the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort,
# `endpoint`, a host:port in place of the profile's Endpoint, and `domainStrategy`, the
# address family it dials destinations over first.
#
# A template unit passes `tag` and `tunnelPort` as shell words ("$TUNNEL_TAG") that
# `profile` exports: the watchdog runs as a script of its own, after the exec.
mkTunnel =
{
description,
@@ -158,6 +161,11 @@ let
endpoint ? null,
domainStrategy ? null,
engine ? "singBox",
runtimeDirectory ? unit,
wantedBy ? [ "multi-user.target" ],
restart ? "always",
# " %i" for a template, whose `profile` reads the instance name from $1.
execArgs ? "",
}:
let
chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) {
@@ -188,18 +196,17 @@ let
'';
in
{
inherit description;
inherit description wantedBy;
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
# Probe-triggered restarts must not trip the start limit.
startLimitIntervalSec = 0;
serviceConfig = {
Type = "simple";
ExecStart = tunnelScript;
Restart = "always";
ExecStart = if execArgs == "" then tunnelScript else "${tunnelScript}${execArgs}";
Restart = restart;
RestartSec = 2;
RuntimeDirectory = unit;
RuntimeDirectory = runtimeDirectory;
RuntimeDirectoryMode = "0750";
UMask = "0077";
};