feat: per-app awg and custom via

This commit is contained in:
FUFSoB committed 2026-10-04 15:39:56 +05:00
1 parent af5b3ff27a
commit 65082aad88
43 files changed
+2674 -197

No files matched your search

+17
View File
@@ -26,6 +26,8 @@ let
amneziaWgProfileNamesFile
awgRuntimeGlobal
awgRuntimeOutbounds
awgRuntimeIfaceOutbounds
perAppViaRuntime
proxySuiteScriptsDir
ruleSets
pkgs
@@ -38,6 +40,7 @@ let
proxyInboundsSubscriptionsFile
;
inherit (ctx.perAppRouting)
perAppViaFile
perAppRoutingProfilesFile
proxychainsConfigFile
proxychainsQuietArg
@@ -73,6 +76,17 @@ in
PER_APP_ROUTING_TPROXY_ENABLED = flag perAppRoutingTproxy.enable;
PER_APP_ROUTING_ZAPRET_ENABLED = flag perAppZapretCfg.enable;
PER_APP_ROUTING_PROFILES_FILE = toString perAppRoutingProfilesFile;
# And the ones `apps add` adds.
RUNTIME_APPS_DIR = constants.runtimeAppsDir;
# The outbounds `apps run --via` takes, tag -> its interface and mark.
PER_APP_VIA_FILE = toString perAppViaFile;
# And the runtime ones, on their own interfaces (<tag>.iface in the outbound spool).
PER_APP_VIA_RUNTIME = flag perAppViaRuntime;
# And global AmneziaWG profiles, each brought up apart for the apps.
PER_APP_VIA_PROFILES = flag ctx.perAppViaProfiles;
# Any other outbound, through a pin slot of these routes.
PER_APP_PIN_TPROXY = flag ctx.perAppPinTproxy;
PER_APP_PIN_TUN = flag ctx.perAppPinTun;
PROXYCHAINS_CONFIG = toString proxychainsConfigFile;
PROXYCHAINS_QUIET_ARG = lib.removeSuffix " " proxychainsQuietArg;
ROUTE_MODE_STATE_FILE = routeModeStateFile;
@@ -94,6 +108,9 @@ in
AWG_CONFIG_TOOL = "${proxySuiteScriptsDir}/amneziawg_config.py";
AWG_TUNNEL_BASE_PORT = toString constants.awgRuntimeTunnelBasePort;
AWG_TUNNEL_SLOTS = toString constants.awgRuntimeTunnelSlots;
AWG_RUNTIME_IFACE_OUTBOUNDS = flag awgRuntimeIfaceOutbounds;
AWG_RUNTIME_OUTBOUND_KIND = cfg.amneziaWg.runtime.outboundKind;
AWG_IFACE_SLOTS = toString constants.awgRuntimeIfaceSlots;
WL_FILE = toString (
pkgs.writeText "proxy-suite-control" (
builtins.toJSON (
+18
View File
@@ -91,6 +91,10 @@ let
path = constants.runtimeAwgDir;
scope = "amneziaWg";
}
++ lib.optional cfg.perAppRouting.enable {
path = constants.runtimeAppsDir;
scope = "perApp";
}
++ lib.optional derived.zapretCutoffEnabled {
path = "${constants.zapret2CutoffDir}/requests";
scope = "zapret";
@@ -352,6 +356,20 @@ lib.mkMerge [
"${constants.runtimeInboundsDir}/listeners"
]
))
# Per-app profiles added at runtime: read by everyone who runs apps, written with the
# perApp scope.
(lib.mkIf (cfg.enable && cfg.perAppRouting.enable) [
"d ${constants.runtimeAppsDir} ${
if !constants.privileged then
"0700 - -"
else if userControlAllows "perApp" then
"2775 root ${userControlCfg.group}"
else if derived.userControlAnyAllows "perApp" then
"2775 root root"
else
"0755 root root"
} -"
])
# 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) [
@@ -42,6 +42,7 @@ slices
// import ./per-app-routing/profiles.nix { inherit ctx; }
// import ./per-app-routing/backend-scripts.nix { inherit ctx; }
// userRules
// import ./per-app-routing/via.nix { inherit ctx userRules; }
// {
inherit (builders) mkAnchorService;
}
@@ -70,16 +70,15 @@ let
'';
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
hasProxychainsProfiles = builtins.any (
profile: profile.route == "proxychains"
) effectivePerAppRoutingProfiles;
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles;
hasTproxyProfiles = builtins.any (
profile: profile.route == "tproxy"
) effectivePerAppRoutingProfiles;
hasZapretProfiles = builtins.any (
profile: profile.route == "zapret"
# A profile run straight into an AmneziaWG interface uses no method, whatever its route.
methodProfiles = builtins.filter (
profile: (profile.outbound or null) == null || !ctx.perAppViaDirect profile.outbound
) effectivePerAppRoutingProfiles;
hasRoute = route: builtins.any (profile: profile.route == route) methodProfiles;
hasProxychainsProfiles = hasRoute "proxychains";
hasTunProfiles = hasRoute "tun";
hasTproxyProfiles = hasRoute "tproxy";
hasZapretProfiles = hasRoute "zapret";
in
{
inherit
@@ -16,18 +16,24 @@
}:
let
# `prelude` runs first and may set what the rest reads: a template whose instance carries
# more than the uid turns its $1 into the uid and sets the shell variables that `nftTable`,
# `markRule` and `sliceNameArg` (the slice's name, as shell text) then name.
mkUserRuleStart =
{
name,
nftFamily,
nftTable,
nftChain,
sliceName,
sliceName ? null,
sliceNameArg ? lib.escapeShellArg sliceName,
sliceLabel,
markRule,
prelude ? "",
}:
pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${prelude}
uid="$1"
if ! [[ $uid =~ ^[0-9]+$ ]]; then
echo "proxy-suite: '$uid' is not a uid" >&2
@@ -44,7 +50,7 @@ let
# The user owns this subtree and names its directories, quotes and semicolons included:
# only a path nft reads as the one quoted string below, never one that closes the quote
# and runs nft commands of its own as root. systemd's names never need more.
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} \
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${sliceNameArg} \
| ${grepBin} -E '^[A-Za-z0-9@._:+,=\\/-]+$' | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2
@@ -74,9 +80,11 @@ let
nftFamily,
nftTable,
nftChain,
prelude ? "",
}:
pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${prelude}
uid="$1"
rule_comment_prefix="proxy-suite-${name}-user-$uid"
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
@@ -140,6 +148,7 @@ let
};
in
{
inherit mkUserRuleStart mkUserRuleStop;
inherit
perAppTunUserRuleStart
perAppTunUserRuleStop
@@ -0,0 +1,514 @@
# `proxy-ctl apps run --via <tag>`: an app's traffic straight into an "interface" AmneziaWG
# outbound, past the proxy (proxy-suite-per-app-via@awg-<hex>); or, for any other outbound,
# into a pin slot of per-app TProxy or TUN, whose selector in the backend sends it there
# (proxy-suite-per-app-via-<route>@<hex>). The tag goes in hex: that keeps it out of
# systemd's slice hierarchy, where "de" would be the parent of "de-2", and nft's cgroup match
# would take both.
{ ctx, userRules }:
let
inherit (ctx)
lib
pkgs
cfg
constants
perAppRoutingCfg
perAppViaInterfaceOutbounds
perAppViaRuntime
perAppViaProfiles
perAppPinSlots
perAppPinTproxy
perAppPinTun
perAppRoutingTun
singBoxCfg
builders
proxySuiteScriptsDir
python3
ip
nft
jq
;
inherit (constants)
awgPerAppRulePriority
awgPerAppUnreachablePriority
runtimeOutboundsDir
awgRuntimeIfacePrefix
awgRuntimeIfaceSlots
awgRuntimeIfaceTableBase
awgRuntimeIfacePerAppFwmarkBase
awgRuntimeIfaceDnsBasePort
;
inherit (import ../../nftables.nix { inherit lib pkgs cfg; })
perAppPinTproxyRulesFiles
perAppPinTunChainFiles
;
remoteDns = cfg.proxy.dns.remote.address;
# proxy.dns.remote, for a profile with no DNS line of its own, if it is an address.
fallbackDns = lib.optional (
builtins.match "[0-9.]+|[0-9A-Fa-f:]*:[0-9A-Fa-f:.]*" remoteDns != null
) remoteDns;
# tag -> what an instance needs of its outbound. proxy-ctl reads it too, to tell which tags
# take this path.
perAppViaFile = pkgs.writeText "proxy-suite-per-app" (
builtins.toJSON (
lib.listToAttrs (
map (
ob:
lib.nameValuePair ob.tag {
inherit (ob) interface;
table = ob.routeTable;
mark = ob.perAppFwmark;
dnsPort = ob.perAppDnsPort;
unit = "proxy-suite-awg-${ob.name}.service";
dnsFile = "/run/proxy-suite-awg-${ob.name}/dns";
inherit fallbackDns;
}
) perAppViaInterfaceOutbounds
)
)
);
ipFamily = cidr: if lib.hasInfix ":" cidr then "ip6" else "ip";
# $1, the instance, to $key, $tag and its outbound's $interface, $table and $mark. An
# awg-<hex> instance is an "interface" outbound; app-<hex> a global profile, which
# proxy-suite-awg-app@<name> has brought up on a slot of its own.
resolveInstance = ''
key=''${1:-}
if [[ ! $key =~ ^(awg|app)-([0-9a-f][0-9a-f]){1,64}$ ]]; then
echo "proxy-suite: '$key' is not a per-app via instance" >&2
exit 1
fi
tag=$(printf '%b' "$(printf '%s' "''${key#*-}" | ${pkgs.gnused}/bin/sed 's/../\\x&/g')")
if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then
echo "proxy-suite: '$tag' is not an outbound tag" >&2
exit 1
fi
if [[ $key == app-* ]]; then
${
if perAppViaProfiles then
''
slot=$(${pkgs.coreutils}/bin/head -n 1 "/run/proxy-suite-awg-app-$tag/slot" 2>/dev/null || true)
if [[ ! $slot =~ ^[0-9]+$ ]] || (( slot >= ${toString constants.awgAppSlots} )); then
echo "proxy-suite: AmneziaWG profile '$tag' is not up for apps (proxy-suite-awg-app@$tag)" >&2
exit 1
fi
entry=$(${jq} -nc --arg t "$tag" --argjson s "$slot" --argjson fallback ${lib.escapeShellArg (builtins.toJSON fallbackDns)} '{
interface: ("${constants.awgAppIfacePrefix}" + ($s | tostring)),
table: (${toString constants.awgAppTableBase} + $s),
mark: (${toString constants.awgAppPerAppFwmarkBase} + $s),
dnsPort: (${toString constants.awgAppDnsBasePort} + $s),
dnsFile: ("/run/proxy-suite-awg-app-" + $t + "/dns"),
fallbackDns: $fallback
}')
''
else
''
echo "proxy-suite: apps cannot run through global AmneziaWG profiles here" >&2
exit 1
''
}
elif ! entry=$(${jq} -ce --arg t "$tag" '.[$t] // empty' ${perAppViaFile}); then
${lib.optionalString perAppViaRuntime ''
# One added at runtime: its slot in the spool, which is group-writable (O_NOFOLLOW).
slot=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$tag.iface" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true)
if [[ $slot =~ ^[0-9]+$ ]] && (( slot < ${toString awgRuntimeIfaceSlots} )); then
entry=$(${jq} -nc --arg t "$tag" --argjson s "$slot" --argjson fallback ${lib.escapeShellArg (builtins.toJSON fallbackDns)} '{
interface: ("${awgRuntimeIfacePrefix}" + ($s | tostring)),
table: (${toString awgRuntimeIfaceTableBase} + $s),
mark: (${toString awgRuntimeIfacePerAppFwmarkBase} + $s),
dnsPort: (${toString awgRuntimeIfaceDnsBasePort} + $s),
dnsFile: ("/run/proxy-suite-awg-if-" + $t + "/dns"),
fallbackDns: $fallback
}')
fi
''}
if [[ -z ''${entry:-} ]]; then
echo "proxy-suite: '$tag' is not an \"interface\" AmneziaWG outbound" >&2
exit 1
fi
fi
interface=$(${jq} -r .interface <<< "$entry")
table=$(${jq} -r .table <<< "$entry")
mark=$(${jq} -r .mark <<< "$entry")
nft_table="proxy_suite_per_app_via_$mark"
dns_port=$(${jq} -r .dnsPort <<< "$entry")
'';
# $servers: the profile's own DNS servers, else proxy.dns.remote.
dnsServers = ''
dns_file=$(${jq} -r .dnsFile <<< "$entry")
servers=()
add_servers() {
local server
while read -r server; do
if [[ $server =~ ^[0-9A-Fa-f:.]+$ ]]; then servers+=("$server"); fi
done
}
if [[ -s $dns_file ]]; then add_servers < "$dns_file"; fi
if (( ! ''${#servers[@]} )); then add_servers < <(${jq} -r '.fallbackDns[]' <<< "$entry"); fi
'';
rulesDown = ''
for family in -4 -6; do
while ${ip} "$family" rule del pref ${toString awgPerAppRulePriority} fwmark "$mark" 2>/dev/null; do :; done
while ${ip} "$family" rule del pref ${toString awgPerAppUnreachablePriority} fwmark "$mark" 2>/dev/null; do :; done
done
'';
viaUp = pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${resolveInstance}
${dnsServers}
dns=""
if (( ''${#servers[@]} )); then
# By the conntrack mark, which only the app's own connections carry: the forwarder's
# queries have the packet mark alone.
dns="ct mark $mark meta l4proto { tcp, udp } th dport 53 redirect to :$dns_port"
else
echo "proxy-suite: AmneziaWG outbound '$tag' names no DNS server: apps run via it look names up outside the tunnel" >&2
fi
${nft} delete table inet "$nft_table" 2>/dev/null || true
${rulesDown}
${nft} -f - <<EOF
table inet $nft_table {
# The per-user cgroup mark rules go here (proxy-suite-per-app-via-user@).
chain app_mark {
}
# Replies find their way back by the mark, past a reverse-path check: only those
# out of the tunnel, never the tunnel's own packets on the uplink.
chain prerouting {
type filter hook prerouting priority mangle - 10; policy accept;
iifname "$interface" ct mark $mark meta mark set $mark
}
# Before the TProxy chains, which let this mark past.
chain output {
type route hook output priority mangle - 10; policy accept;
ct direction reply return
# A packet marked already is not the app's to take: the tunnel's own (its FwMark),
# which still looks like it came from the app's socket and, taken, would be routed
# back into the tunnel; the DNS forwarder's; or proxy-suite's own.
meta mark != 0 return
ct mark $mark meta mark set $mark
meta mark $mark return
# Lookups, wherever the app's resolver is, go to the forwarder (nat_output),
# which asks the profile's resolvers through the tunnel.
meta l4proto { tcp, udp } th dport 53 goto app_mark
# Only what never leaves the host or its link stays out. Private ranges go in, as
# a VPN takes them: the server's own address (where its VPN-only names resolve)
# and the networks behind it are there. The LAN is localSubnets.
ip daddr { 127.0.0.0/8, 169.254.0.0/16, 224.0.0.0/4, 255.255.255.255 } return
ip6 daddr { ::1, fe80::/10, ff00::/8 } return
${lib.concatMapStrings (cidr: ''
${ipFamily cidr} daddr ${cidr} return
'') perAppRoutingCfg.via.localSubnets}
goto app_mark
}
chain nat_output {
type nat hook output priority dstnat; policy accept;
$dns
}
# The app picked its source address on the host's route, before the mark moved it here.
chain nat_postrouting {
type nat hook postrouting priority srcnat; policy accept;
oifname "$interface" meta mark $mark masquerade
}
}
EOF
for family in -4 -6; do
# Turned away while the table has no route of the family: the interface is down, or
# has no address of it. IPv6 may be off altogether.
${ip} "$family" rule add pref ${toString awgPerAppRulePriority} fwmark "$mark" lookup "$table" \
&& ${ip} "$family" rule add pref ${toString awgPerAppUnreachablePriority} fwmark "$mark" unreachable \
|| [[ $family == -6 ]]
done
'';
# The forwarder, for the unit's lifetime; it has nothing to ask without a server.
viaDns = pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${resolveInstance}
${dnsServers}
exec ${python3} ${proxySuiteScriptsDir}/per_app_dns.py --port "$dns_port" --mark "$mark" "''${servers[@]}"
'';
viaDown = pkgs.writeShellScript "proxy-suite-per-app" ''
set -uo pipefail
${resolveInstance}
${nft} delete table inet "$nft_table" 2>/dev/null || true
${rulesDown}
'';
# Instance <uid>-<key>, the key awg-<hex> or <route>-<hex>: the user's apps in the slice
# of what they run via.
userPrelude = ''
instance=''${1:-}
if [[ ! $instance =~ ^([0-9]+)-((awg|app|tproxy|tun)-[0-9a-f]+)$ ]]; then
echo "proxy-suite: '$instance' is not <uid>-<per-app via instance>" >&2
exit 1
fi
key=''${BASH_REMATCH[2]}
case "$key" in
awg-* | app-*)
set -- "$key"
${resolveInstance}
nft_chain=app_mark
;;
${lib.concatMapStrings (route: ''
${route}-*)
set -- "''${key#${route}-}"
${decodeTag}
${pinSlot route false}
if [[ -z $slot ]]; then
echo "proxy-suite: no ${route} pin slot holds '$tag'" >&2
exit 1
fi
nft_chain=${pinRoutes.${route}.nftChain}
;;
'') pinRouteNames}
*)
echo "proxy-suite: '$key' is not run via here" >&2
exit 1
;;
esac
slice_name="proxy-suite-per-app-via-$key.slice"
set -- "''${instance%%-*}"
'';
viaUserStart = userRules.mkUserRuleStart {
name = "per-app-via-$key";
nftFamily = "inet";
nftTable = "$nft_table";
nftChain = "$nft_chain";
sliceNameArg = ''"$slice_name"'';
sliceLabel = "app via";
markRule = "meta mark set $mark ct mark set $mark";
prelude = userPrelude;
};
viaUserStop = userRules.mkUserRuleStop {
name = "per-app-via-$key";
nftFamily = "inet";
nftTable = "$nft_table";
nftChain = "$nft_chain";
prelude = userPrelude;
};
# The pin slots, of per-app TProxy and of per-app TUN.
pinRouteNames = lib.optional perAppPinTproxy "tproxy" ++ lib.optional perAppPinTun "tun";
pinDir = "${constants.runtimeDir}/proxy-suite-per-app-via";
curl = "${pkgs.curl}/bin/curl";
flock = "${pkgs.util-linux}/bin/flock";
pinTun = lib.escapeShellArg perAppRoutingTun.interface;
pinRoutes = {
tproxy = {
fwmarkBase = constants.perAppPinTproxyFwmarkBase;
tableBase = constants.perAppPinTproxyTableBase;
nftFiles = perAppPinTproxyRulesFiles;
# Where the user rule units add their cgroup rules, as for the per-app TProxy's own.
nftChain = "output";
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
secretFile = "${constants.runtimeDir}/proxy-suite-socks/clash-secret";
backend = "proxy-suite-socks.service";
routingDown = builders.mkTproxyRoutingDown {
inherit ip;
fwmark = "$mark";
table = "$table";
};
routingUp = ''
${pinRoutes.tproxy.routingDown}
${builders.mkTproxyRoutingUp {
inherit ip;
inherit (cfg.proxy) ipv6;
fwmark = "$mark";
table = "$table";
}}
'';
};
tun = {
fwmarkBase = constants.perAppPinTunFwmarkBase;
tableBase = constants.perAppPinTunTableBase;
nftFiles = perAppPinTunChainFiles;
nftChain = "app_mark";
clashApi = "http://127.0.0.1:${toString constants.perAppTunClashApiPort}";
secretFile = "${constants.runtimeDir}/proxy-suite-per-app-tun/clash-secret";
backend = "proxy-suite-per-app-tun.service";
# Into the TUN; the slot's nft table SNATs the packets to the source the backend tells
# the slot by.
routingUp = ''
${ip} -4 route replace default dev ${pinTun} table "$table"
${
if cfg.proxy.ipv6 then
''
${ip} -6 route replace default dev ${pinTun} table "$table"
''
else
''
# No IPv6 in the TUN: unreachable, so the app falls back to IPv4.
${ip} -6 route replace unreachable default table "$table"
''
}
for family in -4 -6; do
while ${ip} "$family" rule del pref ${toString constants.perAppPinRulePriority} fwmark "$mark" 2>/dev/null; do :; done
${ip} "$family" rule add pref ${toString constants.perAppPinRulePriority} fwmark "$mark" table "$table"
done
'';
routingDown = ''
for family in -4 -6; do
while ${ip} "$family" rule del pref ${toString constants.perAppPinRulePriority} fwmark "$mark" 2>/dev/null; do :; done
${ip} "$family" route flush table "$table" 2>/dev/null || true
done
'';
};
};
# $1, a tag in hex, to $hex and $tag.
decodeTag = ''
hex=''${1:-}
if [[ ! $hex =~ ^([0-9a-f][0-9a-f]){1,64}$ ]]; then
echo "proxy-suite: '$hex' is not an outbound tag in hex" >&2
exit 1
fi
tag=$(printf '%b' "$(printf '%s' "$hex" | ${pkgs.gnused}/bin/sed 's/../\\x&/g')")
if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then
echo "proxy-suite: '$tag' is not an outbound tag" >&2
exit 1
fi
'';
# $slot: the one of the route's slots that $tag holds; with `claim`, a free one when none
# does. Then its $mark, $table and $nft_table. A slot is the file <route>-<n> in pinDir,
# holding the tag.
pinSlot =
route: claim:
let
r = pinRoutes.${route};
file = ''"${pinDir}/${route}-$n"'';
in
''
${pkgs.coreutils}/bin/mkdir -p ${pinDir}
exec 9>>"${pinDir}/lock"
${flock} 9
slot=""
for (( n = 0; n < ${toString perAppPinSlots}; n++ )); do
if [[ -f ${file} && $(< ${file}) == "$tag" ]]; then
slot=$n
break
fi
done
${lib.optionalString claim ''
for (( n = 0; n < ${toString perAppPinSlots}; n++ )); do
[[ -z $slot ]] || break
if [[ ! -e ${file} ]]; then
printf '%s\n' "$tag" > ${file}
slot=$n
fi
done
''}
${flock} -u 9
if [[ -n $slot ]]; then
mark=$(( ${toString r.fwmarkBase} + slot ))
table=$(( ${toString r.tableBase} + slot ))
nft_table="proxy_suite_per_app_via_${route}_$slot"
fi
'';
# select_pin <tag> <attempts>: switches the slot's selector, while the backend comes up.
mkSelect =
route:
let
r = pinRoutes.${route};
in
''
select_pin() {
local code attempt secret
for attempt in $(${pkgs.coreutils}/bin/seq 1 "$2"); do
secret=$(${pkgs.coreutils}/bin/tr -d '\r\n' 2>/dev/null < ${r.secretFile} || true)
code=$(${curl} -s -o /dev/null -w '%{http_code}' --noproxy '*' -m 3 \
-X PUT "${r.clashApi}/proxies/proxy-suite-pin-${route}-$slot" \
-H "Content-Type: application/json" \
-H @<(printf 'Authorization: Bearer %s\n' "$secret") \
-d "$(${jq} -cn --arg n "$1" '{name: $n}')" || true)
case "$code" in
2??) return 0 ;;
400)
echo "proxy-suite: the backend has no outbound '$1' to run apps through" >&2
return 2
;;
404)
echo "proxy-suite: the backend has no ${route} pin slot $slot; restart ${r.backend}" >&2
return 2
;;
esac
${pkgs.coreutils}/bin/sleep 0.5
done
echo "proxy-suite: the backend's Clash API at ${r.clashApi} did not answer" >&2
return 1
}
'';
mkPinUp =
route:
let
r = pinRoutes.${route};
in
pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${decodeTag}
${pinSlot route true}
if [[ -z $slot ]]; then
echo "proxy-suite: all ${toString perAppPinSlots} ${route} pin slots are taken (perAppRouting.via.pinSlots)" >&2
exit 1
fi
${mkSelect route}
release() {
set +e
${nft} delete table inet "$nft_table" 2>/dev/null
${r.routingDown}
${pkgs.coreutils}/bin/rm -f "${pinDir}/${route}-$slot"
}
trap release ERR
files=(${lib.concatMapStringsSep " " toString r.nftFiles})
${nft} delete table inet "$nft_table" 2>/dev/null || true
${nft} -f "''${files[$slot]}"
${r.routingUp}
# A backend that restarts restarts this too (PartOf), which switches it again.
select_pin "$tag" 60
'';
mkPinDown =
route:
let
r = pinRoutes.${route};
in
pkgs.writeShellScript "proxy-suite-per-app" ''
set -uo pipefail
${decodeTag}
${pinSlot route false}
[[ -n $slot ]] || exit 0
${mkSelect route}
# Blocked until another outbound claims the slot; a backend that is down blocks anyway.
select_pin block 1 2>/dev/null
${nft} delete table inet "$nft_table" 2>/dev/null || true
${r.routingDown}
${pkgs.coreutils}/bin/rm -f "${pinDir}/${route}-$slot"
'';
pinUp = lib.genAttrs pinRouteNames mkPinUp;
pinDown = lib.genAttrs pinRouteNames mkPinDown;
in
{
inherit
perAppViaFile
viaUp
viaDns
viaDown
viaUserStart
viaUserStop
pinRoutes
pinUp
pinDown
;
}
@@ -20,7 +20,9 @@ for (var i = 0; !known && i < templates.length; i++) {
} catch (error) {
return null;
}
if (instance !== uid) {
// A via instance is <uid>-<what the apps run via>.
var owner = template === "proxy-suite-per-app-via-user@" ? instance.split("-")[0] : instance;
if (owner !== uid) {
return null;
}
}
+3
View File
@@ -27,6 +27,9 @@ let
# 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";
# A global profile brought up for `apps run --via`, by proxy-ctl as the app starts.
"proxy-suite-awg-app@" = "perApp";
"proxy-suite-awg-if@" = "outbounds";
"proxy-suite-awg-runtime-sync." = "outbounds";
"proxy-suite-autoproxy-learn." = "autoProxy";
"proxy-suite-zapret2-cutoff." = "zapret";
@@ -2,7 +2,10 @@ def sing_box_preserved_rules:
[.route.rules[]
| select(((.action? // "") == "hijack-dns")
and (((.inbound? // []) | index("xray-dns-in")) != null))];
.outbounds = ($obs[0] + .outbounds)
# perAppRouting.via's pin rules, which no route mode replaces.
def is_pin: ((.outbound? // "") | type) == "string" and ((.outbound? // "") | startswith("proxy-suite-pin-"));
([.route.rules[]? | select(is_pin)]) as $pin_rules
| .outbounds = ($obs[0] + .outbounds)
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
else . end
@@ -27,3 +30,13 @@ def sing_box_preserved_rules:
else . end
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
# Pins after the common hijack-dns and sniff rules, so a pinned app's lookups are answered
# as any other's, and before every rule that picks an outbound.
| .route.rules |= [.[] | select(is_pin | not)]
| (.route.rules | map((.action? // "") == "sniff") | index(true)) as $sniff
| .route.rules = (if $sniff == null then $pin_rules + .route.rules
else .route.rules[:$sniff + 1] + $pin_rules + .route.rules[$sniff + 1:] end)
# Each pin's selector takes any outbound, block first: a slot nobody switched blocks.
| ([.outbounds[].tag | select(startswith("proxy-suite-pin-") | not)]) as $tags
| .outbounds |= map(if .type == "selector" and (.tag | startswith("proxy-suite-pin-"))
then .outbounds = (["block"] + ($tags - ["block"])) | .default = "block" else . end)
@@ -5,6 +5,9 @@
proxyInboundsGuardPrivate,
proxyInboundsGuardStrategy ? null,
userDnsRules ? [ ],
# proxy.dns.remote as a sing-box server, for the AmneziaWG interfaces added at runtime; null
# when there are none.
awgRuntimeDnsServer ? null,
}:
let
@@ -16,6 +19,20 @@ else
(fillTemplate ./backend-filter-sing-box.template.jq {
userDnsRuleCount = toString (builtins.length userDnsRules);
})
# An outbound on such an interface resolves through it (awg-dns-<tag>), as a declared one
# does; only its server cannot be in the build-time config.
+ lib.optionalString (awgRuntimeDnsServer != null) ''
| ([.dns.servers[]?.tag]) as $have
| .dns.servers += [
.outbounds[]
| select(.type == "direct" and (.bind_interface | type) == "string"
and ((.domain_resolver? // "") | type) == "string"
and ((.domain_resolver? // "") | startswith("awg-dns-")))
| select(.domain_resolver as $t | $have | index($t) | not)
| {tag: .domain_resolver, bind_interface} + ${builtins.toJSON awgRuntimeDnsServer}
+ (if .routing_mark then {routing_mark} else {} end)
]
''
+ lib.optionalString proxyInboundsGuardPrivate (
fillTemplate ./backend-filter-private-guard.template.jq {
resolveStrategy = lib.optionalString (
@@ -9,6 +9,7 @@
whitelistBypassJoiners,
awgOutbounds,
awgRuntimeOutbounds ? false,
awgRuntimeIfaceOutbounds ? false,
constants,
pureXrayEnabled,
hybridEnabled,
@@ -182,6 +183,38 @@ let
_proxy_suite_record_tag_source "$1" "$3"
}
${lib.optionalString awgRuntimeIfaceOutbounds ''
# $1 tag, $2 its slot: an AmneziaWG outbound added at runtime on an interface of its
# own, as mkInterfaceOutboundBlock has it. sing-box resolves through the interface
# with a server the backend filter adds for awg-dns-<tag>; XRay resolves as usual.
_proxy_suite_add_awg_interface() {
local ob
case "$2" in
"" | *[!0-9]*) return 1 ;;
esac
[ "$2" -lt ${toString constants.awgRuntimeIfaceSlots} ] || return 1
ob=$(${jq} -nc --arg t "$1" --arg i "${constants.awgRuntimeIfacePrefix}$2" ${
lib.escapeShellArg (
if pureXrayEnabled then
''{protocol: "freedom", tag: $t, streamSettings: {sockopt: ({interface: $i}${
lib.optionalString (routingMark != null) " + {mark: ${toString routingMark}}"
})}}''
else
''{type: "direct", tag: $t, bind_interface: $i, domain_resolver: ("${constants.awgDnsServerTag ""}" + $t)}${
lib.optionalString (routingMark != null) " + {routing_mark: ${toString routingMark}}"
}''
)
}) || return 1
${
if hybridEnabled then
''_proxy_suite_add_sing_box_ob "$ob"''
else
''OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")''
}
_proxy_suite_record_tag_source "$1" awg
}
''}
# $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() {
@@ -507,7 +540,15 @@ let
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" "$(_proxy_suite_read_source "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.port" 2>/dev/null | head -n 1)" runtime ;;
*.awg)
${lib.optionalString awgRuntimeIfaceOutbounds ''
if [ -e "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.iface" ]; then
_proxy_suite_add_awg_interface "$RUNTIME_OB_TAG" "$(_proxy_suite_read_source "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.iface" 2>/dev/null | head -n 1)"
else
''}
_proxy_suite_add_socks_hop "$RUNTIME_OB_TAG" "$(_proxy_suite_read_source "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.port" 2>/dev/null | head -n 1)" runtime
${lib.optionalString awgRuntimeIfaceOutbounds "fi"}
;;
*) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(_proxy_suite_read_source "$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
+10
View File
@@ -129,6 +129,7 @@ let
whitelistBypassJoiners
awgOutbounds
awgRuntimeOutbounds
awgRuntimeIfaceOutbounds
constants
pureXrayEnabled
hybridEnabled
@@ -161,6 +162,15 @@ let
proxyInboundsGuardStrategy
;
userDnsRules = proxyCfg.dns.singBox.rules;
awgRuntimeDnsServer =
if ctx.awgRuntimeIfaceOutbounds then
{
inherit (proxyCfg.dns.remote) type;
server = proxyCfg.dns.remote.address;
server_port = proxyCfg.dns.remote.port;
}
else
null;
};
backendJqFilterFile = pkgs.writeText "proxy-suite-core" backendJqFilter;
+80
View File
@@ -16,6 +16,8 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretEnabled
perAppViaInterfaceOutbounds
perAppViaRuntime
sshProxyOutboundEnabled
sshProxyUnitEnabled
torOutboundEnabled
@@ -68,6 +70,10 @@ let
"sing-box";
localProxyAuthEnabled = ctx.localProxy.authEnabled;
# `apps run --via`: an "interface" AmneziaWG outbound to run through, declared or to come.
perAppViaAwg = perAppViaInterfaceOutbounds != [ ] || perAppViaRuntime || ctx.perAppViaProfiles;
# Or any outbound, through a pin slot: either way, the apps' slices and their marking.
perAppViaEnabled = perAppViaAwg || perAppRouting.pinUp != { };
# For the root units reading what userControl's group writes (outbounds.d,
# subscriptions.d): the file system read-only but for their own directories, so no
@@ -294,6 +300,75 @@ let
execStop = "${perAppRouting.perAppZapretUserRuleStop} %i";
};
}
# `apps run --via <tag>`: an instance per outbound, up while anyone runs through it: its
# rules, and the forwarder its apps' lookups go to. Each user's apps in its slice are
# marked by the next unit (<uid>-<instance>).
{
enable = perAppViaAwg;
name = "proxy-suite-per-app-via@";
value = mkRestartingService {
description = "proxy-suite per-app routing via %i";
execStartPre = "${perAppRouting.viaUp} %i";
execStart = "${perAppRouting.viaDns} %i";
execStopPost = "${perAppRouting.viaDown} %i";
runtimeDirectory = "proxy-suite-per-app-via-%i";
extraServiceConfig = {
# Ready once the forwarder listens, so the app's first lookup finds it.
Type = "notify";
NotifyAccess = "main";
RestartSec = 2;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
ProtectClock = true;
ProtectHostname = true;
ProtectKernelLogs = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
LockPersonality = true;
# nft and ip rules, and SO_MARK on the forwarder's sockets.
CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
};
};
}
]
# `apps run --via <tag>` for any other outbound: a pin slot of per-app TProxy or TUN for
# each outbound apps run through. Part of the backend whose selector it switches: a
# restart of that switches it again.
++ map (route: {
enable = true;
name = "proxy-suite-per-app-via-${route}@";
value =
let
backend = perAppRouting.pinRoutes.${route}.backend;
in
mkOneshotService {
description = "proxy-suite per-app ${route} pin for the outbound %i (in hex)";
execStart = "${perAppRouting.pinUp.${route}} %i";
execStop = "${perAppRouting.pinDown.${route}} %i";
after = [ backend ];
requires = [ backend ];
# As per-app TProxy: under a global mode, proxy-ctl runs the app without its route.
conflicts = [
"${serviceNames.tproxy}.service"
"${serviceNames.tun}.service"
];
}
// {
partOf = [ backend ];
};
}) (builtins.attrNames perAppRouting.pinUp)
++ [
{
enable = perAppViaEnabled;
name = "proxy-suite-per-app-via-user@";
value = mkOneshotService {
description = "Enable proxy-suite per-app via marking for %i";
execStart = "${perAppRouting.viaUserStart} %i";
execStop = "${perAppRouting.viaUserStop} %i";
};
}
{
# Not gated on hasSubscriptions: runtime subscriptions need refreshing too.
enable = proxyEnabled;
@@ -379,6 +454,11 @@ let
name = "${serviceNames.perAppZapret}-anchor";
value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
}
{
enable = perAppViaEnabled;
name = "proxy-suite-per-app-via-anchor@";
value = mkAnchorService "proxy-suite-per-app-via-%i.slice" "Anchor service for the proxy-suite per-app via %i slice";
}
];
timerEntries = [