fix: hardening
This commit is contained in:
168 files changed
+9166
-1644
No files matched your search
@@ -68,6 +68,10 @@ rec {
|
||||
ExecStart = execStart;
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
# Backing off to two minutes: a unit that cannot come up would refetch what it lacks
|
||||
# every 5 s for good.
|
||||
RestartSteps = 5;
|
||||
RestartMaxDelaySec = 120;
|
||||
RuntimeDirectory = runtimeDirectory;
|
||||
}
|
||||
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
|
||||
@@ -128,11 +132,13 @@ rec {
|
||||
execStart,
|
||||
execStop,
|
||||
}:
|
||||
mkOneshotService {
|
||||
# Requires=: holds the shared backend up (StopWhenUnneeded=) and restarts this with it,
|
||||
# its crash included. Restarted by a switch, not stopped and started: a stop drops the hold.
|
||||
lib.recursiveUpdate (mkOneshotService {
|
||||
inherit description execStart execStop;
|
||||
requires = [ "${backendService}.service" ];
|
||||
after = [ "${backendService}.service" ];
|
||||
};
|
||||
}) { serviceConfig."X-StopIfChanged" = false; };
|
||||
|
||||
mkAnchorService =
|
||||
sliceName: description:
|
||||
@@ -201,6 +207,19 @@ rec {
|
||||
${nft} delete table ${family} ${table} 2>/dev/null || true
|
||||
'';
|
||||
|
||||
# A table's rules file swapped in whole, in one transaction: for a reload after the
|
||||
# firewall flushed the ruleset, where a delete-then-load would leave a gap.
|
||||
mkNftReplaceTable =
|
||||
{
|
||||
nft,
|
||||
family,
|
||||
table,
|
||||
file,
|
||||
}:
|
||||
''
|
||||
{ printf '%s\n' "table ${family} ${table}" "delete table ${family} ${table}"; cat ${file}; } | ${nft} -f -
|
||||
'';
|
||||
|
||||
mkIpRuleDeleteByFwmark =
|
||||
{
|
||||
ip,
|
||||
@@ -275,11 +294,15 @@ rec {
|
||||
;
|
||||
}}
|
||||
${mkIpLocalDefaultRouteDelete { inherit ip family table; }}
|
||||
${ip} ${family} route del unreachable default table ${toString table} 2>/dev/null || true
|
||||
'')
|
||||
[
|
||||
"-4"
|
||||
"-6"
|
||||
];
|
||||
]
|
||||
+ ''
|
||||
while ${ip} -6 rule del fwmark ${toString fwmark} table main suppress_prefixlength 0 2>/dev/null; do :; done
|
||||
'';
|
||||
|
||||
mkTproxyRoutingUp =
|
||||
{
|
||||
@@ -291,7 +314,17 @@ rec {
|
||||
lib.concatMapStrings (family: ''
|
||||
${ip} ${family} route replace local default dev lo table ${toString table}
|
||||
${ip} ${family} rule add fwmark ${toString fwmark} table ${toString table}
|
||||
'') ([ "-4" ] ++ lib.optional ipv6 "-6");
|
||||
'') ([ "-4" ] ++ lib.optional ipv6 "-6")
|
||||
# Without proxy.ipv6, marked IPv6 would leave directly: unreachable instead, so apps fall
|
||||
# back to IPv4. Not where the kernel has no IPv6 at all. On-link IPv6 still goes by main
|
||||
# (suppress_prefixlength 0: any route but its default); added last, it is looked at first.
|
||||
+ lib.optionalString (!ipv6) ''
|
||||
if [ -e /proc/net/if_inet6 ]; then
|
||||
${ip} -6 route replace unreachable default table ${toString table}
|
||||
${ip} -6 rule add fwmark ${toString fwmark} table ${toString table}
|
||||
${ip} -6 rule add fwmark ${toString fwmark} table main suppress_prefixlength 0
|
||||
fi
|
||||
'';
|
||||
|
||||
mkIpLinkDelete =
|
||||
{
|
||||
|
||||
@@ -113,6 +113,10 @@ let
|
||||
ip
|
||||
nft
|
||||
;
|
||||
# NixOS's firewall loads the tables in constants.persistedNftDir itself (hosts/nixos.nix).
|
||||
firewallIncludesTables = cfg.host.privileged && cfg.host.kind == "nixos";
|
||||
# Fetches subscriptions through the tunnel (subscriptions.nix): no daemon, never exempt.
|
||||
subscriptionFetchUser = "proxy-suite-fetch";
|
||||
# Filled in below; lazily, so the sub-modules can read each other's results.
|
||||
inherit scripts perAppRouting;
|
||||
};
|
||||
|
||||
@@ -60,6 +60,9 @@ in
|
||||
proxychainsConfigFile
|
||||
amneziaWgProfileNamesFile
|
||||
;
|
||||
withSystemd = constants.serviceManager != "supervisor";
|
||||
withLnav = cfg.tools.lnav.enable;
|
||||
withCurlImpersonate = cfg.tools.curlImpersonate.enable;
|
||||
env = {
|
||||
CLASH_API = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||
SELECTION = selectionMode;
|
||||
@@ -134,7 +137,6 @@ in
|
||||
INBOUNDS_ENABLED = flag proxyInboundsEnabled;
|
||||
INBOUNDS_LINKS_FILE = proxyInboundsLinksFile;
|
||||
INBOUNDS_STATS_FILE = constants.inboundStatsFile;
|
||||
INBOUNDS_XRAY = proxyInboundsXray;
|
||||
INBOUNDS_API = "unix://${constants.inboundStatsApiSocket}";
|
||||
INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile;
|
||||
INBOUNDS_SUB_BASE_URL =
|
||||
@@ -153,19 +155,28 @@ in
|
||||
OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile;
|
||||
RUNTIME_OUTBOUNDS_DIR = constants.runtimeOutboundsDir;
|
||||
RUNTIME_SUBS_DIR = constants.runtimeSubscriptionsDir;
|
||||
RUNTIME_SUBS_ALLOW_HTTP = flag proxyCfg.runtimeSubscriptions.allowHttp;
|
||||
USER_CONTROL_GROUP = userControlCfg.group;
|
||||
# {group: [scopes]}: what proxy-suite-clash-api lets each group's members ask.
|
||||
USER_CONTROL_GROUPS = builtins.toJSON ctx.clashBrokerGroups;
|
||||
LOCAL_PROXY_URL = "http://${localProxy.hostPart}:${toString proxyCfg.listener.port}";
|
||||
AUTOPROXY_ENABLED = flag proxyCfg.autoProxy.enable;
|
||||
AUTOPROXY_STATE_DIR = constants.autoProxyStateDir;
|
||||
AUTOPROXY_SPOOL_DIR = constants.autoProxySpoolDir;
|
||||
TOR_CONTROL_SOCKET = constants.torControlSocket;
|
||||
SING_BOX = "${singBoxCfg.package}/bin/sing-box";
|
||||
STATE_DIR = constants.stateDir;
|
||||
RUNTIME_DIR = constants.runtimeDir;
|
||||
SERVICE_MANAGER = constants.serviceManager;
|
||||
PRIVILEGED = flag constants.privileged;
|
||||
}
|
||||
# Only the engines this host runs, so the other stays out of the closure; unset,
|
||||
# proxy_ctl.py looks on PATH and skips what it cannot run.
|
||||
// lib.optionalAttrs ctx.singBoxEnabled {
|
||||
SING_BOX = "${singBoxCfg.package}/bin/sing-box";
|
||||
}
|
||||
// lib.optionalAttrs proxyInboundsEnabled {
|
||||
INBOUNDS_XRAY = proxyInboundsXray;
|
||||
}
|
||||
// lib.optionalAttrs ctx.clashBrokerEnabled {
|
||||
CLASH_BROKER = constants.clashBrokerSocket;
|
||||
}
|
||||
|
||||
@@ -102,6 +102,10 @@ let
|
||||
++ lib.optional cfg.whitelistBypass.enable {
|
||||
path = "${constants.stateDir}/whitelist-bypass";
|
||||
scope = "whitelistBypass";
|
||||
}
|
||||
++ lib.optional cfg.proxy.autoProxy.enable {
|
||||
path = constants.autoProxySpoolDir;
|
||||
scope = "autoProxy";
|
||||
};
|
||||
|
||||
serviceUnits = import ./units.nix {
|
||||
@@ -122,7 +126,12 @@ let
|
||||
import ../autoproxy.nix {
|
||||
inherit lib pkgs cfg;
|
||||
inherit (control) proxyCtl;
|
||||
inherit (constants) autoProxyStateDir runtimeDir journalctl;
|
||||
inherit (constants)
|
||||
autoProxyStateDir
|
||||
autoProxySpoolDir
|
||||
runtimeDir
|
||||
journalctl
|
||||
;
|
||||
inherit userControlAllows;
|
||||
}
|
||||
);
|
||||
@@ -140,8 +149,17 @@ let
|
||||
# health/ takes hints from watchdogs; groups-state.json is for the front ends.
|
||||
RuntimeDirectory = "proxy-suite-outbound-groups";
|
||||
RuntimeDirectoryMode = "0755";
|
||||
}
|
||||
// lib.optionalAttrs cfg.host.privileged {
|
||||
# health/ is the watchdogs' (root's and the service user's) to write to, not every
|
||||
# local user's. Made here, with the capabilities the watcher lacks.
|
||||
ExecStartPre = "+${pkgs.coreutils}/bin/install -d -m 1730 -o root -g ${constants.serviceUser} ${constants.runtimeDir}/proxy-suite-outbound-groups/health";
|
||||
}
|
||||
// {
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
# Root without capabilities still owns the disks' device nodes.
|
||||
PrivateDevices = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
ProtectClock = true;
|
||||
@@ -176,6 +194,8 @@ let
|
||||
CapabilityBoundingSet = [ "" ];
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
# Root without capabilities still owns the disks' device nodes.
|
||||
PrivateDevices = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
ProtectClock = true;
|
||||
@@ -242,8 +262,10 @@ lib.mkMerge [
|
||||
services.proxy-suite.internal = {
|
||||
# The GUI's pkexec needs its setuid wrapper.
|
||||
polkit.pkexecWrapper = lib.mkIf (cfg.enable && cfg.gui.enable) true;
|
||||
# See constants.serviceUser.
|
||||
systemUsers = [ constants.serviceUser ];
|
||||
# See constants.serviceUser; and the subscription fetcher's (subscriptions.nix).
|
||||
systemUsers =
|
||||
constants.ownTrafficUsers
|
||||
++ lib.optional (constants.privileged && proxyEnabled) context.ctx.subscriptionFetchUser;
|
||||
|
||||
packages = [
|
||||
control.proxyCtl
|
||||
@@ -289,13 +311,17 @@ lib.mkMerge [
|
||||
# carry a mark whose table has no route back. Only those: the LAN is not trusted.
|
||||
(lib.mkIf (tproxyLanSysctl != { }) (
|
||||
let
|
||||
rules = lib.concatMapStrings (interface: ''
|
||||
iifname "${interface}" meta mark ${toString globalTproxy.fwmark} accept
|
||||
'') globalTproxy.lanInterfaces;
|
||||
rules =
|
||||
extra:
|
||||
lib.concatMapStrings (interface: ''
|
||||
iifname "${interface}" meta mark ${toString globalTproxy.fwmark}${extra} accept
|
||||
'') globalTproxy.lanInterfaces;
|
||||
in
|
||||
{
|
||||
extraInputRules = rules;
|
||||
extraReversePathFilterRules = rules;
|
||||
# Into the backend's transparent socket alone: while it restarts, the mark would
|
||||
# otherwise let a gateway client into any of this host's own listeners.
|
||||
extraInputRules = rules " socket transparent 1";
|
||||
extraReversePathFilterRules = rules "";
|
||||
}
|
||||
))
|
||||
];
|
||||
@@ -306,18 +332,12 @@ lib.mkMerge [
|
||||
);
|
||||
|
||||
polkit.enable = lib.mkIf (cfg.enable && (userControlEnabled || cfg.gui.enable)) true;
|
||||
# The GUI's "Retry as Root" and root toggle run proxy-ctl through pkexec: one
|
||||
# admin password then covers the next few minutes, as sudo's does in the TUI.
|
||||
# The GUI's "Retry as Root" runs proxy-ctl through pkexec (polkit.nix), by the path
|
||||
# proxy_model.elevated uses.
|
||||
polkit.actions = lib.mkIf (cfg.enable && cfg.gui.enable) {
|
||||
"${polkit.proxyCtlActionId}.policy" = polkit.mkProxyCtlAction "${control.proxyCtl}/bin/proxy-ctl";
|
||||
};
|
||||
polkit.rules = lib.mkMerge [
|
||||
(lib.mkIf (cfg.enable && cfg.gui.enable) ''
|
||||
polkit.addRule(function(action, subject) {
|
||||
if (action.id === "org.freedesktop.policykit.exec" &&
|
||||
action.lookup("program") === "${control.proxyCtl}/bin/proxy-ctl") {
|
||||
return polkit.Result.AUTH_ADMIN_KEEP;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
'')
|
||||
(lib.mkIf (cfg.enable && userControlEnabled) ''
|
||||
polkit.addRule(function(action, subject) {
|
||||
if (!(${polkit.userControlPolkitMember})) {
|
||||
@@ -356,6 +376,18 @@ lib.mkMerge [
|
||||
"${constants.runtimeInboundsDir}/listeners"
|
||||
]
|
||||
))
|
||||
# inbound_runtime.py's lock, outside the spool the members write to; it opens it
|
||||
# read-only and never makes it, so it must be here first.
|
||||
(lib.mkIf (cfg.enable && derived.proxyInboundsRuntimeEnabled && constants.privileged) (
|
||||
[
|
||||
"f ${constants.runtimeInboundsLock} 0640 root ${
|
||||
if userControlAllows "inbounds" then userControlCfg.group else "root"
|
||||
} -"
|
||||
]
|
||||
++ map (g: "a+ ${constants.runtimeInboundsLock} - - - - g:${g}:r") (
|
||||
derived.userControlExtraGroupsFor "inbounds"
|
||||
)
|
||||
))
|
||||
# Per-app profiles added at runtime: read by everyone who runs apps, written with the
|
||||
# perApp scope.
|
||||
(lib.mkIf (cfg.enable && cfg.perAppRouting.enable) [
|
||||
@@ -436,6 +468,33 @@ lib.mkMerge [
|
||||
"proxy-suite: no outbounds or subscriptions are declared; the proxy will not start"
|
||||
+ " until one is added with `proxy-ctl proxy outbounds add`"
|
||||
)
|
||||
# On Android every app reaches loopback: one that finds the proxy there learns its exit,
|
||||
# or tells whoever asks that this phone runs one.
|
||||
++ lib.optional (cfg.host.kind == "nix-on-droid" && proxyEnabled && !localProxyAuthEnabled) (
|
||||
"proxy-suite: proxy.listener takes no login, and on Android every app can use it;"
|
||||
+ " set proxy.listener.auth"
|
||||
)
|
||||
# Tor's SOCKS port and OpenSSH's -D take no login: without the nftables guard
|
||||
# (constants.daemonMetadataGuard), every local user reaches those exits.
|
||||
++
|
||||
lib.optional
|
||||
(
|
||||
!constants.privileged
|
||||
&& (
|
||||
derived.torOutboundEnabled || (derived.sshProxyOutboundEnabled && !derived.sshProxyNativeOutbound)
|
||||
)
|
||||
)
|
||||
(
|
||||
"proxy-suite: without root, nothing keeps other local users (on Android, other apps) off"
|
||||
+ " the loopback SOCKS ports of ${
|
||||
lib.concatStringsSep " and " (
|
||||
lib.optional derived.torOutboundEnabled "Tor (tor.socksPort)"
|
||||
++ lib.optional (
|
||||
derived.sshProxyOutboundEnabled && !derived.sshProxyNativeOutbound
|
||||
) "the OpenSSH tunnel (sshProxy.listener.port)"
|
||||
)
|
||||
}: neither takes a login. sing-box dials SSH natively, with no listener"
|
||||
)
|
||||
++
|
||||
lib.optional
|
||||
(
|
||||
@@ -452,15 +511,30 @@ lib.mkMerge [
|
||||
+ " anyone who reaches the port uses your outbounds; set listener.auth, or keep it off the"
|
||||
+ " firewall's allowed ports"
|
||||
)
|
||||
# The prober and proxy-ctl's outbound test dial these without credentials.
|
||||
# OpenSSH's -D takes no login at all.
|
||||
++
|
||||
lib.optional
|
||||
(proxyEnabled && localProxyAuthEnabled && proxyCfg.autoProxy.enable && !pureXrayEnabled)
|
||||
(
|
||||
"proxy-suite: proxy.listener.auth does not cover autoProxy's loopback listeners"
|
||||
+ " (ports ${toString proxyCfg.autoProxy.probeBasePort}-${
|
||||
toString (proxyCfg.autoProxy.probeBasePort + proxyCfg.autoProxy.maxExits - 1)
|
||||
} and ${toString constants.outboundTestPort}): every local user reaches your exits through them"
|
||||
cfg.sshProxy.enable
|
||||
&& !(
|
||||
lib.hasPrefix "127." cfg.sshProxy.listener.address
|
||||
|| cfg.sshProxy.listener.address == "::1"
|
||||
|| cfg.sshProxy.listener.address == "localhost"
|
||||
)
|
||||
)
|
||||
(
|
||||
"proxy-suite: sshProxy.listener.address is ${cfg.sshProxy.listener.address}: its SOCKS port takes"
|
||||
+ " no login, so anyone who reaches it uses the SSH server; keep it on loopback, or off the"
|
||||
+ " firewall's allowed ports"
|
||||
)
|
||||
++
|
||||
lib.optional
|
||||
(
|
||||
cfg.warp.enable && cfg.warp.generatorUrl != null && !lib.hasPrefix "https://" cfg.warp.generatorUrl
|
||||
)
|
||||
(
|
||||
"proxy-suite: warp.generatorUrl is not https://: anyone on the way can hand back a profile"
|
||||
+ " of their own, and the WARP traffic goes to them"
|
||||
)
|
||||
# rules/proxy-inbounds.nix guards the names of this host only where XRay leaves names
|
||||
# unresolved, or where IP aliases catch a name that resolves here first.
|
||||
|
||||
@@ -34,6 +34,7 @@ let
|
||||
findBin
|
||||
headBin
|
||||
;
|
||||
inherit (ctx.constants) systemctl;
|
||||
}
|
||||
// slices
|
||||
);
|
||||
|
||||
@@ -73,7 +73,6 @@ let
|
||||
family = "-6";
|
||||
table = perAppRoutingTun.routeTable;
|
||||
}}
|
||||
${nft} -f ${perAppTunChainFile}
|
||||
${perAppTunWaitForInterface}
|
||||
# The backend may not have brought the link up yet, and routes via a down link fail
|
||||
# with "Device for nexthop is not up".
|
||||
@@ -84,7 +83,8 @@ let
|
||||
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable}
|
||||
# No uplink src, as in xrayTunUpScript: it goes stale when the uplink address changes.
|
||||
${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
|
||||
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
# Cleared above, so it goes in; if it did not, marked apps would leave by the main table.
|
||||
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
|
||||
${
|
||||
if ipv6 then
|
||||
''
|
||||
@@ -100,6 +100,8 @@ let
|
||||
''
|
||||
}
|
||||
${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
# The marking last, once its routes are in (as tproxyUpScript).
|
||||
${nft} -f ${perAppTunChainFile}
|
||||
'';
|
||||
|
||||
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
@@ -140,6 +142,27 @@ let
|
||||
${builders.flushResolvedCaches}
|
||||
'';
|
||||
|
||||
# After a firewall reload that flushed the ruleset: the marking alone (the routes stay).
|
||||
# The users' rules go back in with their own units' reload, ordered after this one.
|
||||
perAppTunReloadScript = pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -euo pipefail
|
||||
${builders.mkNftReplaceTable {
|
||||
inherit nft;
|
||||
family = "inet";
|
||||
table = "proxy_suite_per_app_tun";
|
||||
file = perAppTunChainFile;
|
||||
}}
|
||||
'';
|
||||
perAppTproxyReloadScript = pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -euo pipefail
|
||||
${builders.mkNftReplaceTable {
|
||||
inherit nft;
|
||||
family = "inet";
|
||||
table = "proxy_suite_per_app_tproxy";
|
||||
file = perAppTproxyRulesFile;
|
||||
}}
|
||||
'';
|
||||
|
||||
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -euo pipefail
|
||||
|
||||
@@ -154,13 +177,14 @@ let
|
||||
table = perAppRoutingTproxy.routeTable;
|
||||
}}
|
||||
|
||||
${nft} -f ${perAppTproxyRulesFile}
|
||||
# The route first, then the marking (as tproxyUpScript).
|
||||
${builders.mkTproxyRoutingUp {
|
||||
inherit ip;
|
||||
inherit ipv6;
|
||||
fwmark = perAppRoutingTproxy.fwmark;
|
||||
table = perAppRoutingTproxy.routeTable;
|
||||
}}
|
||||
${nft} -f ${perAppTproxyRulesFile}
|
||||
'';
|
||||
|
||||
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
@@ -181,8 +205,10 @@ in
|
||||
{
|
||||
inherit
|
||||
perAppTunUpScript
|
||||
perAppTunReloadScript
|
||||
perAppTunDownScript
|
||||
perAppTproxyUpScript
|
||||
perAppTproxyReloadScript
|
||||
perAppTproxyDownScript
|
||||
;
|
||||
}
|
||||
@@ -13,9 +13,83 @@
|
||||
grepBin,
|
||||
findBin,
|
||||
headBin,
|
||||
systemctl,
|
||||
}:
|
||||
|
||||
let
|
||||
# The hold: what a per-app slice sends unmarked is turned away, in a table no backend
|
||||
# touches, so a backend restart or crash holds the apps rather than letting them out
|
||||
# directly. It goes with the user's unit, not its restart, and mirrors the route's exceptions.
|
||||
holdTable = "proxy_suite_per_app_hold";
|
||||
# nftables.nix's RESERVED_IP and RESERVED_IP6, which the TUN and TProxy chains leave alone.
|
||||
reserved4 = [
|
||||
"10.0.0.0/8"
|
||||
"100.64.0.0/10"
|
||||
"127.0.0.0/8"
|
||||
"169.254.0.0/16"
|
||||
"172.16.0.0/12"
|
||||
"192.0.0.0/24"
|
||||
"224.0.0.0/4"
|
||||
"240.0.0.0/4"
|
||||
"255.255.255.255/32"
|
||||
];
|
||||
reserved6 = [
|
||||
"::/128"
|
||||
"::1/128"
|
||||
"::ffff:0:0/96"
|
||||
"fc00::/7"
|
||||
"fe80::/10"
|
||||
"ff00::/8"
|
||||
];
|
||||
nftSet = items: "{ ${lib.concatStringsSep ", " items} }";
|
||||
# As shell words in double quotes, printed one per line: a mark of "$mark" is the shell's.
|
||||
# Every route marks lookups wherever the resolver is, loopback's too. `allow`: what goes
|
||||
# unmarked, in either family.
|
||||
mkHoldBodies =
|
||||
{
|
||||
# The marks the route's packets carry, as shell text (a number, or "$mark").
|
||||
marks,
|
||||
allow,
|
||||
}:
|
||||
let
|
||||
# Not merely "no mark": since Linux 5.17 CAP_NET_RAW sets one (ping -m), so a held app
|
||||
# could mark its way out. A kernel AmneziaWG interface's own encapsulated packets keep
|
||||
# the app's socket with the interface's FwMark: the via route lists that mark too.
|
||||
unmarked = "meta mark != { ${lib.concatStringsSep ", " marks} }";
|
||||
reject = "reject with icmpx admin-prohibited";
|
||||
allow4 = builtins.filter (cidr: !lib.hasInfix ":" cidr) allow;
|
||||
allow6 = builtins.filter (lib.hasInfix ":") allow;
|
||||
bodies = [
|
||||
"${unmarked} meta l4proto { tcp, udp } th dport 53 ${reject}"
|
||||
"${unmarked} ct direction != reply ip daddr != ${nftSet allow4} ${reject}"
|
||||
"${unmarked} ct direction != reply ip6 daddr != ${nftSet allow6} ${reject}"
|
||||
];
|
||||
in
|
||||
"printf '%s\\n' ${lib.concatMapStringsSep " " (body: "\"${body}\"") bodies}";
|
||||
tunHold =
|
||||
mark:
|
||||
mkHoldBodies {
|
||||
marks = [ mark ];
|
||||
allow = reserved4 ++ reserved6 ++ perAppRoutingTun.localSubnets;
|
||||
};
|
||||
tproxyHold =
|
||||
mark:
|
||||
mkHoldBodies {
|
||||
marks = [ mark ];
|
||||
allow = reserved4 ++ reserved6 ++ perAppRoutingTproxy.localSubnets;
|
||||
};
|
||||
# Deletes the rules of one comment from a chain, if the table is there.
|
||||
dropRulesByComment = table: chain: comment: ''
|
||||
handles=$(${nft} -a list chain ${table} ${chain} 2>/dev/null \
|
||||
| ${grepBin} -F "comment \"${comment}\"" \
|
||||
| ${awk} '{ print $NF }' || true)
|
||||
if [ -n "$handles" ]; then
|
||||
while IFS= read -r handle; do
|
||||
[ -n "$handle" ] || continue
|
||||
${nft} delete rule ${table} ${chain} handle "$handle" || true
|
||||
done <<< "$handles"
|
||||
fi
|
||||
'';
|
||||
# `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.
|
||||
@@ -30,6 +104,8 @@ let
|
||||
sliceLabel,
|
||||
markRule,
|
||||
prelude ? "",
|
||||
# Shell text printing the hold's rule bodies (mkHoldBodies); null: no hold.
|
||||
hold ? null,
|
||||
}:
|
||||
pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -euo pipefail
|
||||
@@ -58,6 +134,22 @@ let
|
||||
fi
|
||||
cgroup_path=''${cgroup_dir#/sys/fs/cgroup/}
|
||||
cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }')
|
||||
${lib.optionalString (hold != null) ''
|
||||
# The hold first: from here on, nothing of the app leaves unmarked.
|
||||
hold_comment="$rule_comment_prefix-hold"
|
||||
${dropRulesByComment "inet ${holdTable}" "output" "$hold_comment"}
|
||||
{
|
||||
printf '%s\n' "add table inet ${holdTable}" \
|
||||
"add chain inet ${holdTable} output { type filter hook output priority filter; policy accept; }"
|
||||
# In a subshell: `hold` may be a case statement over several lines.
|
||||
(
|
||||
${hold}
|
||||
) | while IFS= read -r body; do
|
||||
printf 'add rule inet ${holdTable} output socket cgroupv2 level %s "%s" %s comment "%s"\n' \
|
||||
"$cgroup_level" "$cgroup_path" "$body" "$hold_comment"
|
||||
done
|
||||
} | ${nft} -f -
|
||||
''}
|
||||
|
||||
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
|
||||
| ${grepBin} -F "comment \"$rule_comment_prefix-mark\"" \
|
||||
@@ -81,12 +173,24 @@ let
|
||||
nftTable,
|
||||
nftChain,
|
||||
prelude ? "",
|
||||
# Whether the start put a hold in (mkUserRuleStart).
|
||||
hold ? false,
|
||||
# The unit this runs in, as shell text.
|
||||
unitName ? ''"proxy-suite-${name}-user@$uid.service"'',
|
||||
}:
|
||||
pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -euo pipefail
|
||||
${prelude}
|
||||
uid="$1"
|
||||
rule_comment_prefix="proxy-suite-${name}-user-$uid"
|
||||
${lib.optionalString hold ''
|
||||
# Its restart (the backend's restart or crash, through Requires=, or a switch) keeps the
|
||||
# hold, a job of that type until the stop half is done: the app waits for its marking.
|
||||
if ! ${systemctl} list-jobs --no-legend ${unitName} \
|
||||
| ${awk} '$3 == "restart" { found = 1 } END { exit !found }'; then
|
||||
${dropRulesByComment "inet ${holdTable}" "output" "$rule_comment_prefix-hold"}
|
||||
fi
|
||||
''}
|
||||
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
|
||||
| ${grepBin} -F "comment \"$rule_comment_prefix-mark\"" \
|
||||
| ${awk} '{ print $NF }' || true)
|
||||
@@ -107,28 +211,32 @@ let
|
||||
sliceName = perAppTunSliceName;
|
||||
sliceLabel = "app TUN";
|
||||
markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}";
|
||||
hold = tunHold (toString perAppRoutingTun.fwmark);
|
||||
};
|
||||
perAppTunUserRuleStop = mkUserRuleStop {
|
||||
name = "per-app-tun";
|
||||
nftFamily = "inet";
|
||||
nftTable = "proxy_suite_per_app_tun";
|
||||
nftChain = "app_mark";
|
||||
hold = true;
|
||||
};
|
||||
|
||||
perAppTproxyUserRuleStart = mkUserRuleStart {
|
||||
name = "per-app-tproxy";
|
||||
nftFamily = "inet";
|
||||
nftTable = "proxy_suite_per_app_tproxy";
|
||||
nftChain = "output";
|
||||
nftChain = "app_mark";
|
||||
sliceName = perAppTproxySliceName;
|
||||
sliceLabel = "app TProxy";
|
||||
markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}";
|
||||
hold = tproxyHold (toString perAppRoutingTproxy.fwmark);
|
||||
};
|
||||
perAppTproxyUserRuleStop = mkUserRuleStop {
|
||||
name = "per-app-tproxy";
|
||||
nftFamily = "inet";
|
||||
nftTable = "proxy_suite_per_app_tproxy";
|
||||
nftChain = "output";
|
||||
nftChain = "app_mark";
|
||||
hold = true;
|
||||
};
|
||||
|
||||
perAppZapretUserRuleStart = mkUserRuleStart {
|
||||
@@ -148,7 +256,13 @@ let
|
||||
};
|
||||
in
|
||||
{
|
||||
inherit mkUserRuleStart mkUserRuleStop;
|
||||
inherit
|
||||
mkUserRuleStart
|
||||
mkUserRuleStop
|
||||
mkHoldBodies
|
||||
tunHold
|
||||
tproxyHold
|
||||
;
|
||||
inherit
|
||||
perAppTunUserRuleStart
|
||||
perAppTunUserRuleStop
|
||||
|
||||
@@ -27,6 +27,7 @@ let
|
||||
ip
|
||||
nft
|
||||
jq
|
||||
awk
|
||||
;
|
||||
inherit (constants)
|
||||
awgPerAppRulePriority
|
||||
@@ -91,7 +92,7 @@ let
|
||||
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
|
||||
if [[ ! $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] || (( 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
|
||||
@@ -112,9 +113,16 @@ let
|
||||
}
|
||||
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
|
||||
# One added at runtime: the slot its interface runs in, as proxy-suite-awg-if@ keeps it;
|
||||
# else the spool's, which is group-writable (O_NOFOLLOW), and names the slot it gets
|
||||
# next, not the one a tag removed and added again still runs in.
|
||||
slot_file="/run/proxy-suite-awg-if-$tag/slot"
|
||||
if [[ -s $slot_file && ! -L $slot_file ]]; then
|
||||
slot=$(${pkgs.coreutils}/bin/head -n 1 "$slot_file")
|
||||
else
|
||||
slot=$(${pkgs.coreutils}/bin/dd if="${runtimeOutboundsDir}/$tag.iface" iflag=nofollow,nonblock status=none 2>/dev/null | ${pkgs.coreutils}/bin/head -n 1 || true)
|
||||
fi
|
||||
if [[ $slot =~ ^(0|[1-9][0-9]{0,2})$ ]] && (( 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),
|
||||
@@ -217,6 +225,12 @@ let
|
||||
type nat hook postrouting priority srcnat; policy accept;
|
||||
oifname "$interface" meta mark $mark masquerade
|
||||
}
|
||||
# The app's packets out of any other interface: the ip rules are gone (networkd
|
||||
# drops rules it did not make), and the main table took them to the uplink.
|
||||
chain misrouted {
|
||||
type filter hook postrouting priority filter; policy accept;
|
||||
meta mark $mark oifname != { "lo", "$interface" } drop
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
@@ -237,9 +251,15 @@ let
|
||||
exec ${python3} ${proxySuiteScriptsDir}/per_app_dns.py --port "$dns_port" --mark "$mark" "''${servers[@]}"
|
||||
'';
|
||||
|
||||
# A failure keeps the marking and the unreachable rule, so the apps are turned away rather
|
||||
# than sent out directly until the restart; viaUp clears it. A stop takes it all down.
|
||||
viaDown = pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -uo pipefail
|
||||
${resolveInstance}
|
||||
if [[ ''${SERVICE_RESULT:-success} != success ]]; then
|
||||
echo "proxy-suite: per-app via $1 failed ($SERVICE_RESULT): its apps are held until it is back" >&2
|
||||
exit 0
|
||||
fi
|
||||
${nft} delete table inet "$nft_table" 2>/dev/null || true
|
||||
${rulesDown}
|
||||
'';
|
||||
@@ -279,7 +299,33 @@ let
|
||||
slice_name="proxy-suite-per-app-via-$key.slice"
|
||||
set -- "''${instance%%-*}"
|
||||
'';
|
||||
viaUserStart = userRules.mkUserRuleStart {
|
||||
# The hold (user-rules.nix), by what the key runs via: an AmneziaWG interface takes the
|
||||
# private ranges too (as viaUp's chain does), a pin slot what its route's backend takes.
|
||||
viaHold = ''
|
||||
case "$key" in
|
||||
awg-* | app-*)
|
||||
${userRules.mkHoldBodies {
|
||||
marks = [
|
||||
"$mark"
|
||||
(toString cfg.proxy.tproxy.proxyMark)
|
||||
];
|
||||
allow = [
|
||||
"127.0.0.0/8"
|
||||
"169.254.0.0/16"
|
||||
"224.0.0.0/4"
|
||||
"255.255.255.255/32"
|
||||
"::1/128"
|
||||
"fe80::/10"
|
||||
"ff00::/8"
|
||||
]
|
||||
++ perAppRoutingCfg.via.localSubnets;
|
||||
}}
|
||||
;;
|
||||
tproxy-*) ${userRules.tproxyHold "$mark"} ;;
|
||||
tun-*) ${userRules.tunHold "$mark"} ;;
|
||||
esac
|
||||
'';
|
||||
viaUserRule = userRules.mkUserRuleStart {
|
||||
name = "per-app-via-$key";
|
||||
nftFamily = "inet";
|
||||
nftTable = "$nft_table";
|
||||
@@ -288,6 +334,7 @@ let
|
||||
sliceLabel = "app via";
|
||||
markRule = "meta mark set $mark ct mark set $mark";
|
||||
prelude = userPrelude;
|
||||
hold = viaHold;
|
||||
};
|
||||
viaUserStop = userRules.mkUserRuleStop {
|
||||
name = "per-app-via-$key";
|
||||
@@ -295,7 +342,88 @@ let
|
||||
nftTable = "$nft_table";
|
||||
nftChain = "$nft_chain";
|
||||
prelude = userPrelude;
|
||||
hold = true;
|
||||
unitName = ''"proxy-suite-per-app-via-user@$instance.service"'';
|
||||
};
|
||||
|
||||
# $1, a user unit's instance <uid>-<key>, to $key and $via_unit, the unit whose table
|
||||
# the key's user rules go in.
|
||||
viaUserKey = ''
|
||||
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[1]}
|
||||
case "$key" in
|
||||
awg-* | app-*) via_unit="proxy-suite-per-app-via@$key.service" ;;
|
||||
*) via_unit="proxy-suite-per-app-via-''${key%%-*}@''${key#*-}.service" ;;
|
||||
esac
|
||||
'';
|
||||
# Held while a user's rule goes in, and while the last user's unit takes the via unit
|
||||
# down: no rule lands in a table on its way out, to leave its app unmarked.
|
||||
viaUsersLock = ''
|
||||
${pkgs.coreutils}/bin/mkdir -p ${pinDir}
|
||||
exec 8>>"${pinDir}/users-$key.lock"
|
||||
${flock} 8
|
||||
'';
|
||||
viaUserStart = pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -euo pipefail
|
||||
${viaUserKey}
|
||||
${viaUsersLock}
|
||||
# proxy-ctl starts it first; one on its way down takes the table with it.
|
||||
if [[ $(${constants.systemctl} show --property=ActiveState --value "$via_unit") != active ]]; then
|
||||
echo "proxy-suite: $via_unit is not up" >&2
|
||||
exit 1
|
||||
fi
|
||||
${viaUserRule} "$1"
|
||||
'';
|
||||
# ExecStopPost of a user's unit: with no other user's left, the via unit goes, and the
|
||||
# global profile it ran through. perApp members may only start those (polkit.nix):
|
||||
# stopping one under another user's apps would send them out unmarked.
|
||||
viaRetire = pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -euo pipefail
|
||||
${viaUserKey}
|
||||
# Its own restart (a job of that type until the stop half is done) comes straight back.
|
||||
if ${constants.systemctl} list-jobs --no-legend "proxy-suite-per-app-via-user@$1.service" \
|
||||
| ${awk} '$3 == "restart" { found = 1 } END { exit !found }'; then
|
||||
exit 0
|
||||
fi
|
||||
${viaUsersLock}
|
||||
others=$(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \
|
||||
"proxy-suite-per-app-via-user@*-$key.service" \
|
||||
| ${awk} -v self="proxy-suite-per-app-via-user@$1.service" '$1 != self')
|
||||
[[ -z $others ]] || exit 0
|
||||
was=$(${constants.systemctl} show --property=ActiveState --value "$via_unit" || true)
|
||||
${constants.systemctl} stop "$via_unit"
|
||||
# A failed one kept its rules to hold its apps (viaDown), and a stop runs nothing more for
|
||||
# it: with no app left, they go here.
|
||||
if [[ $was == failed && ( $key == awg-* || $key == app-* ) ]]; then
|
||||
SERVICE_RESULT=success ${viaDown} "$key" || true
|
||||
${constants.systemctl} reset-failed "$via_unit" 2>/dev/null || true
|
||||
fi
|
||||
${lib.optionalString perAppViaProfiles ''
|
||||
# After the via unit: its stop reads the profile's slot.
|
||||
if [[ $key == app-* ]]; then
|
||||
set -- "''${key#app-}"
|
||||
${decodeTag}
|
||||
${constants.systemctl} stop "proxy-suite-awg-app@$tag.service"
|
||||
fi
|
||||
''}
|
||||
'';
|
||||
# ExecStartPost of the via units, $1 the key. Their table starts empty, also on a restart
|
||||
# (Restart=, or that of the backend a pin is part of), under users' units that stay
|
||||
# active: their rules go back in here, or their apps would go out unmarked.
|
||||
viaReapply = pkgs.writeShellScript "proxy-suite-per-app" ''
|
||||
set -uo pipefail
|
||||
${constants.systemctl} list-units --plain --no-legend --state=active \
|
||||
"proxy-suite-per-app-via-user@*-''${1:-}.service" \
|
||||
| while read -r unit _; do
|
||||
instance=''${unit#proxy-suite-per-app-via-user@}
|
||||
${viaUserRule} "''${instance%.service}" \
|
||||
|| echo "proxy-suite: the rule of $unit did not go back in" >&2
|
||||
done
|
||||
'';
|
||||
# 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";
|
||||
@@ -308,7 +436,7 @@ let
|
||||
tableBase = constants.perAppPinTproxyTableBase;
|
||||
nftFiles = perAppPinTproxyRulesFiles;
|
||||
# Where the user rule units add their cgroup rules, as for the per-app TProxy's own.
|
||||
nftChain = "output";
|
||||
nftChain = "app_mark";
|
||||
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||
secretFile = "${constants.runtimeDir}/proxy-suite-socks/clash-secret";
|
||||
backend = "proxy-suite-socks.service";
|
||||
@@ -458,6 +586,26 @@ let
|
||||
set -euo pipefail
|
||||
${decodeTag}
|
||||
${pinSlot route true}
|
||||
if [[ -z $slot ]]; then
|
||||
# Every slot taken: one that nothing has run through for a minute (no user's marking
|
||||
# unit for it), as a perApp member could leave behind by starting the unit alone, is
|
||||
# taken back. The minute spares one proxy-ctl has just started for its app.
|
||||
for (( n = 0; n < ${toString perAppPinSlots}; n++ )); do
|
||||
slot_file="${pinDir}/${route}-$n"
|
||||
[[ -f $slot_file ]] || continue
|
||||
other=$(< "$slot_file")
|
||||
[[ $other =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || continue
|
||||
(( $(${pkgs.coreutils}/bin/date +%s) - $(${pkgs.coreutils}/bin/stat -c %Y "$slot_file") >= 60 )) || continue
|
||||
other_hex=$(printf '%s' "$other" | ${pkgs.coreutils}/bin/od -An -tx1 | ${pkgs.coreutils}/bin/tr -d ' \n')
|
||||
if [[ -z $(${constants.systemctl} list-units --plain --no-legend --state=active,activating,reloading \
|
||||
"proxy-suite-per-app-via-user@*-${route}-$other_hex.service") ]]; then
|
||||
echo "proxy-suite: taking back ${route} pin slot $n from '$other': nothing runs through it" >&2
|
||||
${constants.systemctl} stop "proxy-suite-per-app-via-${route}@$other_hex.service" || true
|
||||
break
|
||||
fi
|
||||
done
|
||||
${pinSlot route true}
|
||||
fi
|
||||
if [[ -z $slot ]]; then
|
||||
echo "proxy-suite: all ${toString perAppPinSlots} ${route} pin slots are taken (perAppRouting.via.pinSlots)" >&2
|
||||
exit 1
|
||||
@@ -472,8 +620,10 @@ let
|
||||
trap release ERR
|
||||
files=(${lib.concatMapStringsSep " " toString r.nftFiles})
|
||||
${nft} delete table inet "$nft_table" 2>/dev/null || true
|
||||
${nft} -f "''${files[$slot]}"
|
||||
# The route first, then the marking: a packet marked before its route is in would
|
||||
# leave by the main table, and the kill switch lets the mark through.
|
||||
${r.routingUp}
|
||||
${nft} -f "''${files[$slot]}"
|
||||
# A backend that restarts restarts this too (PartOf), which switches it again.
|
||||
select_pin "$tag" 60
|
||||
'';
|
||||
@@ -505,8 +655,11 @@ in
|
||||
viaUp
|
||||
viaDns
|
||||
viaDown
|
||||
viaUserRule
|
||||
viaUserStart
|
||||
viaUserStop
|
||||
viaRetire
|
||||
viaReapply
|
||||
pinRoutes
|
||||
pinUp
|
||||
pinDown
|
||||
|
||||
@@ -3,6 +3,8 @@ if (typeof unit !== "string" || @verbs@.indexOf(verb) === -1) {
|
||||
return null;
|
||||
}
|
||||
var known = @units@.indexOf(unit) !== -1;
|
||||
// One of the subject's own per-app marking units, rather than one every user shares.
|
||||
var own = false;
|
||||
var templates = @templates@;
|
||||
for (var i = 0; !known && i < templates.length; i++) {
|
||||
var template = templates[i];
|
||||
@@ -25,6 +27,7 @@ for (var i = 0; !known && i < templates.length; i++) {
|
||||
if (owner !== uid) {
|
||||
return null;
|
||||
}
|
||||
own = true;
|
||||
}
|
||||
known = true;
|
||||
}
|
||||
@@ -40,6 +43,9 @@ for (var prefix in scopeByUnitPrefix) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (scope === "perApp" && !own && @sharedVerbs@.indexOf(verb) === -1) {
|
||||
return null;
|
||||
}
|
||||
// Any of the subject's groups that holds the scope.
|
||||
var groupScopes = @groupScopes@;
|
||||
for (var group in groupScopes) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Polkit rule body granting userControl group members passwordless control over the
|
||||
# units of their scopes.
|
||||
# units of their scopes; and the GUI's pkexec action for proxy-ctl.
|
||||
#
|
||||
# Only units this module declares, by their full names: systemd asks the same
|
||||
# manage-units question with the same unit name for a transient unit
|
||||
@@ -30,6 +30,10 @@ let
|
||||
# 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";
|
||||
# Their watchdogs, which pull them in (Wants=, BindsTo=): the same scope, or "services"
|
||||
# would start what it does not hold.
|
||||
"proxy-suite-awg-app-watchdog@" = "perApp";
|
||||
"proxy-suite-awg-if-watchdog@" = "outbounds";
|
||||
"proxy-suite-awg-runtime-sync." = "outbounds";
|
||||
"proxy-suite-autoproxy-learn." = "autoProxy";
|
||||
"proxy-suite-zapret2-cutoff." = "zapret";
|
||||
@@ -50,10 +54,18 @@ let
|
||||
"reload-or-try-restart"
|
||||
"reset-failed"
|
||||
];
|
||||
# perApp units every user's apps share: start only, as a stop or restart would send the
|
||||
# other users' apps out unmarked. They go once idle on their own.
|
||||
sharedVerbs = [
|
||||
"start"
|
||||
"reset-failed"
|
||||
];
|
||||
proxyCtlActionId = "io.github.FUFSoB.ProxySuite.proxy-ctl";
|
||||
in
|
||||
{
|
||||
userControlPolkitRules = fillTemplate ./polkit-rules.template.js {
|
||||
verbs = builtins.toJSON verbs;
|
||||
sharedVerbs = builtins.toJSON sharedVerbs;
|
||||
units = builtins.toJSON units;
|
||||
templates = builtins.toJSON templates;
|
||||
coreutils = pkgs.coreutils;
|
||||
@@ -64,4 +76,36 @@ in
|
||||
userControlPolkitMember = lib.concatMapStringsSep " || " (
|
||||
group: "subject.isInGroup(${builtins.toJSON group})"
|
||||
) (builtins.attrNames userControlGroupScopes);
|
||||
|
||||
inherit proxyCtlActionId;
|
||||
# pkexec's action for proxy-ctl, by its path after realpath. The password every time: a
|
||||
# kept grant covers the whole session, and proxy-ctl as root runs commands (`apps run`).
|
||||
mkProxyCtlAction =
|
||||
program:
|
||||
pkgs.writeTextFile {
|
||||
name = "proxy-suite-polkit-action";
|
||||
# polkitd skips a file it cannot parse, and pkexec then falls back to its generic action.
|
||||
checkPhase = ''
|
||||
${pkgs.libxml2.bin}/bin/xmllint --noout --nonet \
|
||||
--dtdvalid ${pkgs.polkit.out}/share/polkit-1/policyconfig-1.dtd "$target"
|
||||
'';
|
||||
text = ''
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
|
||||
<policyconfig>
|
||||
<vendor>proxy-suite</vendor>
|
||||
<action id="${proxyCtlActionId}">
|
||||
<description>Run proxy-ctl as root</description>
|
||||
<message>Authentication is required to change proxy-suite as root</message>
|
||||
<defaults>
|
||||
<allow_any>auth_admin</allow_any>
|
||||
<allow_inactive>auth_admin</allow_inactive>
|
||||
<allow_active>auth_admin</allow_active>
|
||||
</defaults>
|
||||
<annotate key="org.freedesktop.policykit.exec.path">${program}</annotate>
|
||||
</action>
|
||||
</policyconfig>
|
||||
'';
|
||||
};
|
||||
}
|
||||
@@ -31,6 +31,10 @@ let
|
||||
builders
|
||||
constants
|
||||
;
|
||||
# A value in a shell comment, on that one line: a newline in a tag (types.str) would end
|
||||
# the comment and run the rest as root.
|
||||
oneLine = value: builtins.replaceStrings [ "\n" "\r" ] [ " " " " ] (toString value);
|
||||
|
||||
runtimeDir = "${constants.runtimeDir}/proxy-suite-inbounds";
|
||||
linksFile = "${runtimeDir}/links.json";
|
||||
subscriptionsFile = "${runtimeDir}/subscriptions.json";
|
||||
@@ -126,7 +130,7 @@ let
|
||||
in
|
||||
if urlSource == null then
|
||||
''
|
||||
# via outbound: ${ob.tag} (static xray json)
|
||||
# via outbound: ${oneLine ob.tag} (static xray json)
|
||||
OB_JSON=$(cat ${
|
||||
pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON (ob.xrayJson // { inherit (ob) tag; }))
|
||||
})
|
||||
@@ -135,7 +139,7 @@ let
|
||||
''
|
||||
else
|
||||
''
|
||||
# via outbound: ${ob.tag}
|
||||
# via outbound: ${oneLine ob.tag}
|
||||
URL=$(cat ${lib.escapeShellArg urlSource})
|
||||
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \
|
||||
--backend xray --tag ${lib.escapeShellArg ob.tag})
|
||||
@@ -165,9 +169,12 @@ let
|
||||
printf '%s' "$body" > "$SUB_DIR.new/$token"
|
||||
done
|
||||
chmod -R u=rwX,g=rX,o= "$SUB_DIR.new"
|
||||
# Traverse-only for the group: the web server opens a token by name but can never
|
||||
# list them all (autoindex, a stray directory listing).
|
||||
chmod 0710 "$SUB_DIR.new"
|
||||
${constants.ifPrivileged ''
|
||||
${pkgs.coreutils}/bin/chgrp -R ${lib.escapeShellArg subsCfg.group} "$SUB_DIR.new" ||
|
||||
echo "proxy-suite: group ${subsCfg.group} cannot be given the subscriptions; they stay root-only" >&2''}
|
||||
echo "proxy-suite: group "${lib.escapeShellArg subsCfg.group}" cannot be given the subscriptions; they stay root-only" >&2''}
|
||||
rm -rf "$SUB_DIR"
|
||||
mv "$SUB_DIR.new" "$SUB_DIR"
|
||||
${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}"
|
||||
@@ -194,11 +201,19 @@ let
|
||||
|
||||
INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED")
|
||||
|
||||
# Every address this host has now, for the direct outbound's fence (rules/proxy-inbounds.nix):
|
||||
# one it gains later is fenced from the next start. Where netlink is closed (Android), the
|
||||
# fence keeps what the configuration knows.
|
||||
if ! HOST_ADDRESSES=$(${ip} -j addr show | ${jq} -c '[.[].addr_info[]?.local | strings] | unique'); then
|
||||
echo "proxy-suite: cannot list this host's addresses; direct reaches any port of those not configured" >&2
|
||||
HOST_ADDRESSES='[]'
|
||||
fi
|
||||
|
||||
OUTBOUNDS_JSON='[]'
|
||||
${viaOutboundsBlock}
|
||||
|
||||
${lib.optionalString needsLocalProxyAuth ''
|
||||
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
|
||||
LOCAL_PROXY_PASSWORD="$(cat ${lib.escapeShellArg localProxyAuthPasswordSource})"
|
||||
''}
|
||||
|
||||
# With inbounds.runtime, the routing rules are build-inbound.py's: the template's with the
|
||||
@@ -216,8 +231,19 @@ let
|
||||
} \
|
||||
--argjson runtime ${if proxyInboundsRuntimeEnabled then "true" else "false"} \
|
||||
--slurpfile rendered <(printf '%s' "$RENDERED") \
|
||||
--argjson host_addresses "$HOST_ADDRESSES" \
|
||||
'.inbounds += $ibs[0]
|
||||
| (.outbounds[] | select(.tag == "direct") | .settings.finalRules[] | select(._hostAddresses))
|
||||
|= (.ip += ($host_addresses - .ip) | del(._hostAddresses))
|
||||
| .outbounds = $obs[0] + .outbounds
|
||||
# A via outbound that is freedom too (xrayJson, say, for its fragment settings)
|
||||
# dials from this host as "direct" does: the same fence, ahead of its own rules;
|
||||
# all of it but the closing allow of "direct", which would end them.
|
||||
| ([.outbounds[] | select(.tag == "direct") | .settings.finalRules // []] | first // []) as $fence
|
||||
| (.outbounds[] | select(.protocol == "freedom" and .tag != "direct"
|
||||
and ((.tag // "") | startswith("direct-self") | not)))
|
||||
|= (.settings = ((.settings // {})
|
||||
| .finalRules = (($fence | map(select(. != {action: "allow"}))) + (.finalRules // []))))
|
||||
| if $runtime then
|
||||
.routing.rules = $rendered[0].rules
|
||||
| .outbounds += $rendered[0].selfOutbounds
|
||||
@@ -262,7 +288,8 @@ let
|
||||
else
|
||||
''
|
||||
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"''}
|
||||
chmod 640 "$RUNTIME_DIR/config.json.tmp"
|
||||
# Without root the group is the user's own primary one, which may be shared.
|
||||
chmod ${if constants.privileged then "640" else "600"} "$RUNTIME_DIR/config.json.tmp"
|
||||
''
|
||||
}
|
||||
${constants.grantFileAcl pkgs ''"$RUNTIME_DIR/config.json.tmp"''
|
||||
@@ -271,26 +298,17 @@ let
|
||||
}
|
||||
mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json"
|
||||
|
||||
# The stats API's socket takes this setgid directory's group: XRay cannot chown it.
|
||||
# The stats API's socket: the daemon's and root's alone. Whoever reaches it can reset the
|
||||
# counters, wiping per-user traffic before the collector adds it up; the stats scope
|
||||
# reads the collector's file instead.
|
||||
API_DIR=$(dirname ${lib.escapeShellArg constants.inboundStatsApiSocket})
|
||||
rm -rf "$API_DIR"
|
||||
${
|
||||
if !constants.privileged then
|
||||
''mkdir -m 0700 "$API_DIR"''
|
||||
else if userControlAllows "stats" then
|
||||
''
|
||||
install -d -m 2750 -o ${constants.serviceUser} -g ${lib.escapeShellArg userControlCfg.group} "$API_DIR" ||
|
||||
install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"''
|
||||
else
|
||||
''install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"''
|
||||
''install -d -m 0700 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"''
|
||||
}
|
||||
# userControl.groups with the stats scope: into the directory, and onto the socket XRay
|
||||
# makes in it as its own group is (a default entry; the socket's mode caps it).
|
||||
${lib.optionalString (constants.privileged && userControlExtraGroupsFor "stats" != [ ]) ''
|
||||
${pkgs.acl}/bin/setfacl -m ${
|
||||
lib.concatMapStringsSep "," (g: "g:${g}:rx,d:g:${g}:rwx") (userControlExtraGroupsFor "stats")
|
||||
} -- "$API_DIR"
|
||||
''}
|
||||
|
||||
${writeLinksBlock}
|
||||
${writeSubscriptionsBlock}
|
||||
@@ -300,7 +318,8 @@ let
|
||||
'';
|
||||
|
||||
# Adds XRay's counters to the daily totals, read and reset in one call, and notes who
|
||||
# is online. Run by a timer, and by the inbounds' ExecStop, so a restart loses nothing.
|
||||
# is online: .online, for `proxy-ctl inbounds online` without the API. Run by a timer,
|
||||
# and by the inbounds' ExecStop, so a restart loses nothing.
|
||||
collectInboundStats = pkgs.writeShellScript "proxy-suite-inbounds" ''
|
||||
set -euo pipefail
|
||||
file=${lib.escapeShellArg constants.inboundStatsFile}
|
||||
@@ -326,18 +345,22 @@ let
|
||||
}
|
||||
[ -s "$file" ] || echo '{}' > "$file"
|
||||
tmp=$(${pkgs.coreutils}/bin/mktemp "$file.XXXXXX")
|
||||
${jq} --argjson q "$reading" --argjson online "$online" --argjson awg "$awg" \
|
||||
# Slurped, not --argjson: one argument holds at most 128 KiB, which a few hundred users'
|
||||
# counters outgrow, and the reading above already reset them.
|
||||
${jq} --slurpfile q_ <(printf '%s' "$reading") --slurpfile online_ <(printf '%s' "$online") \
|
||||
--slurpfile awg_ <(printf '%s' "$awg") \
|
||||
--arg day "$(${pkgs.coreutils}/bin/date +%F)" \
|
||||
--argjson now "$(${pkgs.coreutils}/bin/date +%s)" \
|
||||
-f ${
|
||||
"\$q_[0] as \$q | \$online_[0] as \$online | \$awg_[0] as \$awg | $(< ${
|
||||
builtins.path {
|
||||
name = "proxy-suite-inbounds";
|
||||
path = ../inbound-stats-add.jq;
|
||||
}
|
||||
} "$file" > "$tmp"
|
||||
})
|
||||
| .online = (\$online.users // [])" "$file" > "$tmp"
|
||||
${lib.optionalString (userControlAllows "stats") ''
|
||||
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" ||
|
||||
echo "proxy-suite: group ${userControlCfg.group} cannot read the stats; they stay root-only" >&2
|
||||
echo "proxy-suite: group "${lib.escapeShellArg userControlCfg.group}" cannot read the stats; they stay root-only" >&2
|
||||
''}
|
||||
chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp"
|
||||
${constants.grantFileAcl pkgs ''"$tmp"'' (userControlExtraGroupsFor "stats") "r"}
|
||||
|
||||
@@ -15,6 +15,7 @@ let
|
||||
tproxyLanSysctl
|
||||
perAppRoutingTun
|
||||
proxyCfg
|
||||
cfg
|
||||
;
|
||||
inherit (proxyCfg) ipv6;
|
||||
inherit (constants)
|
||||
@@ -47,6 +48,23 @@ let
|
||||
"-6"
|
||||
];
|
||||
|
||||
# A table, as NixOS's firewall includes it (constants.persistedNftDir): written aside and
|
||||
# renamed, never half there. `lines`: its rules, as shell words printed one per line.
|
||||
persistedNftDir = ctx.constants.persistedNftDir;
|
||||
persistTable =
|
||||
table: lines:
|
||||
lib.optionalString ctx.firewallIncludesTables ''
|
||||
${pkgs.coreutils}/bin/install -d -m 0700 ${persistedNftDir}
|
||||
(
|
||||
umask 077
|
||||
printf '%s\n' "add table inet ${table}" "delete table inet ${table}" ${lines} \
|
||||
> ${persistedNftDir}/${table}.nft.tmp
|
||||
) && mv -f ${persistedNftDir}/${table}.nft.tmp ${persistedNftDir}/${table}.nft
|
||||
'';
|
||||
# Before the table goes: a firewall reload in between would bring it back.
|
||||
unpersistTable =
|
||||
table: lib.optionalString ctx.firewallIncludesTables "rm -f ${persistedNftDir}/${table}.nft";
|
||||
|
||||
# Replies to connections from outside (sshd, a game server, anything listening) take
|
||||
# proxyMark, so the fwmark rule sends them back out the way they came instead of into
|
||||
# the TUN, where nothing expects them. Locally started connections stay "original".
|
||||
@@ -72,18 +90,30 @@ let
|
||||
in
|
||||
{
|
||||
# One nft transaction swaps the old table for the new: traffic never sees neither. Also the
|
||||
# unit's reload, which a switch runs instead of a restart (units.nix).
|
||||
# unit's reload, which a switch runs instead of a restart (units.nix). The time daemons'
|
||||
# users are looked up here rather than named in the rules: a missing one would fail them all.
|
||||
killSwitchUpScript = pkgs.writeShellScript "proxy-suite-routing" ''
|
||||
set -euo pipefail
|
||||
${nft} -f - <<'EOF'
|
||||
uids=()
|
||||
for user in ${lib.escapeShellArgs cfg.killSwitch.timeSyncUsers}; do
|
||||
uid=$(${pkgs.coreutils}/bin/id -u -- "$user" 2>/dev/null) && uids+=("$uid")
|
||||
done
|
||||
time_sync=
|
||||
if (( ''${#uids[@]} )); then
|
||||
time_sync="add element inet proxy_suite_killswitch time_sync_uids { $(IFS=,; echo "''${uids[*]}") }"
|
||||
fi
|
||||
${nft} -f - <<EOF
|
||||
add table inet proxy_suite_killswitch
|
||||
delete table inet proxy_suite_killswitch
|
||||
include "${killSwitchRulesFile}"
|
||||
$time_sync
|
||||
EOF
|
||||
${persistTable "proxy_suite_killswitch" '''include "${killSwitchRulesFile}"' ''${time_sync:+"$time_sync"}''}
|
||||
'';
|
||||
|
||||
killSwitchDownScript = pkgs.writeShellScript "proxy-suite-routing" ''
|
||||
set +e
|
||||
${unpersistTable "proxy_suite_killswitch"}
|
||||
${deleteKillSwitchTable}
|
||||
'';
|
||||
|
||||
@@ -95,6 +125,10 @@ in
|
||||
tun6_route_prefix=${lib.escapeShellArg globalTunIPv6RoutePrefix}
|
||||
tun_addr=""
|
||||
tun_route_prefix=""
|
||||
# A kernel booted with ipv6.disable=1 refuses every -6 command: the TUN still comes up.
|
||||
families=(-4)
|
||||
if [ -e /proc/net/if_inet6 ]; then families+=(-6); fi
|
||||
has_ipv6() { [ "''${#families[@]}" = 2 ]; }
|
||||
|
||||
${builders.cidrNetworkFunction}
|
||||
|
||||
@@ -113,6 +147,7 @@ in
|
||||
${deleteXrayTunRules}
|
||||
${deleteXrayTunReplyTable}
|
||||
${nft} -f ${xrayTunReplyRules}
|
||||
${persistTable xrayTunReplyTable "'include \"${xrayTunReplyRules}\"'"}
|
||||
|
||||
# XRay may not have brought the link up yet, and routes via a down link fail with
|
||||
# "Device for nexthop is not up".
|
||||
@@ -121,30 +156,59 @@ in
|
||||
tun_route_prefix="$(cidr_network "$tun_cidr")"
|
||||
|
||||
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface}
|
||||
${lib.optionalString ipv6 ''${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}''}
|
||||
${lib.optionalString ipv6 ''has_ipv6 && ${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}''}
|
||||
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex}
|
||||
# No uplink src: it goes stale when the uplink address changes, and XRay's own sockets
|
||||
# (routed by uid and mark, not bound to an interface) pick theirs from main.
|
||||
${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
|
||||
${lib.optionalString ipv6 ''
|
||||
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
|
||||
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
|
||||
''}
|
||||
${
|
||||
if ipv6 then
|
||||
''
|
||||
if has_ipv6; then
|
||||
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
|
||||
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
|
||||
fi
|
||||
''
|
||||
else
|
||||
''
|
||||
# No IPv6 in the TUN: unreachable, as sing-box's strict_route and the per-app TUN
|
||||
# have it, so apps fall back to IPv4. Without, the rules below would find nothing
|
||||
# in this table and go on to main: every IPv6 connection straight out the uplink.
|
||||
${ip} -6 route replace unreachable default table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
|
||||
''
|
||||
}
|
||||
${lib.optionalString perAppRoutingTun.enable ''
|
||||
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
|
||||
${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
|
||||
for family in "''${families[@]}"; do
|
||||
${ip} "$family" rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
|
||||
done
|
||||
''}
|
||||
service_uid=$(${pkgs.coreutils}/bin/id -u ${constants.serviceUser})
|
||||
${ip} -4 rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main
|
||||
${ip} -6 rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main
|
||||
for family in -4 -6; do
|
||||
for service_user in ${lib.escapeShellArgs constants.ownTrafficUsers}; do
|
||||
service_uid=$(${pkgs.coreutils}/bin/id -u "$service_user")
|
||||
for family in "''${families[@]}"; do
|
||||
${ip} "$family" rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main
|
||||
done
|
||||
done
|
||||
for family in "''${families[@]}"; do
|
||||
${ip} "$family" rule add pref ${toString xrayTunMarkBypassRulePriority} fwmark ${toString globalTproxy.proxyMark} lookup main
|
||||
${ip} "$family" rule add pref ${toString xrayTunDnsRulePriority} ipproto udp dport 53 table ${toString tunAutoRouteTableIndex}
|
||||
${ip} "$family" rule add pref ${toString xrayTunDnsRulePriority} ipproto tcp dport 53 table ${toString tunAutoRouteTableIndex}
|
||||
${ip} "$family" rule add pref ${toString xrayTunMainRulePriority} lookup main suppress_prefixlength 0
|
||||
done
|
||||
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
|
||||
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
|
||||
for family in "''${families[@]}"; do
|
||||
${ip} "$family" rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
|
||||
done
|
||||
'';
|
||||
|
||||
# The reply marking, after a firewall reload that flushed the ruleset: without it, replies
|
||||
# to connections from outside (sshd among them) are routed into the TUN until it restarts.
|
||||
xrayTunReloadScript = pkgs.writeShellScript "proxy-suite-routing" ''
|
||||
set -euo pipefail
|
||||
${builders.mkNftReplaceTable {
|
||||
inherit nft;
|
||||
family = "inet";
|
||||
table = xrayTunReplyTable;
|
||||
file = xrayTunReplyRules;
|
||||
}}
|
||||
'';
|
||||
|
||||
tproxyUpScript = pkgs.writeShellScript "proxy-suite-routing" ''
|
||||
@@ -164,24 +228,50 @@ in
|
||||
table = globalTproxy.routeTable;
|
||||
}}
|
||||
|
||||
${nft} -f ${nftablesRulesFile}
|
||||
# Set on NixOS already; system-manager hosts only get them here.
|
||||
# Set on NixOS already; system-manager hosts only get them here. Left on at the stop:
|
||||
# by then something else (Docker, libvirt) may rely on forwarding too.
|
||||
${lib.concatStrings (
|
||||
lib.mapAttrsToList (name: value: ''
|
||||
${pkgs.procps}/bin/sysctl -q -w ${name}=${toString value}
|
||||
'') tproxyLanSysctl
|
||||
)}
|
||||
# The route first, then the marking: a packet marked before its rule exists would leave
|
||||
# by the main table, and the kill switch lets the mark through.
|
||||
${builders.mkTproxyRoutingUp {
|
||||
inherit ip;
|
||||
inherit ipv6;
|
||||
fwmark = globalTproxy.fwmark;
|
||||
table = globalTproxy.routeTable;
|
||||
}}
|
||||
${nft} -f ${nftablesRulesFile}
|
||||
${persistTable "singbox" "'include \"${nftablesRulesFile}\"'"}
|
||||
'';
|
||||
|
||||
# After a firewall reload that flushed the ruleset (NixOS's flushRuleset, a distribution's
|
||||
# `flush ruleset` config): the marking alone, swapped in whole in one transaction. The
|
||||
# policy routing is no nftables state, and stays.
|
||||
tproxyReloadScript = pkgs.writeShellScript "proxy-suite-routing" ''
|
||||
set -euo pipefail
|
||||
${builders.mkNftReplaceTable {
|
||||
inherit nft;
|
||||
family = "inet";
|
||||
table = "singbox";
|
||||
file = nftablesRulesFile;
|
||||
}}
|
||||
'';
|
||||
|
||||
# The daemon guard (constants.daemonMetadataGuard) as loaded: a static table, so its
|
||||
# listing loads again as it is.
|
||||
persistDaemonGuardScript = pkgs.writeShellScript "proxy-suite-routing" ''
|
||||
set -euo pipefail
|
||||
rules=$(${nft} -s list table inet proxy_suite_daemon_guard) || exit 0
|
||||
${persistTable "proxy_suite_daemon_guard" ''"$rules"''}
|
||||
'';
|
||||
|
||||
tproxyDownScript = pkgs.writeShellScript "proxy-suite-routing" ''
|
||||
set +e
|
||||
|
||||
${unpersistTable "singbox"}
|
||||
${builders.mkNftDeleteTable {
|
||||
inherit nft;
|
||||
family = "inet";
|
||||
@@ -216,6 +306,7 @@ in
|
||||
table = tunAutoRouteTableIndex;
|
||||
}}
|
||||
${deleteXrayTunRules}
|
||||
${unpersistTable xrayTunReplyTable}
|
||||
${deleteXrayTunReplyTable}
|
||||
${builders.mkIpRouteFlushTable {
|
||||
inherit ip;
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
|
||||
# inbounds.routing.blockPrivate (or, without it, this host's loopback), enforced here because
|
||||
# the listener passes names unresolved.
|
||||
# Just before the first direct rule (or last, for a direct final), so names that the
|
||||
# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local
|
||||
# mixed-in clients lose names that resolve private. Rules for other inbounds do not count:
|
||||
# autoProxy's direct probe pin would put the guard first, resolving every name, .onion too.
|
||||
# This host's own addresses too, its public one among them, on every port but those its
|
||||
# clients may reach there (inbounds.serverPorts and the like): dialed from here, a service the
|
||||
# firewall keeps from the internet would answer (the start script lists them).
|
||||
| [{inbound: ["mixed-in"], action: "resolve"@resolveStrategy@},
|
||||
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard
|
||||
{inbound: ["mixed-in"]@rejectMatch@, action: "reject"}]
|
||||
+ (($ARGS.named.host_addresses // []) as $own
|
||||
| if $own == [] or @hostPortsAllOpen@ then [] else [{inbound: ["mixed-in"], ip_cidr: $own@hostPortMatch@, action: "reject"}] end) as $guard
|
||||
| (.route.rules
|
||||
| map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null)
|
||||
| index(true)) as $first_direct
|
||||
|
||||
@@ -4,7 +4,11 @@ def sing_box_preserved_rules:
|
||||
and (((.inbound? // []) | index("xray-dns-in")) != null))];
|
||||
# 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
|
||||
# Slurped (lists of one), not arguments: they grow with the outbounds and rules.
|
||||
$route_rules[0] as $route_rules | $probe_inbounds[0] as $probe_inbounds
|
||||
| $probe_pin_rules[0] as $probe_pin_rules | $autoproxy_rule_sets[0] as $autoproxy_rule_sets
|
||||
| $autoproxy_rules[0] as $autoproxy_rules
|
||||
| ([.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}]
|
||||
@@ -30,6 +34,13 @@ def is_pin: ((.outbound? // "") | type) == "string" and ((.outbound? // "") | st
|
||||
else . end
|
||||
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
|
||||
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
|
||||
# What autoProxy sends through an exit is looked up through the proxy too, as every other
|
||||
# proxied name is (proxy.dns.remote): not by the local resolver, in the clear, for a
|
||||
# destination learned blocked. Its own rule-sets alone, which hold names only.
|
||||
| .dns.rules = ((.dns.rules // []) + [$autoproxy_rules[]
|
||||
| select((.outbound? // "direct") != "direct"
|
||||
and ((.rule_set? // []) | all(startswith("autoproxy-"))) and ((.rule_set? // []) | length > 0))
|
||||
| {rule_set, server: "remote"}])
|
||||
# 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)]
|
||||
|
||||
@@ -13,7 +13,8 @@ def xray_rewrite_proxy_rule($single_tag):
|
||||
end;
|
||||
def xray_preserved_rules:
|
||||
[.routing.rules[]
|
||||
| select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote")];
|
||||
| select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote"
|
||||
or . == "inbounds-private-guard" or . == "inbounds-host-guard")];
|
||||
def xray_final_rule($tag; $single_tag):
|
||||
if $tag == "proxy" and "@selectionMode@" == "urltest" then
|
||||
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
|
||||
@@ -42,7 +43,9 @@ def xray_pin_server_names:
|
||||
else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local")
|
||||
| . + {domains: ($names | map("full:" + .)), skipFallback: true}]
|
||||
end;
|
||||
.outbounds = ($obs[0] + .outbounds)
|
||||
# Slurped (a list of one), not an argument: it grows with the rules.
|
||||
$route_rules[0] as $route_rules
|
||||
| .outbounds = ($obs[0] + .outbounds)
|
||||
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
|
||||
| if $auth_enabled then
|
||||
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
|
||||
@@ -65,11 +68,25 @@ def xray_pin_server_names:
|
||||
# too: name the rest instead. Disabling is a runtime decision, so always.
|
||||
# ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop";
|
||||
# rename one of them if that matters.
|
||||
| if $ARGS.named.xray_selectable == null then . else
|
||||
($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates
|
||||
# Slurped (a list of one), not an argument: every tag of a large subscription.
|
||||
| ($ARGS.named.xray_selectable // [null])[0] as $selectable
|
||||
| if $selectable == null then . else
|
||||
($selectable | map("proxy-suite-ob-" + .)) as $candidates
|
||||
| if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end
|
||||
| if .observatory then .observatory.subjectSelector = $candidates else . end
|
||||
end
|
||||
# This host's own addresses, on every port but those its inbounds' clients may reach there,
|
||||
# just after the inbounds' guard: dialed from here, its public one would reach a service
|
||||
# the firewall keeps from the internet (the start script lists them).
|
||||
| ($ARGS.named.host_addresses // []) as $own
|
||||
| (.routing.rules | map((.ruleTag? // "") == "inbounds-private-guard") | index(true)) as $at
|
||||
| if $own == [] or $at == null or "@hostClosedPorts@" == "" then . else
|
||||
.routing.rules |= [.[] | select((.ruleTag? // "") != "inbounds-host-guard")]
|
||||
| .routing.rules = .routing.rules[:$at + 1]
|
||||
+ [{type: "field", ruleTag: "inbounds-host-guard", inboundTag: ["mixed-in"], ip: $own,
|
||||
port: "@hostClosedPorts@", outboundTag: "block"}]
|
||||
+ .routing.rules[$at + 1:]
|
||||
end
|
||||
| if $xray_single_proxy_tag == "" then
|
||||
.
|
||||
else
|
||||
|
||||
@@ -4,17 +4,31 @@
|
||||
selectionMode,
|
||||
proxyInboundsGuardPrivate,
|
||||
proxyInboundsGuardStrategy ? null,
|
||||
# inbounds.routing.blockPrivate: the guard rejects the private ranges, else loopback alone.
|
||||
proxyInboundsBlockPrivate ? true,
|
||||
proxyInboundsLoopback ? [ ],
|
||||
# The ports of this host's own addresses its inbounds' clients may not reach, as ranges.
|
||||
proxyInboundsHostClosedPorts ? [ ],
|
||||
userDnsRules ? [ ],
|
||||
# proxy.dns.remote as a sing-box server, for the AmneziaWG interfaces added at runtime; null
|
||||
# when there are none.
|
||||
awgRuntimeDnsServer ? null,
|
||||
# proxy.listener on an address other machines reach (0.0.0.0, a LAN address).
|
||||
listenerExposed ? false,
|
||||
}:
|
||||
|
||||
let
|
||||
fillTemplate = import ../../lib/fill-template.nix;
|
||||
# XRay's port list: "80,1000-2000".
|
||||
closedPorts = map (
|
||||
r: if r.from == r.to then toString r.from else "${toString r.from}-${toString r.to}"
|
||||
) proxyInboundsHostClosedPorts;
|
||||
in
|
||||
if pureXrayEnabled then
|
||||
(fillTemplate ./backend-filter-xray.template.jq { inherit selectionMode; })
|
||||
(fillTemplate ./backend-filter-xray.template.jq {
|
||||
inherit selectionMode;
|
||||
hostClosedPorts = lib.concatStringsSep "," closedPorts;
|
||||
})
|
||||
else
|
||||
(fillTemplate ./backend-filter-sing-box.template.jq {
|
||||
userDnsRuleCount = toString (builtins.length userDnsRules);
|
||||
@@ -33,8 +47,45 @@ else
|
||||
+ (if .routing_mark then {routing_mark} else {} end)
|
||||
]
|
||||
''
|
||||
# A listener others reach, without the inbounds' guard: a LAN client could CONNECT to
|
||||
# 127.0.0.1 (or a name resolving there), which the private-ranges rule sends direct, dialed
|
||||
# from here: this host's loopback-only services. This host's own clients may still, and
|
||||
# their names stay unresolved for the proxy.
|
||||
+ lib.optionalString (listenerExposed && !proxyInboundsGuardPrivate) ''
|
||||
| {source_ip_cidr: ["127.0.0.0/8", "::1/128"], invert: true} as $remote
|
||||
| [{type: "logical", mode: "and", rules: [{inbound: ["mixed-in"]}, $remote],
|
||||
action: "resolve", server: "local"},
|
||||
{type: "logical", mode: "and",
|
||||
rules: [{inbound: ["mixed-in"], ip_cidr: ${builtins.toJSON proxyInboundsLoopback}}, $remote],
|
||||
action: "reject"}] as $guard
|
||||
| (.route.rules
|
||||
| map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null)
|
||||
| index(true)) as $first_direct
|
||||
| if $first_direct != null then
|
||||
.route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:]
|
||||
elif (.route.final // "direct") == "direct" then
|
||||
.route.rules += $guard
|
||||
else . end
|
||||
''
|
||||
# No sniffing on mixed-in, where the inbounds' clients arrive: an SNI the rules send direct
|
||||
# would take their connection direct to any address. Their names still route as names.
|
||||
+ lib.optionalString proxyInboundsGuardPrivate ''
|
||||
| (.route.rules[]? | select(.action? == "sniff" and (has("inbound") | not)))
|
||||
|= . + {inbound: ["mixed-in"], invert: true}
|
||||
''
|
||||
+ lib.optionalString proxyInboundsGuardPrivate (
|
||||
fillTemplate ./backend-filter-private-guard.template.jq {
|
||||
rejectMatch =
|
||||
if proxyInboundsBlockPrivate then
|
||||
", ip_is_private: true"
|
||||
else
|
||||
", ip_cidr: ${builtins.toJSON proxyInboundsLoopback}";
|
||||
# sing-box's port_range is always from:to.
|
||||
hostPortMatch = ", port_range: ${
|
||||
builtins.toJSON (map (r: "${toString r.from}:${toString r.to}") proxyInboundsHostClosedPorts)
|
||||
}";
|
||||
# Then there is nothing to reject: no rule, as an empty port_range would match any port.
|
||||
hostPortsAllOpen = lib.boolToString (proxyInboundsHostClosedPorts == [ ]);
|
||||
resolveStrategy = lib.optionalString (
|
||||
proxyInboundsGuardStrategy != null
|
||||
) ", strategy: \"${proxyInboundsGuardStrategy}\"";
|
||||
|
||||
@@ -55,7 +55,9 @@ _proxy_suite_write_xray_sidecar_config() {
|
||||
if [ "$(@jq@ 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
|
||||
return 0
|
||||
fi
|
||||
@jq@ -n \
|
||||
# umask: the file holds every XRay outbound's credentials until the start script's
|
||||
# chmod, in a runtime directory others can list.
|
||||
(umask 077 && @jq@ -n \
|
||||
--arg loglevel "$XRAY_LOGLEVEL" \
|
||||
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
|
||||
--argjson port "$XRAY_SIDECAR_PORT" \
|
||||
@@ -92,5 +94,5 @@ _proxy_suite_write_xray_sidecar_config() {
|
||||
domainStrategy: "AsIs",
|
||||
rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
|
||||
}
|
||||
}' > "$RUNTIME_DIR/xray-sidecar.json"
|
||||
}' > "$RUNTIME_DIR/xray-sidecar.json")
|
||||
}
|
||||
@@ -27,9 +27,17 @@
|
||||
mkSubscriptionBlock,
|
||||
mkSubscriptionLoadHelperBlock,
|
||||
runtimeSubscriptionsBlock,
|
||||
laterTags ? [ ],
|
||||
# The backends, to check a runtime JSON outbound with before it joins the config.
|
||||
singBoxBin ? null,
|
||||
xrayBin ? null,
|
||||
}:
|
||||
|
||||
let
|
||||
# A value in a shell comment, on that one line: a newline in a tag (types.str) would end
|
||||
# the comment and run the rest as root.
|
||||
oneLine = value: builtins.replaceStrings [ "\n" "\r" ] [ " " " " ] (toString value);
|
||||
|
||||
sshProxyTag = "ssh-proxy";
|
||||
torOutboundEnabled = torCfg != null && torCfg.enable && torCfg.asOutbound;
|
||||
groupsJq = builtins.path {
|
||||
@@ -41,12 +49,13 @@ let
|
||||
|
||||
# The keys of an outbound that point the backend at a local file or program, comma-joined;
|
||||
# a sing-box tor outbound as "type: tor". proxy_url_parsers.local_file_keys and proxy-ctl's
|
||||
# _local_file_keys apply the same rule.
|
||||
# _local_file_keys apply the same rule. A non-ASCII key counts as well: Go's JSON
|
||||
# decoding matches field names under Unicode case folding ("maſterKeyLog" is masterKeyLog).
|
||||
localFileKeysJq = ''
|
||||
[(if .type == "tor" then "type: tor" else empty end),
|
||||
(.. | objects | keys[] | ascii_downcase
|
||||
| select(endswith("file") or (endswith("path") and . != "path") or endswith("directory")
|
||||
or IN("masterkeylog", "torrc", "extra_args")))]
|
||||
| select((explode | any(. > 127)) or endswith("file") or (endswith("path") and . != "path")
|
||||
or endswith("directory") or IN("masterkeylog", "torrc", "extra_args")))]
|
||||
| unique | join(", ")
|
||||
'';
|
||||
|
||||
@@ -91,16 +100,24 @@ let
|
||||
case "$pref" in
|
||||
xray)
|
||||
ob=$(_proxy_suite_parse_xray_url "$tag" "$url") || return 1
|
||||
_proxy_suite_check_url_outbound xray "$ob" "$tag" "$source" || return 1
|
||||
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
|
||||
;;
|
||||
sing-box)
|
||||
ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url") || return 1
|
||||
_proxy_suite_check_url_outbound sing-box "$ob" "$tag" "$source" || return 1
|
||||
_proxy_suite_add_sing_box_ob "$ob"
|
||||
;;
|
||||
*)
|
||||
if ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url" 2>"$RUNTIME_DIR/sing-box-parser.err"); then
|
||||
# Created 0600 first: the parser's error can quote the link's id or password,
|
||||
# and the runtime directory is world-listable.
|
||||
(umask 077 && : > "$RUNTIME_DIR/sing-box-parser.err")
|
||||
# One sing-box parses but refuses still gets XRay's turn.
|
||||
if ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url" 2>"$RUNTIME_DIR/sing-box-parser.err") &&
|
||||
_proxy_suite_check_url_outbound sing-box "$ob" "$tag" "$source" 2>/dev/null; then
|
||||
_proxy_suite_add_sing_box_ob "$ob"
|
||||
elif ob=$(_proxy_suite_parse_xray_url "$tag" "$url"); then
|
||||
_proxy_suite_check_url_outbound xray "$ob" "$tag" "$source" || return 1
|
||||
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
|
||||
else
|
||||
echo "proxy-suite: outbound '$tag' cannot be parsed by SingBox or XRay" >&2
|
||||
@@ -115,6 +132,9 @@ let
|
||||
else
|
||||
''
|
||||
ob=$(_proxy_suite_parse_url "$tag" "$url") || return 1
|
||||
_proxy_suite_check_url_outbound ${
|
||||
if pureXrayEnabled then "xray" else "sing-box"
|
||||
} "$ob" "$tag" "$source" || return 1
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
# Raw JSON gets the tag and the routing mark a Nix-declared one gets (rawOutboundJson).
|
||||
@@ -166,14 +186,17 @@ let
|
||||
"" | *[!0-9]*) return 1 ;;
|
||||
esac
|
||||
[ "$2" -ge 1 ] && [ "$2" -le 65535 ] || return 1
|
||||
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
|
||||
# The tunnel's listener takes the hop login (constants.ensureHopLogin).
|
||||
${constants.ensureHopLogin pkgs}
|
||||
ob=$(${jq} -nc --arg t "$1" --argjson p "$2" --arg u ${constants.hopUser} \
|
||||
--rawfile pw ${lib.escapeShellArg constants.hopLoginFile} ${
|
||||
lib.escapeShellArg (
|
||||
if pureXrayEnabled then
|
||||
''{protocol: "socks", tag: $t, settings: {address: "127.0.0.1", port: $p, user: $u, pass: ($pw | rtrimstr("\n"))}}''
|
||||
else
|
||||
''{type: "socks", tag: $t, server: "127.0.0.1", server_port: $p, username: $u, password: ($pw | rtrimstr("\n"))}''
|
||||
)
|
||||
}) || return 1
|
||||
${
|
||||
if hybridEnabled then
|
||||
''_proxy_suite_add_sing_box_ob "$ob"''
|
||||
@@ -219,19 +242,25 @@ let
|
||||
# written before links existed: those entries share as JSON until the next update).
|
||||
_proxy_suite_record_subscription_share() {
|
||||
SUBSCRIPTION_URLS_JSON=$(${jq} --arg t "$1" --rawfile u <(_proxy_suite_read_source "$2") '.[$t] = ($u | rtrimstr("\n"))' <<< "$SUBSCRIPTION_URLS_JSON")
|
||||
# Only the entries merged (_proxy_suite_record_outbound_source ran first): one left
|
||||
# out for a taken tag would otherwise put its link on that tag's outbound.
|
||||
if [ -s "$3" ]; then
|
||||
OUTBOUND_URLS_JSON=$(${jq} --slurpfile l "$3" '. + $l[0]' <<< "$OUTBOUND_URLS_JSON") || true
|
||||
OUTBOUND_URLS_JSON=$(${jq} --slurpfile l "$3" --arg s "sub:$1" \
|
||||
--slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \
|
||||
'. + ($l[0] | with_entries(select($sources[0][.key] == $s)))' <<< "$OUTBOUND_URLS_JSON") || true
|
||||
fi
|
||||
}
|
||||
|
||||
# $1 source label, $2 array length before the add, $3 after. Subscriptions
|
||||
# append an unknown number of outbounds, so they label them by range.
|
||||
# Here and below, whatever grows with the outbounds goes to jq through a file, not
|
||||
# --argjson: a big subscription outgrows the kernel's 128 KiB limit on one argument.
|
||||
_proxy_suite_record_outbound_source() {
|
||||
[ "$3" -gt "$2" ] || return 0
|
||||
OUTBOUND_SOURCES_JSON=$(${jq} \
|
||||
--argjson sources "$OUTBOUND_SOURCES_JSON" --arg s "$1" \
|
||||
--slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") --arg s "$1" \
|
||||
--argjson b "$2" --argjson a "$3" \
|
||||
'reduce .[$b:$a][].tag as $t ($sources; .[$t] = $s)' <<< "$OUTBOUNDS_JSON")
|
||||
'reduce .[$b:$a][].tag as $t ($sources[0]; .[$t] = $s)' <<< "$OUTBOUNDS_JSON")
|
||||
}
|
||||
|
||||
${
|
||||
@@ -256,6 +285,15 @@ let
|
||||
}
|
||||
''
|
||||
}
|
||||
# $1 kind, $2 the outbound parsed from a URL, $3 tag, $4 source label: a runtime one
|
||||
# through the backend's own check, as for runtime JSON.
|
||||
_proxy_suite_check_url_outbound() {
|
||||
[ "$4" = runtime ] || return 0
|
||||
_proxy_suite_check_json_outbound "$1" "$2" && return 0
|
||||
echo "proxy-suite: runtime outbound '$3' is not one the backend takes" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
# $1 tag, $2 URL, $3 source label, $4 backend preference (auto|sing-box|xray).
|
||||
# Returns non-zero when the URL cannot be parsed; the caller decides whether
|
||||
# that is fatal.
|
||||
@@ -266,6 +304,28 @@ let
|
||||
OUTBOUND_URLS_JSON=$(${jq} --arg t "$tag" --rawfile u <(printf '%s' "$url") '.[$t] = $u' <<< "$OUTBOUND_URLS_JSON")
|
||||
}
|
||||
|
||||
# $1 kind, $2 the outbound: whether its backend takes it, as one it refuses would fail
|
||||
# the whole start. Alone (its references dropped), as the service user, from stdin.
|
||||
_proxy_suite_check_json_outbound() {
|
||||
local kind="$1" ob="$2" as=()
|
||||
[ "$(${pkgs.coreutils}/bin/id -u)" = 0 ] && as=(${constants.runAsServiceUser pkgs [ ]})
|
||||
case "$kind" in
|
||||
${lib.optionalString (singBoxBin != null) ''
|
||||
sing-box)
|
||||
${jq} -c '{outbounds: [del(.detour, .domain_resolver) | select(.type != "selector" and .type != "urltest")]}' <<< "$ob" \
|
||||
| "''${as[@]}" ${singBoxBin} check -c /dev/stdin >/dev/null 2>&1
|
||||
;;
|
||||
''}
|
||||
${lib.optionalString (xrayBin != null) ''
|
||||
xray)
|
||||
${jq} -c '{outbounds: [del(.proxySettings) | del(.streamSettings.sockopt.dialerProxy)]}' <<< "$ob" \
|
||||
| "''${as[@]}" ${xrayBin} run -test -format json -c stdin: >/dev/null 2>&1
|
||||
;;
|
||||
''}
|
||||
*) return 0 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# $1 tag, $2 file holding one sing-box or XRay outbound, $3 source label.
|
||||
_proxy_suite_add_json_outbound() {
|
||||
local tag="$1" source="$3" ob kind unsafe
|
||||
@@ -282,6 +342,10 @@ let
|
||||
fi
|
||||
fi
|
||||
kind=$(${jq} -r 'if has("protocol") then "xray" elif has("type") then "sing-box" else "" end' <<< "$ob")
|
||||
if [ "$source" = runtime ] && ! _proxy_suite_check_json_outbound "$kind" "$ob"; then
|
||||
echo "proxy-suite: runtime outbound '$tag' is not one the backend takes (a field misspelt, or one it no longer has)" >&2
|
||||
return 1
|
||||
fi
|
||||
${jsonAddBlock}
|
||||
_proxy_suite_record_tag_source "$tag" "$source"
|
||||
}
|
||||
@@ -297,8 +361,16 @@ let
|
||||
[ -f "$f" ] && [ ! -L "$f" ] || continue
|
||||
tag="''${f##*/}"
|
||||
tag="''${tag%.*}"
|
||||
# A tab or newline in a name would split the line into entries of its own.
|
||||
if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then
|
||||
echo "proxy-suite: warning: ignoring a runtime outbound whose name is not a valid tag" >&2
|
||||
continue
|
||||
fi
|
||||
case "$tag" in
|
||||
proxy | direct | block${lib.optionalString torOutboundEnabled " | tor"})
|
||||
# proxy-suite-*: the test selector and the pin selectors the start script adds;
|
||||
# priority.json is the priority overrides, not an outbound.
|
||||
proxy | direct | block | priority | proxy-suite-*${lib.optionalString torOutboundEnabled " | tor"})
|
||||
[ "$f" = "${runtimeOutboundsDir}/priority.json" ] && continue
|
||||
echo "proxy-suite: warning: ignoring runtime outbound '$tag': reserved name" >&2
|
||||
continue
|
||||
;;
|
||||
@@ -316,7 +388,7 @@ let
|
||||
jsonFile = pkgs.writeText "proxy-suite-core" outboundJson;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag} (static ${backend} json)
|
||||
# outbound: ${oneLine tag} (static ${backend} json)
|
||||
OB_JSON=$(cat "${jsonFile}")
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")
|
||||
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
|
||||
@@ -326,8 +398,8 @@ let
|
||||
urlSource = if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-core" ob.url;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag}
|
||||
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static || exit 1
|
||||
# outbound: ${oneLine tag}
|
||||
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat ${lib.escapeShellArg urlSource})" static || exit 1
|
||||
'';
|
||||
|
||||
singBoxRawOutboundJson =
|
||||
@@ -347,7 +419,7 @@ let
|
||||
jsonFile = pkgs.writeText "proxy-suite-core" outboundJson;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag} (hybrid XRay json sidecar)
|
||||
# outbound: ${oneLine tag} (hybrid XRay json sidecar)
|
||||
OB_JSON=$(cat "${jsonFile}")
|
||||
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
|
||||
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
|
||||
@@ -358,7 +430,7 @@ let
|
||||
jsonFile = pkgs.writeText "proxy-suite-core" outboundJson;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag} (hybrid SingBox json)
|
||||
# outbound: ${oneLine tag} (hybrid SingBox json)
|
||||
OB_JSON=$(cat "${jsonFile}")
|
||||
_proxy_suite_add_sing_box_ob "$OB_JSON"
|
||||
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
|
||||
@@ -368,8 +440,8 @@ let
|
||||
urlSource = if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-core" ob.url;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag} (hybrid ${ob.backend})
|
||||
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static ${ob.backend} || exit 1
|
||||
# outbound: ${oneLine tag} (hybrid ${ob.backend})
|
||||
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat ${lib.escapeShellArg urlSource})" static ${ob.backend} || exit 1
|
||||
'';
|
||||
|
||||
mkSshProxyOutboundBlock =
|
||||
@@ -420,7 +492,7 @@ let
|
||||
-f ${lib.escapeShellArg sshProxyCfg.hostKeyFile} \
|
||||
| ${jq} -R -s '[splits("\n")] | map(select(length > 0 and (startswith("#") | not))) | map(sub("^\\S+\\s+"; ""))')
|
||||
if [ "$(${jq} 'length' <<< "$SSH_HOST_KEYS")" -eq 0 ]; then
|
||||
echo "proxy-suite: no host keys for ${knownHostsTarget} in ${sshProxyCfg.hostKeyFile}" >&2
|
||||
echo "proxy-suite: no host keys for "${lib.escapeShellArg knownHostsTarget}" in "${lib.escapeShellArg sshProxyCfg.hostKeyFile} >&2
|
||||
exit 1
|
||||
fi
|
||||
OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON")
|
||||
@@ -433,7 +505,9 @@ let
|
||||
# sing-box opens the key as ${constants.serviceUser}, which cannot read a key in a
|
||||
# home directory: it gets a copy only root and its group can read.
|
||||
SSH_IDENTITY="$RUNTIME_DIR/ssh-identity"
|
||||
install -m 0640 ${constants.ifPrivileged "-g ${constants.serviceUser} "}${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY"
|
||||
install -m ${
|
||||
if constants.privileged then "0640" else "0600"
|
||||
} ${constants.ifPrivileged "-g ${constants.serviceUser} "}${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY"
|
||||
OB_JSON=$(${jq} --arg key "$SSH_IDENTITY" '.private_key_path = $key' <<< "$OB_JSON")
|
||||
''}
|
||||
${hostKeyFileBlock}
|
||||
@@ -448,7 +522,7 @@ let
|
||||
|
||||
# Outbounds whose JSON is known at build time: every backend takes it as is.
|
||||
mkFixedOutboundBlock = comment: source: outbound: ''
|
||||
# outbound: ${outbound.tag} (${comment})
|
||||
# outbound: ${oneLine outbound.tag} (${comment})
|
||||
OB_JSON=${lib.escapeShellArg (builtins.toJSON outbound)}
|
||||
${
|
||||
if hybridEnabled then
|
||||
@@ -459,28 +533,52 @@ let
|
||||
_proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source}
|
||||
'';
|
||||
|
||||
# As mkFixedOutboundBlock, with the hop login added at start: it is drawn per boot, and
|
||||
# the password reaches jq from its file, never argv.
|
||||
mkHopOutboundBlock = comment: source: outbound: ''
|
||||
# outbound: ${oneLine outbound.tag} (${comment})
|
||||
${constants.ensureHopLogin pkgs}
|
||||
OB_JSON=$(${jq} -c --arg u ${constants.hopUser} --rawfile pw ${lib.escapeShellArg constants.hopLoginFile} ${
|
||||
lib.escapeShellArg (
|
||||
if pureXrayEnabled then
|
||||
''.settings += {user: $u, pass: ($pw | rtrimstr("\n"))}''
|
||||
else
|
||||
''. + {username: $u, password: ($pw | rtrimstr("\n"))}''
|
||||
)
|
||||
} <<< ${lib.escapeShellArg (builtins.toJSON outbound)})
|
||||
${
|
||||
if hybridEnabled then
|
||||
''_proxy_suite_add_sing_box_ob "$OB_JSON"''
|
||||
else
|
||||
''OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$OB_JSON") '. + $ob' <<< "$OUTBOUNDS_JSON")''
|
||||
}
|
||||
_proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source}
|
||||
'';
|
||||
|
||||
# WARP and "singBox" or "userspace" 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.
|
||||
# Every hop but Tor's takes the hop login (constants.ensureHopLogin); Tor has none to take.
|
||||
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;
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
type = "socks";
|
||||
inherit tag;
|
||||
server = "127.0.0.1";
|
||||
server_port = port;
|
||||
}
|
||||
);
|
||||
(if source == "tor" then mkFixedOutboundBlock else mkHopOutboundBlock) "SOCKS hop to ${unit}" source
|
||||
(
|
||||
if pureXrayEnabled then
|
||||
{
|
||||
protocol = "socks";
|
||||
inherit tag;
|
||||
settings = {
|
||||
address = "127.0.0.1";
|
||||
inherit port;
|
||||
};
|
||||
}
|
||||
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.
|
||||
@@ -532,11 +630,31 @@ let
|
||||
|
||||
mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock;
|
||||
|
||||
# Tags a runtime outbound may not take: the outbounds added after it, the groups (declared
|
||||
# and runtime), and the backend template's own. Those already in (declared, subscriptions,
|
||||
# an earlier runtime one under another extension) are checked as it comes.
|
||||
runtimeTakenTags = laterTags ++ lib.optional pureXrayEnabled "dns-out";
|
||||
runtimeOutboundsBlock = ''
|
||||
# outbounds added at runtime, and the hop each one chains through (<tag>.detour)
|
||||
RUNTIME_DETOURS_JSON='{}'
|
||||
RUNTIME_TAKEN_JSON=$(
|
||||
for f in "${runtimeOutboundsDir}"/*.group; do
|
||||
[ -e "$f" ] || continue
|
||||
f="''${f##*/}"
|
||||
printf '%s\n' "''${f%.group}"
|
||||
done | ${jq} -R . | ${jq} -cs --argjson fixed ${lib.escapeShellArg (builtins.toJSON runtimeTakenTags)} '. + $fixed'
|
||||
)
|
||||
while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do
|
||||
[ -n "$RUNTIME_OB_TAG" ] || continue
|
||||
# A duplicate tag fails the backend's start, every outbound with it: this one goes.
|
||||
if {
|
||||
printf '%s\n' "''${OUTBOUNDS_JSON:-[]}"
|
||||
${lib.optionalString hybridEnabled ''printf '%s\n' "''${XRAY_OUTBOUNDS_JSON:-[]}"''}
|
||||
} | ${jq} -e -s --arg t "$RUNTIME_OB_TAG" --argjson taken "$RUNTIME_TAKEN_JSON" \
|
||||
'(add | [.[].tag]) + $taken | index([$t]) != null' >/dev/null 2>&1; then
|
||||
echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG': the tag is taken" >&2
|
||||
continue
|
||||
fi
|
||||
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.
|
||||
@@ -581,24 +699,25 @@ let
|
||||
# unchained; whatever chained through it is checked again.
|
||||
detourBlock = ''
|
||||
# outbound chaining
|
||||
DETOURS_JSON=$(${jq} -c --argjson runtime "$RUNTIME_DETOURS_JSON" '.outbounds = $runtime + .outbounds' \
|
||||
DETOURS_JSON=$(${jq} -c --slurpfile runtime <(printf '%s' "$RUNTIME_DETOURS_JSON") '.outbounds = $runtime[0] + .outbounds' \
|
||||
<<< ${lib.escapeShellArg (builtins.toJSON detours)})
|
||||
while [ "$DETOURS_JSON" != '{"outbounds":{},"subscriptions":{}}' ]; do
|
||||
# The filter reads $sources as the object itself, so the program unwraps the slurped one.
|
||||
DETOUR_RESULT=$(${jq} -c --slurpfile xob <(printf '%s' "${
|
||||
if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"
|
||||
}") '{outbounds: ., xray: $xob[0]}' <<< "$OUTBOUNDS_JSON" \
|
||||
| ${jq} -c -f ${
|
||||
| ${jq} -c -f <(printf '%s' '$sources[0] as $sources | '; cat ${
|
||||
builtins.path {
|
||||
name = "proxy-suite-outbound-detours";
|
||||
path = ../../outbound-detours.jq;
|
||||
}
|
||||
} \
|
||||
}) \
|
||||
--argjson d "$DETOURS_JSON" \
|
||||
--argjson sources "$OUTBOUND_SOURCES_JSON" \
|
||||
--slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \
|
||||
--arg kind ${detourKind})
|
||||
DETOUR_DROP=$(${jq} -c --argjson sources "$OUTBOUND_SOURCES_JSON" \
|
||||
'[.errors[] | select($sources[.tag] == "runtime")] | unique_by(.tag)' <<< "$DETOUR_RESULT")
|
||||
if ${jq} -e --argjson sources "$OUTBOUND_SOURCES_JSON" 'any(.errors[]; $sources[.tag] != "runtime")' <<< "$DETOUR_RESULT" >/dev/null; then
|
||||
DETOUR_DROP=$(${jq} -c --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \
|
||||
'[.errors[] | select($sources[0][.tag] == "runtime")] | unique_by(.tag)' <<< "$DETOUR_RESULT")
|
||||
if ${jq} -e --slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") 'any(.errors[]; $sources[0][.tag] != "runtime")' <<< "$DETOUR_RESULT" >/dev/null; then
|
||||
${jq} -r '.errors[] | "proxy-suite: " + .message' <<< "$DETOUR_RESULT" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -638,7 +757,7 @@ let
|
||||
DISABLED_TAGS_JSON=$(${jq} -c --arg t "''${DISABLED_TAG%.disabled}" '. + [$t]' <<< "$DISABLED_TAGS_JSON")
|
||||
done
|
||||
fi
|
||||
DISABLED_TAGS_JSON=$(${jq} -c --argjson tags "$OUTBOUND_TAGS_JSON" 'map(select(. as $t | $tags | index([$t]))) | unique' <<< "$DISABLED_TAGS_JSON")
|
||||
DISABLED_TAGS_JSON=$(${jq} -c --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") 'map(select(. as $t | $tags[0] | index([$t]))) | unique' <<< "$DISABLED_TAGS_JSON")
|
||||
'';
|
||||
|
||||
# proxy.groups and those `proxy-ctl proxy groups add` left as <tag>.group next to the runtime
|
||||
@@ -671,7 +790,7 @@ let
|
||||
# As proxy-ctl names them; the spool is group-writable, and a group tagged "proxy"
|
||||
# would shadow the real selector.
|
||||
case "$GROUP_NAME" in
|
||||
proxy | direct | block${lib.optionalString torOutboundEnabled " | tor"} | [!A-Za-z0-9]* | *[!A-Za-z0-9._-]*)
|
||||
proxy | direct | block | proxy-suite-*${lib.optionalString torOutboundEnabled " | tor"} | [!A-Za-z0-9]* | *[!A-Za-z0-9._-]*)
|
||||
echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': reserved or invalid name" >&2
|
||||
continue
|
||||
;;
|
||||
@@ -713,12 +832,13 @@ let
|
||||
while IFS= read -r GROUP_NAME; do
|
||||
echo "proxy-suite: warning: ignoring group '$GROUP_NAME': an outbound has that tag" >&2
|
||||
GROUPS_CONFIG_JSON=$(${jq} -c --arg g "$GROUP_NAME" 'del(.[$g])' <<< "$GROUPS_CONFIG_JSON")
|
||||
done < <(${jq} -r --argjson tags "$OUTBOUND_TAGS_JSON" 'keys[] | select(. as $g | $tags | index([$g]))' <<< "$GROUPS_CONFIG_JSON")
|
||||
done < <(${jq} -r --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") 'keys[] | select(. as $g | $tags[0] | index([$g]))' <<< "$GROUPS_CONFIG_JSON")
|
||||
# A runtime group inside itself is left out, like any runtime outbound that cannot be
|
||||
# built; only a loop among declared groups fails the start.
|
||||
while :; do
|
||||
GROUPS_RESULT=$(${jq} -nc --argjson tags "$OUTBOUND_TAGS_JSON" --argjson sources "''${OUTBOUND_SOURCES_JSON:-{\}}" \
|
||||
'{tags: $tags, sources: $sources}' \
|
||||
GROUPS_RESULT=$(${jq} -nc --slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") \
|
||||
--slurpfile sources <(printf '%s' "''${OUTBOUND_SOURCES_JSON:-{\}}") \
|
||||
'{tags: $tags[0], sources: $sources[0]}' \
|
||||
| ${jq} -c -f ${groupsJq} \
|
||||
--argjson groups "$GROUPS_CONFIG_JSON" \
|
||||
--argjson priority "$PRIORITY_JSON" \
|
||||
@@ -741,7 +861,7 @@ let
|
||||
GROUP_TAGS_JSON=$(${jq} -c '.groups | keys_unsorted' <<< "$GROUPS_RESULT")
|
||||
GROUPS_INFO_JSON=$(${jq} -c '.groups' <<< "$GROUPS_RESULT")
|
||||
TOP_TAGS_JSON=$(${jq} -c '.top' <<< "$GROUPS_RESULT")
|
||||
OUTBOUNDS_JSON=$(${jq} -c --argjson g "$(${jq} -c '.outbounds' <<< "$GROUPS_RESULT")" '. + $g' <<< "$OUTBOUNDS_JSON")
|
||||
OUTBOUNDS_JSON=$(${jq} -c --slurpfile g <(${jq} -c '.outbounds' <<< "$GROUPS_RESULT") '. + $g[0]' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
|
||||
pinBlock = ''
|
||||
@@ -778,19 +898,21 @@ let
|
||||
# chains through, what selection leaves alone, and what was disabled.
|
||||
inventoryBlock = ''
|
||||
${jq} -n \
|
||||
--argjson tags "$OUTBOUND_TAGS_JSON" \
|
||||
--argjson sources "$OUTBOUND_SOURCES_JSON" \
|
||||
--slurpfile tags <(printf '%s' "$OUTBOUND_TAGS_JSON") \
|
||||
--slurpfile sources <(printf '%s' "$OUTBOUND_SOURCES_JSON") \
|
||||
--arg pinned "$PINNED_OUTBOUND" \
|
||||
--arg selection ${lib.escapeShellArg selectionMode} \
|
||||
--slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \
|
||||
--slurpfile xobs <(printf '%s' "${if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"}") \
|
||||
--argjson selectable "$SELECTABLE_TAGS_JSON" \
|
||||
--slurpfile selectable <(printf '%s' "$SELECTABLE_TAGS_JSON") \
|
||||
--argjson disabled "$DISABLED_TAGS_JSON" \
|
||||
--argjson groups "$GROUPS_INFO_JSON" \
|
||||
--argjson top "$TOP_TAGS_JSON" \
|
||||
--slurpfile groups <(printf '%s' "$GROUPS_INFO_JSON") \
|
||||
--slurpfile top <(printf '%s' "$TOP_TAGS_JSON") \
|
||||
--argjson priority "$PRIORITY_JSON" \
|
||||
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
|
||||
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection,
|
||||
'$tags[0] as $tags | $sources[0] as $sources | $selectable[0] as $selectable
|
||||
| $groups[0] as $groups | $top[0] as $top
|
||||
| {tags: $tags, sources: $sources, pinned: $pinned, selection: $selection,
|
||||
detours: ([($xobs[0] + $obs[0])[] | (.detour // .streamSettings.sockopt.dialerProxy?) as $h
|
||||
| select($h != null) | {key: .tag, value: $h}] | from_entries),
|
||||
excluded: ($top - $selectable), disabled: $disabled,
|
||||
@@ -864,17 +986,17 @@ let
|
||||
if [ -z "$PINNED_OUTBOUND" ] && [ "''${GROUPS_WATCHED:-true}" != true ]; then
|
||||
# No Clash API here for the watcher to drive: sing-box's own urltest instead.
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$SELECTABLE_TAGS_JSON" \
|
||||
--slurpfile tags <(printf '%s' "$SELECTABLE_TAGS_JSON") \
|
||||
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
|
||||
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
|
||||
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:"30s",tolerance:$tolerance}')
|
||||
'{type:"urltest",tag:"proxy",outbounds:$tags[0],url:$url,interval:"30s",tolerance:$tolerance}')
|
||||
else
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$TAGS" \
|
||||
--slurpfile tags <(printf '%s' "$TAGS") \
|
||||
--arg default "$DEFAULT_TAG" \
|
||||
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default,interrupt_exist_connections:true}')
|
||||
'{type:"selector",tag:"proxy",outbounds:$tags[0],default:$default,interrupt_exist_connections:true}')
|
||||
fi
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile w <(printf '%s' "$WRAPPER") '$w + .' <<< "$OUTBOUNDS_JSON")
|
||||
''
|
||||
else if selectionMode == "selector" then
|
||||
''
|
||||
@@ -884,10 +1006,10 @@ let
|
||||
DEFAULT_TAG=$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON")
|
||||
fi
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$TAGS" \
|
||||
--slurpfile tags <(printf '%s' "$TAGS") \
|
||||
--arg default "$DEFAULT_TAG" \
|
||||
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||
'{type:"selector",tag:"proxy",outbounds:$tags[0],default:$default}')
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile w <(printf '%s' "$WRAPPER") '$w + .' <<< "$OUTBOUNDS_JSON")
|
||||
''
|
||||
else
|
||||
''
|
||||
@@ -896,18 +1018,18 @@ let
|
||||
# A pin beats latency ranking: the same outbounds, behind a selector
|
||||
# the Clash API can also switch live.
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$TAGS" \
|
||||
--slurpfile tags <(printf '%s' "$TAGS") \
|
||||
--arg default "$PINNED_OUTBOUND" \
|
||||
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
|
||||
'{type:"selector",tag:"proxy",outbounds:$tags[0],default:$default}')
|
||||
else
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$SELECTABLE_TAGS_JSON" \
|
||||
--slurpfile tags <(printf '%s' "$SELECTABLE_TAGS_JSON") \
|
||||
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
|
||||
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
|
||||
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
|
||||
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
|
||||
'{type:"urltest",tag:"proxy",outbounds:$tags[0],url:$url,interval:$interval,tolerance:$tolerance}')
|
||||
fi
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||
OUTBOUNDS_JSON=$(${jq} --slurpfile w <(printf '%s' "$WRAPPER") '$w + .' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
# Real exits for autoProxy, taken after the wrapper may have renamed one to
|
||||
# "proxy".
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
SUB_CACHE_DIR="@cacheDir@"
|
||||
RUNTIME_SUBS_DIR="@runtimeSubscriptionsDir@"
|
||||
|
||||
# The caches hold every server's credentials and original link: root and, with the
|
||||
# "secrets" scope, the userControl groups only, as for the share file.
|
||||
mkdir -p "$SUB_CACHE_DIR"
|
||||
@cacheDirAccess@
|
||||
|
||||
_proxy_suite_valid_subscription_cache() {
|
||||
[ -s "$1" ] && @jq@ -e @validCacheFilter@ "$1" >/dev/null 2>&1
|
||||
}
|
||||
@@ -34,34 +39,72 @@ _proxy_suite_drop_invalid_subscription_cache() {
|
||||
fi
|
||||
}
|
||||
|
||||
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically,
|
||||
# and next to it <tag>.links: each entry's original URI, for proxy-ctl to share.
|
||||
# $1 "direct" to fetch as the service user, past the kill switch and outside the tunnel;
|
||||
# otherwise as an unprivileged user the tunnel and the kill switch take as they take root.
|
||||
# Root opens the output files either way (the links on fd 3).
|
||||
_proxy_suite_run_fetcher() {
|
||||
local how="$1" tag="$2" src="$3" cache_tmp="$4" links_tmp="$5" as=(@tunnelFetch@)
|
||||
shift 5
|
||||
[ "$how" = direct ] && as=(@directFetch@)
|
||||
printf '%s' "$(_proxy_suite_read_source "$src")" \
|
||||
| PYTHONPATH="@pythonPath@" "${as[@]}" @python3@ @fetchSubscriptionPy@ \
|
||||
@backendArg@ --tag-prefix "$tag" --links-fd 3 "$@" > "$cache_tmp" 3> "$links_tmp"
|
||||
}
|
||||
|
||||
# A temporary file of its own next to $1: the start scripts share the directory and fetch at
|
||||
# once. Readable as the caches always were; the directory's mode keeps others out.
|
||||
_proxy_suite_cache_tmp() {
|
||||
local tmp
|
||||
tmp=$(mktemp "$1.XXXXXX") || return 1
|
||||
chmod 0644 "$tmp"
|
||||
printf '%s' "$tmp"
|
||||
}
|
||||
|
||||
# $1 tag, $2 file holding the subscription URL, then the fetcher's flags. Writes the cache
|
||||
# atomically, and <tag>.links for proxy-ctl to share. Through the tunnel; directly past the
|
||||
# kill switch only with no cache, which has no proxy to fetch through.
|
||||
_proxy_suite_fetch_subscription() {
|
||||
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links"
|
||||
mkdir -p "$SUB_CACHE_DIR"
|
||||
if printf '%s' "$(_proxy_suite_read_source "$src")" \
|
||||
| PYTHONPATH="@pythonPath@" @python3@ @fetchSubscriptionPy@ \
|
||||
@backendArg@ --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then
|
||||
if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then
|
||||
mv "$links.tmp" "$links"
|
||||
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links" cache_tmp links_tmp
|
||||
# What a fetch killed midway (a stop's timeout) left behind.
|
||||
@findutils@/bin/find "$SUB_CACHE_DIR" -maxdepth 1 -type f \( -name "$tag.json.??????" -o -name "$tag.links.??????" \) \
|
||||
-mmin +10 -delete 2>/dev/null || true
|
||||
cache_tmp=$(_proxy_suite_cache_tmp "$cache") || return 1
|
||||
links_tmp=$(_proxy_suite_cache_tmp "$links") || { rm -f "$cache_tmp"; return 1; }
|
||||
if _proxy_suite_run_fetcher tunnel "$tag" "$src" "$cache_tmp" "$links_tmp" "${@:3}" ||
|
||||
{ @killSwitch@ && ! _proxy_suite_valid_subscription_cache "$cache" &&
|
||||
echo "proxy-suite: subscription '$tag' not fetched through the tunnel and not cached; fetching it directly, past the kill switch" >&2 &&
|
||||
_proxy_suite_run_fetcher direct "$tag" "$src" "$cache_tmp" "$links_tmp" "${@:3}"; }; then
|
||||
if _proxy_suite_commit_subscription_cache "$cache_tmp" "$cache" "$tag"; then
|
||||
mv "$links_tmp" "$links"
|
||||
return 0
|
||||
fi
|
||||
rm -f "$links.tmp"
|
||||
rm -f "$links_tmp"
|
||||
return 1
|
||||
fi
|
||||
rm -f "$cache.tmp" "$links.tmp"
|
||||
rm -f "$cache_tmp" "$links_tmp"
|
||||
echo "proxy-suite: failed to update subscription '$tag'" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
# Every runtime subscription, as "<tag>\t<url file>" lines.
|
||||
# Every runtime subscription, as "<tag>\t<url file>" lines. Checked again here, as the spool
|
||||
# is group-writable: a declared subscription's name would take over its cache.
|
||||
_proxy_suite_runtime_subscriptions() {
|
||||
local f tag
|
||||
local f tag declared
|
||||
[ -d "$RUNTIME_SUBS_DIR" ] || return 0
|
||||
for f in "$RUNTIME_SUBS_DIR"/*.url; do
|
||||
[ -f "$f" ] && [ ! -L "$f" ] || continue
|
||||
tag="${f##*/}"
|
||||
tag="${tag%.url}"
|
||||
if [[ ! $tag =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ || $tag == proxy-suite-* ]]; then
|
||||
echo "proxy-suite: warning: ignoring a runtime subscription whose name is not a valid tag" >&2
|
||||
continue
|
||||
fi
|
||||
for declared in @declaredTags@; do
|
||||
if [ "$tag" = "$declared" ]; then
|
||||
echo "proxy-suite: warning: ignoring runtime subscription '$tag': a declared one has that name" >&2
|
||||
continue 2
|
||||
fi
|
||||
done
|
||||
printf '%s\t%s\n' "$tag" "$f"
|
||||
done
|
||||
}
|
||||
@@ -21,9 +21,17 @@ let
|
||||
fetchSubscriptionPy
|
||||
routingMarkJq
|
||||
;
|
||||
inherit (constants) stateDir runtimeSubscriptionsDir;
|
||||
inherit (constants) stateDir runtimeSubscriptionsDir runtimeOutboundsDir;
|
||||
# Outbounds and groups the start script adds after the subscriptions, which a subscription
|
||||
# entry must not take the tag of.
|
||||
laterTagsJson = builtins.toJSON (ctx.effectiveOutboundTags ++ ctx.groupTags);
|
||||
subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend;
|
||||
subscriptionBackendArg = "--backend ${subscriptionBackend}";
|
||||
# Each entry also through its backend's own config check: one it refuses would fail the
|
||||
# whole start, every other outbound with it.
|
||||
subscriptionBackendArg =
|
||||
"--backend ${subscriptionBackend}"
|
||||
+ lib.optionalString (subscriptionBackend != "xray") " --check-sing-box ${ctx.singBox}"
|
||||
+ lib.optionalString (subscriptionBackend != "sing-box") " --check-xray ${ctx.xray}";
|
||||
subscriptionCacheDir = "${stateDir}/subscriptions/${backend}";
|
||||
|
||||
mkSubscriptionUrlSource =
|
||||
@@ -35,16 +43,53 @@ let
|
||||
readSourceFunction = constants.readSourceFunction pkgs;
|
||||
cacheDir = subscriptionCacheDir;
|
||||
inherit runtimeSubscriptionsDir jq;
|
||||
declaredTags = lib.escapeShellArgs (map (sub: sub.tag) proxyCfg.subscriptions);
|
||||
validCacheFilter = lib.escapeShellArg (
|
||||
if hybridEnabled then
|
||||
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
|
||||
else
|
||||
''type == "array"''
|
||||
);
|
||||
diffutils = pkgs.diffutils;
|
||||
inherit (pkgs) diffutils findutils;
|
||||
# The directory alone, not what is in it (constants.grantDirAcl): the caches are 0644, and
|
||||
# a recursive pass would trip over another start script's temporary file.
|
||||
cacheDirAccess =
|
||||
let
|
||||
secrets = ctx.userControlAllows "secrets";
|
||||
extraGroups = ctx.userControlExtraGroupsFor "secrets";
|
||||
in
|
||||
lib.optionalString secrets ''
|
||||
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg ctx.userControlCfg.group} "$SUB_CACHE_DIR"
|
||||
''
|
||||
+ ''
|
||||
chmod ${if secrets then "0750" else "0700"} "$SUB_CACHE_DIR"
|
||||
''
|
||||
+ constants.ifPrivileged (
|
||||
if extraGroups == [ ] then
|
||||
''${pkgs.acl}/bin/setfacl -b -- "$SUB_CACHE_DIR"''
|
||||
else
|
||||
''${pkgs.acl}/bin/setfacl --set ${
|
||||
lib.concatStringsSep "," (
|
||||
[
|
||||
"u::rwx"
|
||||
"g::${if secrets then "r-x" else "---"}"
|
||||
"o::---"
|
||||
]
|
||||
++ map (g: "g:${g}:r-x") extraGroups
|
||||
)
|
||||
} -- "$SUB_CACHE_DIR"''
|
||||
);
|
||||
pythonPath = parserScriptsPythonPath;
|
||||
inherit python3 fetchSubscriptionPy;
|
||||
backendArg = subscriptionBackendArg;
|
||||
killSwitch = lib.boolToString ctx.killSwitchDirectFallbacks;
|
||||
# Its own user, not exempt from the tunnel or the kill switch: the HTTP client and the
|
||||
# parser of what any subscription server sends do not run as root.
|
||||
tunnelFetch = constants.ifPrivileged "${pkgs.util-linux}/bin/setpriv --reuid=${ctx.subscriptionFetchUser} --regid=${ctx.subscriptionFetchUser} --clear-groups --inh-caps=-all --ambient-caps=-all --bounding-set=-all --no-new-privs --";
|
||||
# Past the kill switch as the service user, resolving names itself (constants.ownLookups).
|
||||
directFetch = lib.optionalString ctx.killSwitchDirectFallbacks "${pkgs.util-linux}/bin/unshare --mount ${constants.ownLookups pkgs} ${
|
||||
constants.runAsServiceUser pkgs [ ]
|
||||
}";
|
||||
};
|
||||
|
||||
# Merging a cache into OUTBOUNDS_JSON needs the routing mark, which differs per
|
||||
@@ -62,25 +107,54 @@ let
|
||||
mergeBlock =
|
||||
if hybridEnabled then
|
||||
''
|
||||
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$cache")
|
||||
SUB_SING_BOX_JSON=$(_proxy_suite_free_tags "$tag" < <(${jq} -c '.singBox' "$cache"))
|
||||
${markBlock}OUTBOUNDS_JSON=$(${jq} --slurpfile sub <(printf '%s' "$SUB_SING_BOX_JSON") '. + $sub[0]' <<< "$OUTBOUNDS_JSON")
|
||||
_proxy_suite_add_xray_sidecar_obs "$(${jq} -c '.xray' "$cache")"
|
||||
_proxy_suite_add_xray_sidecar_obs "$(_proxy_suite_free_tags "$tag" < <(${jq} -c '.xray' "$cache"))"
|
||||
''
|
||||
else
|
||||
''
|
||||
SUB_JSON=$(cat "$cache")
|
||||
SUB_JSON=$(_proxy_suite_free_tags "$tag" < "$cache")
|
||||
${markBlock}OUTBOUNDS_JSON=$(${jq} --slurpfile sub <(printf '%s' "$SUB_JSON") '. + $sub[0]' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
in
|
||||
''
|
||||
# $1 tag, $2 file holding the subscription URL. Fetches on a cold cache and
|
||||
# merges whatever is cached; a subscription that cannot be fetched is a
|
||||
# stdin: a subscription's outbounds; prints those whose tag is free. A taken one (by any
|
||||
# other outbound, a group or the suite's own) would fail the backend's start.
|
||||
_proxy_suite_free_tags() {
|
||||
local entries taken f name
|
||||
entries=$(cat)
|
||||
taken=$(
|
||||
{
|
||||
${jq} -r 'map(.tag) | .[]' <<< "$OUTBOUNDS_JSON"
|
||||
if [ -d ${lib.escapeShellArg runtimeOutboundsDir} ]; then
|
||||
for f in ${lib.escapeShellArg runtimeOutboundsDir}/*.url ${lib.escapeShellArg runtimeOutboundsDir}/*.json \
|
||||
${lib.escapeShellArg runtimeOutboundsDir}/*.awg ${lib.escapeShellArg runtimeOutboundsDir}/*.group; do
|
||||
[ -e "$f" ] || continue
|
||||
name="''${f##*/}"
|
||||
printf '%s\n' "''${name%.*}"
|
||||
done
|
||||
fi
|
||||
} | ${jq} -R . | ${jq} -cs --argjson fixed ${lib.escapeShellArg laterTagsJson} '. + $fixed + ["proxy", "direct", "block"] | unique'
|
||||
)
|
||||
${jq} -r --arg sub "$1" --slurpfile taken <(printf '%s' "$taken") '
|
||||
$taken[0] as $taken
|
||||
| .[] | .tag | select(. as $t | ($taken | index([$t])) != null or startswith("proxy-suite-"))
|
||||
| "proxy-suite: warning: subscription \($sub) entry \(.) left out: the tag is taken"
|
||||
' <<< "$entries" >&2
|
||||
${jq} -c --slurpfile taken <(printf '%s' "$taken") '
|
||||
$taken[0] as $taken
|
||||
| map(select(.tag as $t | ($taken | index([$t])) == null and ($t | startswith("proxy-suite-") | not)))
|
||||
' <<< "$entries"
|
||||
}
|
||||
|
||||
# $1 tag, $2 file holding the subscription URL, then the fetcher's flags. Fetches on a
|
||||
# cold cache and merges whatever is cached; a subscription that cannot be fetched is a
|
||||
# warning, never a failed start.
|
||||
_proxy_suite_load_subscription() {
|
||||
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" before after
|
||||
_proxy_suite_drop_invalid_subscription_cache "$cache" "$tag"
|
||||
if [ ! -f "$cache" ]; then
|
||||
_proxy_suite_fetch_subscription "$tag" "$src" \
|
||||
_proxy_suite_fetch_subscription "$tag" "$src" "''${@:3}" \
|
||||
|| echo "proxy-suite: warning: could not fetch subscription '$tag'" >&2
|
||||
fi
|
||||
[ -f "$cache" ] || return 0
|
||||
@@ -92,21 +166,31 @@ let
|
||||
}
|
||||
'';
|
||||
|
||||
# A subscription's fetcher flags. Runtime ones take proxy.runtimeSubscriptions', https only
|
||||
# unless allowHttp: over http anyone on the way could add entries.
|
||||
mkSubscriptionFetchArgs =
|
||||
sub:
|
||||
lib.optionalString sub.allowPrivateServers " --allow-private-servers"
|
||||
+ lib.optionalString sub.allowInsecure " --allow-insecure";
|
||||
runtimeCfg = proxyCfg.runtimeSubscriptions;
|
||||
runtimeFetchArgs =
|
||||
mkSubscriptionFetchArgs runtimeCfg + lib.optionalString (!runtimeCfg.allowHttp) " --https-only";
|
||||
|
||||
mkSubscriptionBlock = sub: _routingMark: ''
|
||||
# subscription: ${sub.tag}
|
||||
_proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}
|
||||
_proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}${mkSubscriptionFetchArgs sub}
|
||||
'';
|
||||
|
||||
runtimeSubscriptionsBlock = ''
|
||||
# subscriptions added at runtime
|
||||
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
|
||||
[ -n "$RUNTIME_SUB_TAG" ] || continue
|
||||
_proxy_suite_load_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"
|
||||
_proxy_suite_load_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"${runtimeFetchArgs}
|
||||
done < <(_proxy_suite_runtime_subscriptions)
|
||||
'';
|
||||
|
||||
mkSubscriptionFetchBlock = sub: ''
|
||||
if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}; then
|
||||
if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}${mkSubscriptionFetchArgs sub}; then
|
||||
echo "Updated subscription: ${sub.tag}"
|
||||
else
|
||||
FAILED=1
|
||||
@@ -116,7 +200,7 @@ let
|
||||
runtimeSubscriptionsFetchBlock = ''
|
||||
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
|
||||
[ -n "$RUNTIME_SUB_TAG" ] || continue
|
||||
if _proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"; then
|
||||
if _proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"${runtimeFetchArgs}; then
|
||||
echo "Updated subscription: $RUNTIME_SUB_TAG"
|
||||
else
|
||||
FAILED=1
|
||||
|
||||
@@ -148,6 +148,11 @@ let
|
||||
mkSubscriptionLoadHelperBlock
|
||||
runtimeSubscriptionsBlock
|
||||
;
|
||||
# What the start script adds after the runtime outbounds: one of theirs named like these
|
||||
# would fail the backend's start, every outbound with it.
|
||||
laterTags = sctx.effectiveOutboundTags ++ sctx.groupTags;
|
||||
singBoxBin = if pureXrayEnabled then null else sctx.singBox;
|
||||
xrayBin = if xrayEnabled then sctx.xray else null;
|
||||
};
|
||||
inherit (outboundScripts) mkOutboundScript;
|
||||
|
||||
@@ -161,6 +166,13 @@ let
|
||||
proxyInboundsGuardPrivate
|
||||
proxyInboundsGuardStrategy
|
||||
;
|
||||
proxyInboundsBlockPrivate = proxyInboundsCfg.routing.blockPrivate;
|
||||
inherit (ctx) proxyInboundsLoopback proxyInboundsHostClosedPorts;
|
||||
listenerExposed =
|
||||
let
|
||||
address = proxyCfg.listener.address;
|
||||
in
|
||||
!(lib.hasPrefix "127." address || address == "::1" || address == "localhost");
|
||||
userDnsRules = proxyCfg.dns.singBox.rules;
|
||||
awgRuntimeDnsServer =
|
||||
if ctx.awgRuntimeIfaceOutbounds then
|
||||
|
||||
@@ -38,6 +38,7 @@ let
|
||||
;
|
||||
inherit (constants)
|
||||
autoProxyStateDir
|
||||
autoProxySpoolDir
|
||||
outboundTestPort
|
||||
xrayDnsBridgePorts
|
||||
xraySidecarPorts
|
||||
@@ -47,22 +48,20 @@ let
|
||||
inherit pkgs;
|
||||
inherit (constants) serviceUser ifPrivileged;
|
||||
};
|
||||
autoProxyMigrate = import ../autoproxy-migrate.nix { inherit pkgs; };
|
||||
# Who reads the probe listeners' login (`proxy outbounds test`, `proxy auto probe`).
|
||||
# Local proxy auth with userControl off keeps its group as before.
|
||||
probeLoginMainGroup =
|
||||
(!userControlCfg.enable && localProxyAuthEnabled)
|
||||
|| userControlAllows "outbounds"
|
||||
|| userControlAllows "autoProxy";
|
||||
probeLoginExtraGroups = lib.unique (
|
||||
ctx.userControlExtraGroupsFor "outbounds" ++ ctx.userControlExtraGroupsFor "autoProxy"
|
||||
);
|
||||
runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
|
||||
userControlGroup = lib.escapeShellArg userControlCfg.group;
|
||||
chgrp = "${pkgs.coreutils}/bin/chgrp";
|
||||
|
||||
routeModeBlacklistTail =
|
||||
if pureXrayEnabled then
|
||||
''
|
||||
+ .proxyGeo
|
||||
+ .block
|
||||
''
|
||||
else
|
||||
''
|
||||
+ .block
|
||||
+ .proxyGeo
|
||||
'';
|
||||
|
||||
# Every route mode is the same four assignments over one jq program on the rule buckets.
|
||||
routeModeArms = [
|
||||
{
|
||||
@@ -73,9 +72,10 @@ let
|
||||
.common
|
||||
+ (.custom | map(.entries) | add // [])
|
||||
+ .proxyPrimary
|
||||
+ .block
|
||||
+ .direct
|
||||
+ .safetyDirect
|
||||
${routeModeBlacklistTail}
|
||||
+ .proxyGeo
|
||||
'';
|
||||
}
|
||||
{
|
||||
@@ -86,9 +86,10 @@ let
|
||||
.common
|
||||
+ (.custom | map(.entries) | add // [])
|
||||
+ .proxyPrimary
|
||||
+ .block
|
||||
+ .direct
|
||||
+ .safetyDirect
|
||||
${routeModeBlacklistTail}
|
||||
+ .proxyGeo
|
||||
'';
|
||||
}
|
||||
{
|
||||
@@ -101,8 +102,9 @@ let
|
||||
.common
|
||||
+ (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // [])
|
||||
+ .proxyPrimary
|
||||
+ .block
|
||||
+ .safetyDirect
|
||||
${routeModeBlacklistTail}
|
||||
+ .proxyGeo
|
||||
'';
|
||||
}
|
||||
{
|
||||
@@ -113,8 +115,8 @@ let
|
||||
rules = ''
|
||||
.common
|
||||
+ (.custom | map(select(.category == "block") | .entries) | add // [])
|
||||
+ .safetyDirect
|
||||
+ .block
|
||||
+ .safetyDirect
|
||||
'';
|
||||
}
|
||||
];
|
||||
@@ -153,6 +155,16 @@ let
|
||||
'';
|
||||
|
||||
writeProxychainsConfigBlock = ''
|
||||
# proxychains reads its config by words: a password with whitespace in it would come out
|
||||
# as another field, or another line. None then, and proxy-ctl says why.
|
||||
case "''${LOCAL_PROXY_PASSWORD:-}" in
|
||||
*[[:space:]]*)
|
||||
echo "proxy-suite: listener.auth's password has whitespace, which proxychains cannot take; no proxychains config" >&2
|
||||
rm -f "${runtimeProxychainsConfig}"
|
||||
;;
|
||||
*)
|
||||
# Private from the start: the chmod below would leave a moment where anyone reads it.
|
||||
(umask 077 && : > "${runtimeProxychainsConfig}")
|
||||
{
|
||||
printf '%s\n' 'strict_chain'
|
||||
${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"}
|
||||
@@ -167,12 +179,15 @@ let
|
||||
"$LOCAL_PROXY_PASSWORD"
|
||||
} > "${runtimeProxychainsConfig}"
|
||||
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"''}
|
||||
chmod 640 "${runtimeProxychainsConfig}"
|
||||
# Without root the group is the user's own primary one, which may be shared.
|
||||
chmod ${if constants.privileged then "640" else "600"} "${runtimeProxychainsConfig}"
|
||||
# It holds the proxy's password: userControl.groups that run apps through proxychains.
|
||||
${constants.grantFileAcl pkgs ''"${runtimeProxychainsConfig}"''
|
||||
(ctx.userControlExtraGroupsFor "perApp")
|
||||
"r"
|
||||
}
|
||||
;;
|
||||
esac
|
||||
'';
|
||||
|
||||
mkStartScript =
|
||||
@@ -209,7 +224,7 @@ let
|
||||
${hybridRuntimeHelpersBlock routingMark xraySidecarPort xrayDnsBridgePort}
|
||||
${subscriptionCacheHelpersBlock}
|
||||
${lib.optionalString enableLocalProxyAuth ''
|
||||
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
|
||||
LOCAL_PROXY_PASSWORD="$(cat ${lib.escapeShellArg localProxyAuthPasswordSource})"
|
||||
# The umask stays in the subshell: left set, it also narrowed everything
|
||||
# written below, and autoProxy's state.json is group-readable by design.
|
||||
(
|
||||
@@ -238,9 +253,9 @@ let
|
||||
AUTOPROXY_RULES_JSON='[]'
|
||||
${lib.optionalString enableAutoProxy ''
|
||||
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
|
||||
# 0751: sing-box, running as ${constants.serviceUser}, reaches the rules/ inside;
|
||||
# 0771 with userControl's autoProxy scope, whose group queues learn requests there.
|
||||
install -d -m ${if ctx.userControlAnyAllows "autoProxy" then "0771" else "0751"} "$AUTOPROXY_DIR"
|
||||
# Root's alone, 0751: sing-box, running as ${constants.serviceUser}, reaches the
|
||||
# rules/ inside. An install from before the spool is made so first.
|
||||
${autoProxyMigrate} "$AUTOPROXY_DIR" ${lib.escapeShellArg autoProxySpoolDir}
|
||||
[ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json"
|
||||
|
||||
# direct is always exit 0; state is keyed by tag, so shifting indices are
|
||||
@@ -249,9 +264,9 @@ let
|
||||
PROBE_EXITS_JSON=$(${jq} -c \
|
||||
--argjson max ${toString proxyCfg.autoProxy.maxExits} \
|
||||
--argjson base ${toString proxyCfg.autoProxy.probeBasePort} \
|
||||
--argjson disabled "''${DISABLED_TAGS_JSON:-[]}" \
|
||||
--slurpfile disabled <(printf '%s' "''${DISABLED_TAGS_JSON:-[]}") \
|
||||
--arg dir "$AUTOPROXY_DIR" '
|
||||
(["direct"] + map(select(. != "direct" and (. as $t | $disabled | index([$t]) | not))))[0:$max]
|
||||
(["direct"] + map(select(. != "direct" and (. as $t | $disabled[0] | index([$t]) | not))))[0:$max]
|
||||
| to_entries
|
||||
| map({i: .key, tag: .value, port: ($base + .key),
|
||||
rule_set: ("autoproxy-" + (.key | tostring)),
|
||||
@@ -264,8 +279,19 @@ let
|
||||
|
||||
PROBE_INBOUNDS_JSON=$(${jq} -c 'map({type: "mixed", tag: ("probe-in-" + (.i | tostring)),
|
||||
listen: "127.0.0.1", listen_port: .port})' <<< "$PROBE_EXITS_JSON")
|
||||
PROBE_PIN_RULES_JSON=$(${jq} -c 'map({inbound: ["probe-in-" + (.i | tostring)],
|
||||
outbound: .tag})' <<< "$PROBE_EXITS_JSON")
|
||||
# The hosts probed are ones the inbounds' clients dialed: the direct probe gets their
|
||||
# fence (inbounds.routing.blockPrivate), resolving as a direct dial would.
|
||||
PROBE_PIN_RULES_JSON=$(${jq} -c --argjson fence ${
|
||||
lib.escapeShellArg (
|
||||
builtins.toJSON (
|
||||
if ctx.proxyInboundsCfg.routing.blockPrivate then
|
||||
{ ip_is_private = true; }
|
||||
else
|
||||
{ ip_cidr = ctx.proxyInboundsLoopback; }
|
||||
)
|
||||
)
|
||||
} '[{inbound: ["probe-in-0"], action: "resolve", server: "local"}, ({inbound: ["probe-in-0"], action: "reject"} + $fence)]
|
||||
+ map({inbound: ["probe-in-" + (.i | tostring)], outbound: .tag})' <<< "$PROBE_EXITS_JSON")
|
||||
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c 'map({type: "local", format: "source",
|
||||
tag: .rule_set, path: .path})' <<< "$PROBE_EXITS_JSON")
|
||||
# all-bypass means everything direct; learned exits must not override it.
|
||||
@@ -280,7 +306,7 @@ let
|
||||
# hybrid XRay outbound is a sing-box socks hop whose real server is the sidecar's.
|
||||
# A loopback hop (the WARP tunnel, XRay's SSH listener) has no server worth timing.
|
||||
ENDPOINTS_TMP="$RUNTIME_DIR/outbound-endpoints.json.tmp"
|
||||
${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") '
|
||||
(umask 077 && ${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") '
|
||||
$sidecar[0] as $sidecar
|
||||
| def endpoint:
|
||||
if .server then {server, port: .server_port}
|
||||
@@ -301,7 +327,7 @@ let
|
||||
| ($real[.tag] // .) | select(endpoint != null and (endpoint.server | test("^(127\\.|::1$|localhost$)") | not))
|
||||
| {key: $tag, value: (endpoint + {network: (if udp then "udp" else "tcp" end)})}]
|
||||
| from_entries
|
||||
' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP"
|
||||
' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP")
|
||||
# Where each proxy server is: not credentials, but not for every local user either.
|
||||
${
|
||||
if userControlCfg.enable || localProxyAuthEnabled then
|
||||
@@ -336,16 +362,18 @@ let
|
||||
${lib.optionalString (!pureXrayEnabled) ''
|
||||
# Delay and download: a loopback listener pinned to a selector over every real
|
||||
# exit, switched one outbound at a time through the Clash API.
|
||||
OUTBOUNDS_JSON=$(${jq} -c --argjson tags "$EXIT_TAGS_JSON" \
|
||||
'. + [{type: "selector", tag: "proxy-suite-test", outbounds: $tags}]' <<< "$OUTBOUNDS_JSON")
|
||||
# Slurped, not --argjson: one argument holds at most 128 KiB, less than the tags
|
||||
# of a large subscription.
|
||||
OUTBOUNDS_JSON=$(${jq} -c --slurpfile tags <(printf '%s' "$EXIT_TAGS_JSON") \
|
||||
'. + [{type: "selector", tag: "proxy-suite-test", outbounds: $tags[0]}]' <<< "$OUTBOUNDS_JSON")
|
||||
PROBE_INBOUNDS_JSON=$(${jq} -c '. + [{type: "mixed", tag: "proxy-suite-test-in",
|
||||
listen: "127.0.0.1", listen_port: ${toString outboundTestPort}}]' <<< "$PROBE_INBOUNDS_JSON")
|
||||
PROBE_PIN_RULES_JSON=$(${jq} -c \
|
||||
'. + [{inbound: ["proxy-suite-test-in"], outbound: "proxy-suite-test"}]' <<< "$PROBE_PIN_RULES_JSON")
|
||||
${jq} -n --argjson tags "$EXIT_TAGS_JSON" \
|
||||
${jq} -n --slurpfile tags <(printf '%s' "$EXIT_TAGS_JSON") \
|
||||
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} '
|
||||
{port: ${toString outboundTestPort}, selector: "proxy-suite-test", url: $url,
|
||||
outbounds: ($tags | map({key: ., value: .}) | from_entries)}
|
||||
outbounds: ($tags[0] | map({key: ., value: .}) | from_entries)}
|
||||
' > "$RUNTIME_DIR/outbound-test.json"
|
||||
# Tags and a loopback port only.
|
||||
chmod 644 "$RUNTIME_DIR/outbound-test.json"
|
||||
@@ -402,14 +430,25 @@ let
|
||||
esac
|
||||
''}
|
||||
|
||||
# Every address this host has now, for the inbounds' guard (backend-filter-private-guard):
|
||||
# dialed from here, a client would reach any port of them past the firewall.
|
||||
HOST_ADDRESSES_JSON='[]'
|
||||
${lib.optionalString (ctx.proxyInboundsEnabled && ctx.proxyInboundsNeedLocalProxy) ''
|
||||
if ! HOST_ADDRESSES_JSON=$(${pkgs.iproute2}/bin/ip -j addr show | ${jq} -c \
|
||||
'[.[].addr_info[]?.local | strings | if test(":") then . + "/128" else . + "/32" end] | unique'); then
|
||||
echo "proxy-suite: cannot list this host's addresses; the inbounds' clients reach any port of them" >&2
|
||||
HOST_ADDRESSES_JSON='[]'
|
||||
fi
|
||||
''}
|
||||
|
||||
# umask: the file holds credentials until the chmod below; the process
|
||||
# substitutions keep them out of the argv every local user can read.
|
||||
(umask 077 && ${jq} \
|
||||
--slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \
|
||||
--argjson probe_inbounds "$PROBE_INBOUNDS_JSON" \
|
||||
--argjson probe_pin_rules "$PROBE_PIN_RULES_JSON" \
|
||||
--argjson autoproxy_rule_sets "$AUTOPROXY_RULE_SETS_JSON" \
|
||||
--argjson autoproxy_rules "$AUTOPROXY_RULES_JSON" \
|
||||
--slurpfile probe_inbounds <(printf '%s' "$PROBE_INBOUNDS_JSON") \
|
||||
--slurpfile probe_pin_rules <(printf '%s' "$PROBE_PIN_RULES_JSON") \
|
||||
--slurpfile autoproxy_rule_sets <(printf '%s' "$AUTOPROXY_RULE_SETS_JSON") \
|
||||
--slurpfile autoproxy_rules <(printf '%s' "$AUTOPROXY_RULES_JSON") \
|
||||
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
|
||||
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
|
||||
${
|
||||
@@ -419,24 +458,54 @@ let
|
||||
"--arg password ''"
|
||||
} \
|
||||
--argjson route_enabled "$ROUTE_MODE_ACTIVE" \
|
||||
--argjson route_rules "$ROUTE_RULES_JSON" \
|
||||
--slurpfile route_rules <(printf '%s' "$ROUTE_RULES_JSON") \
|
||||
--arg route_final "$ROUTE_FINAL" \
|
||||
--arg dns_final "$DNS_FINAL" \
|
||||
--argjson clear_dns_rules "$CLEAR_DNS_RULES" \
|
||||
--arg xray_loglevel "$XRAY_LOGLEVEL" \
|
||||
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
|
||||
--argjson xray_selectable "$SELECTABLE_TAGS_JSON" \
|
||||
--slurpfile xray_selectable <(printf '%s' "$SELECTABLE_TAGS_JSON") \
|
||||
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \
|
||||
--argjson host_addresses "$HOST_ADDRESSES_JSON" \
|
||||
-f "$BACKEND_JQ_FILTER" \
|
||||
"${configFile}" > "$RUNTIME_DIR/config.json")
|
||||
${lib.optionalString excludeServiceUserFromTun ''
|
||||
# proxy-suite's own daemons (the inbound XRay, replies to its clients included)
|
||||
# stay out of the TUN; the uid is only known on this host.
|
||||
SERVICE_UID=$(${pkgs.coreutils}/bin/id -u ${constants.serviceUser})
|
||||
(umask 077 && ${jq} --argjson uid "$SERVICE_UID" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = [$uid]' \
|
||||
SERVICE_UIDS=$(for service_user in ${lib.escapeShellArgs constants.ownTrafficUsers}; do
|
||||
${pkgs.coreutils}/bin/id -u "$service_user"
|
||||
done | ${jq} -cs .)
|
||||
(umask 077 && ${jq} --argjson uids "$SERVICE_UIDS" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = $uids' \
|
||||
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next")
|
||||
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
|
||||
''}
|
||||
${lib.optionalString (!pureXrayEnabled) ''
|
||||
# The probe and test listeners reach any exit past the routing rules and the kill
|
||||
# switch: a login per start, into jq through its environment (argv is public).
|
||||
if ${jq} -e '[.inbounds[]? | (.tag // "") | select(startswith("probe-in-") or . == "proxy-suite-test-in")] | length > 0' \
|
||||
"$RUNTIME_DIR/config.json" >/dev/null; then
|
||||
PROBE_PASSWORD=$(${pkgs.coreutils}/bin/od -An -tx1 -N16 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n')
|
||||
(umask 077 && PROBE_PASSWORD="$PROBE_PASSWORD" ${jq} '(.inbounds[]? | select((.tag // "") | startswith("probe-in-") or . == "proxy-suite-test-in"))
|
||||
+= {users: [{username: "probe", password: $ENV.PROBE_PASSWORD}]}' \
|
||||
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next")
|
||||
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
|
||||
(umask 077 && printf 'probe:%s\n' "$PROBE_PASSWORD" > "$RUNTIME_DIR/probe-login.tmp")
|
||||
unset PROBE_PASSWORD
|
||||
${
|
||||
# Only to the groups that test outbounds or probe for autoProxy: to any other the
|
||||
# login is a way out direct, past the routing rules and the kill switch.
|
||||
if probeLoginMainGroup then
|
||||
''
|
||||
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$RUNTIME_DIR/probe-login.tmp"''}
|
||||
chmod ${if constants.privileged then "640" else "600"} "$RUNTIME_DIR/probe-login.tmp"
|
||||
''
|
||||
else
|
||||
''chmod 600 "$RUNTIME_DIR/probe-login.tmp"''
|
||||
}
|
||||
${constants.grantFileAcl pkgs ''"$RUNTIME_DIR/probe-login.tmp"'' probeLoginExtraGroups "r"}
|
||||
mv "$RUNTIME_DIR/probe-login.tmp" "$RUNTIME_DIR/probe-login"
|
||||
fi
|
||||
''}
|
||||
# The Clash API lists every connection and switches outbounds. Loopback alone lets
|
||||
# every local user at it, and every web page too (sing-box allows any origin): a
|
||||
# secret per start.
|
||||
@@ -472,7 +541,9 @@ let
|
||||
else
|
||||
''
|
||||
${constants.ifPrivileged ''${chgrp} ${constants.serviceUser} "$backend_config"''}
|
||||
chmod 640 "$backend_config"
|
||||
# Without root the group is the user's own primary one, which may be shared
|
||||
# (users): the owner alone then.
|
||||
chmod ${if constants.privileged then "640" else "600"} "$backend_config"
|
||||
''
|
||||
}
|
||||
${constants.grantFileAcl pkgs ''"$backend_config"'' (ctx.userControlExtraGroupsFor "secrets") "r"}
|
||||
|
||||
@@ -12,7 +12,6 @@ let
|
||||
globalTun
|
||||
globalTproxy
|
||||
killSwitchEnabled
|
||||
awgGlobalProfiles
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretEnabled
|
||||
@@ -41,7 +40,9 @@ let
|
||||
|
||||
inherit (routingScripts)
|
||||
xrayTunUpScript
|
||||
xrayTunReloadScript
|
||||
tproxyUpScript
|
||||
tproxyReloadScript
|
||||
tproxyDownScript
|
||||
killSwitchUpScript
|
||||
killSwitchDownScript
|
||||
@@ -74,6 +75,135 @@ let
|
||||
perAppViaAwg = perAppViaInterfaceOutbounds != [ ] || perAppViaRuntime || ctx.perAppViaProfiles;
|
||||
# Or any outbound, through a pin slot: either way, the apps' slices and their marking.
|
||||
perAppViaEnabled = perAppViaAwg || perAppRouting.pinUp != { };
|
||||
# A per-app backend every user's apps share. perApp members may only start it (polkit.nix):
|
||||
# it goes once the last user's marking unit that requires it stops, or the last pin of it.
|
||||
perAppSharedBackend =
|
||||
unit: restartOnSwitch (lib.recursiveUpdate unit { unitConfig.StopWhenUnneeded = true; });
|
||||
# A switch restarts it rather than stopping it across activation: a shorter gap, and a
|
||||
# restart keeps the per-app holds (user-rules.nix). [Service] is where the switch reads it.
|
||||
restartOnSwitch = unit: lib.recursiveUpdate unit { serviceConfig."X-StopIfChanged" = false; };
|
||||
# Rules a firewall reload can flush, put back by `reload` (a start of the firewall: by
|
||||
# proxy-suite-firewall-reapply). After=, or the firewall's flush could come after it.
|
||||
reloadAfterFirewall =
|
||||
reload: unit:
|
||||
lib.recursiveUpdate unit {
|
||||
after = (unit.after or [ ]) ++ [ "nftables.service" ];
|
||||
serviceConfig.ExecReload = reload;
|
||||
unitConfig.ReloadPropagatedFrom = [ "nftables.service" ];
|
||||
};
|
||||
# NixOS's firewall loads the static tables itself (constants.persistedNftDir); the per-app
|
||||
# ones hold cgroup matches, which fail the firewall's whole load once the cgroup is gone.
|
||||
firewallIncludes = ctx.firewallIncludesTables;
|
||||
reloadAfterFirewallUnlessIncluded =
|
||||
reload: if firewallIncludes then lib.id else reloadAfterFirewall reload;
|
||||
# What proxy-suite-firewall-reapply reloads, as systemctl patterns.
|
||||
firewallReapplyUnits =
|
||||
lib.optionals (!firewallIncludes) (
|
||||
lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service"
|
||||
++ lib.optional (proxyEnabled || proxyInboundsEnabled) "proxy-suite-daemon-guard.service"
|
||||
++ lib.optional (proxyEnabled && globalTproxy.enable) "${serviceNames.tproxy}.service"
|
||||
# Only XRay's TUN has a reload; sing-box's would be restarted.
|
||||
++ lib.optional (proxyEnabled && globalTun.enable && pureXrayEnabled) "${serviceNames.tun}.service"
|
||||
)
|
||||
++ lib.optionals (proxyEnabled && perAppRoutingTun.enable) [
|
||||
"${serviceNames.perAppTun}.service"
|
||||
"${serviceNames.perAppTun}-user@*.service"
|
||||
]
|
||||
++ lib.optionals (proxyEnabled && perAppRoutingTproxy.enable) [
|
||||
"${serviceNames.perAppTproxy}.service"
|
||||
"${serviceNames.perAppTproxy}-user@*.service"
|
||||
]
|
||||
++ lib.optional perAppViaAwg "proxy-suite-per-app-via@*.service"
|
||||
++ map (route: "proxy-suite-per-app-via-${route}@*.service") (
|
||||
builtins.attrNames perAppRouting.pinUp
|
||||
);
|
||||
# A per-app route's DNS forwarder (nftables.nix's dns_redirect), up while the route or one
|
||||
# of its pin slots is: a listener for the route's own mark, and one for each slot's.
|
||||
perAppDnsUnit = route: "proxy-suite-per-app-${route}-dns.service";
|
||||
mkPerAppDnsForwarder =
|
||||
{
|
||||
route,
|
||||
mark,
|
||||
basePort,
|
||||
pinMarkBase,
|
||||
pins,
|
||||
bind ? [ ],
|
||||
}:
|
||||
let
|
||||
listeners = [
|
||||
"${toString basePort}:${toString mark}"
|
||||
]
|
||||
++ lib.genList (slot: "${toString (basePort + 1 + slot)}:${toString (pinMarkBase + slot)}") (
|
||||
if pins then ctx.perAppPinSlots else 0
|
||||
);
|
||||
in
|
||||
restartOnSwitch (mkRestartingService {
|
||||
description = "proxy-suite per-app ${route} DNS forwarder";
|
||||
execStart = lib.concatStringsSep " " (
|
||||
[
|
||||
ctx.python3
|
||||
"${ctx.proxySuiteScriptsDir}/per_app_dns.py"
|
||||
]
|
||||
++ map (l: "--listen ${l}") listeners
|
||||
++ map (a: "--bind ${a}") bind
|
||||
++ [ ctx.constants.perAppDnsUpstream ]
|
||||
);
|
||||
runtimeDirectory = "proxy-suite-per-app-${route}-dns";
|
||||
extraServiceConfig = {
|
||||
# Ready once it listens, so the route's apps' first lookup finds it.
|
||||
Type = "notify";
|
||||
NotifyAccess = "main";
|
||||
RestartSec = 2;
|
||||
DynamicUser = true;
|
||||
# SO_MARK on its sockets, and nothing else.
|
||||
AmbientCapabilities = [ "CAP_NET_ADMIN" ];
|
||||
CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
|
||||
NoNewPrivileges = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
PrivateTmp = true;
|
||||
PrivateDevices = true;
|
||||
ProtectClock = true;
|
||||
ProtectHostname = true;
|
||||
ProtectKernelLogs = true;
|
||||
ProtectKernelModules = true;
|
||||
ProtectKernelTunables = true;
|
||||
ProtectControlGroups = true;
|
||||
RestrictNamespaces = true;
|
||||
RestrictRealtime = true;
|
||||
LockPersonality = true;
|
||||
MemoryDenyWriteExecute = true;
|
||||
SystemCallArchitectures = "native";
|
||||
RestrictAddressFamilies = [
|
||||
"AF_UNIX"
|
||||
"AF_INET"
|
||||
"AF_INET6"
|
||||
];
|
||||
SystemCallFilter = [ "@system-service" ];
|
||||
# The apps' queries on loopback, sent on to the upstream the backend answers for.
|
||||
IPAddressAllow = [
|
||||
"localhost"
|
||||
ctx.constants.perAppDnsUpstream
|
||||
];
|
||||
IPAddressDeny = "any";
|
||||
};
|
||||
})
|
||||
// {
|
||||
unitConfig.StopWhenUnneeded = true;
|
||||
};
|
||||
# The global TUN and TProxy carry every app already: the per-app TProxy backend, its pin
|
||||
# slots and per-app zapret refuse to start under them, and go when one starts
|
||||
# (constants.refuseUnderGlobal).
|
||||
globalModeUnits = [
|
||||
"${serviceNames.tproxy}.service"
|
||||
"${serviceNames.tun}.service"
|
||||
];
|
||||
perAppUnderGlobalModes = [
|
||||
"${serviceNames.perAppTproxy}.service"
|
||||
"proxy-suite-per-app-via-tproxy@*.service"
|
||||
"proxy-suite-per-app-via-tun@*.service"
|
||||
"${serviceNames.perAppZapret}.service"
|
||||
];
|
||||
|
||||
# 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
|
||||
@@ -99,7 +229,9 @@ let
|
||||
{
|
||||
enable = proxyEnabled;
|
||||
name = serviceNames.socks;
|
||||
value = mkRestartingService {
|
||||
# No PropagatesStopTo= TProxy: it stops TProxy on a restart too, which should hold the
|
||||
# traffic meanwhile. `proxy off` stops TProxy itself.
|
||||
value = restartOnSwitch (mkRestartingService {
|
||||
description = "${backendDescription} proxy client (SOCKS + TProxy-ready)";
|
||||
# Only XRay goes through the OpenSSH unit's listener.
|
||||
after = [
|
||||
@@ -114,11 +246,18 @@ let
|
||||
++ lib.optional torOutboundEnabled "proxy-suite-tor.service"
|
||||
++ map (j: "proxy-suite-wb-joiner-${j.tag}.service") whitelistBypassJoiners;
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
# The hop login drawn as root, ahead of the start script, which ProtectSystem keeps
|
||||
# from writing /run (constants.ensureHopLogin).
|
||||
execStartPre = lib.filter (x: x != null) [
|
||||
(ctx.constants.daemonMetadataGuard ctx.pkgs)
|
||||
"+${ctx.constants.ensureHopLogin ctx.pkgs}"
|
||||
];
|
||||
execStart = scripts.startSocks;
|
||||
runtimeDirectory = serviceNames.socks;
|
||||
stateDirectory = "proxy-suite";
|
||||
extraServiceConfig = xrayAssetEnv // spoolReaderSandbox [ ];
|
||||
};
|
||||
# The hybrid sidecar's config has no geo rules: only XRay as the backend reads them.
|
||||
extraServiceConfig = lib.optionalAttrs pureXrayEnabled xrayAssetEnv // spoolReaderSandbox [ ];
|
||||
});
|
||||
}
|
||||
{
|
||||
enable = proxyInboundsEnabled;
|
||||
@@ -139,6 +278,7 @@ let
|
||||
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service"
|
||||
++ lib.optional torOnionEnabled "proxy-suite-tor.service";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStartPre = ctx.constants.daemonMetadataGuard ctx.pkgs;
|
||||
execStart = scripts.startInbounds;
|
||||
# inbounds.routing.serverSource's dummy interface.
|
||||
execStopPost = scripts.stopInboundsInterface;
|
||||
@@ -146,9 +286,24 @@ let
|
||||
# The collector's file.
|
||||
stateDirectory = "proxy-suite";
|
||||
# While XRay still runs: what it counted since the last timer run.
|
||||
extraServiceConfig = xrayAssetEnv // {
|
||||
ExecStop = scripts.collectInboundStats;
|
||||
};
|
||||
extraServiceConfig =
|
||||
xrayAssetEnv
|
||||
// {
|
||||
ExecStop = scripts.collectInboundStats;
|
||||
}
|
||||
# Nothing it runs is setuid (setpriv drops to the service user by itself), and no
|
||||
# other unit shares its temporary files.
|
||||
// lib.optionalAttrs ctx.constants.privileged {
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
# Root parses the group-writable inbounds.d: it writes nowhere but its runtime
|
||||
# and state directories, which systemd leaves writable.
|
||||
ProtectSystem = "strict";
|
||||
ProtectKernelTunables = true;
|
||||
ProtectControlGroups = true;
|
||||
# The stats API's directory is the daemon's alone now, no setgid one to make.
|
||||
RestrictSUIDSGID = true;
|
||||
};
|
||||
};
|
||||
}
|
||||
{
|
||||
@@ -158,7 +313,11 @@ let
|
||||
description = "Apply proxy-suite inbound users and listeners added at runtime";
|
||||
execStart = scripts.reloadInbounds;
|
||||
stateDirectory = "proxy-suite";
|
||||
extraServiceConfig.RemainAfterExit = false;
|
||||
# Root, over the spool userControl's group writes.
|
||||
extraServiceConfig = {
|
||||
RemainAfterExit = false;
|
||||
}
|
||||
// spoolReaderSandbox [ ];
|
||||
};
|
||||
}
|
||||
{
|
||||
@@ -173,20 +332,22 @@ let
|
||||
extraServiceConfig.RemainAfterExit = false;
|
||||
};
|
||||
}
|
||||
# Pulled in by every global tunnel and left up when it stops or crashes: only
|
||||
# proxy-ctl's off verbs take it down. After them, so a first start still fetches
|
||||
# subscriptions and resolves endpoints directly.
|
||||
# Up from boot, before any network, and pulled in by every global tunnel; only proxy-ctl's
|
||||
# off verbs take it down. What the tunnels fetch to come up goes as a user it lets past.
|
||||
{
|
||||
enable = killSwitchEnabled;
|
||||
name = serviceNames.killSwitch;
|
||||
value =
|
||||
mkOneshotService {
|
||||
description = "proxy-suite kill switch - reject traffic outside the global tunnel";
|
||||
# After the firewall: its start flushes the whole ruleset on some hosts.
|
||||
after = [
|
||||
"${serviceNames.socks}.service"
|
||||
"${serviceNames.tun}.service"
|
||||
]
|
||||
++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles);
|
||||
"sysinit.target"
|
||||
"nftables.service"
|
||||
"firewall.service"
|
||||
];
|
||||
wants = [ "network-pre.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = killSwitchUpScript;
|
||||
execStop = killSwitchDownScript;
|
||||
extraServiceConfig.ExecReload = killSwitchUpScript;
|
||||
@@ -195,100 +356,210 @@ let
|
||||
# new rules from a switch are swapped in by a reload instead, in one transaction.
|
||||
// {
|
||||
reloadIfChanged = true;
|
||||
before = [ "network-pre.target" ];
|
||||
unitConfig = {
|
||||
# Not stopped at shutdown either, unlike the units it guards.
|
||||
DefaultDependencies = false;
|
||||
}
|
||||
# Put back after a firewall reload that flushed the ruleset (see reloadAfterFirewall).
|
||||
// lib.optionalAttrs (!firewallIncludes) {
|
||||
ReloadPropagatedFrom = [ "nftables.service" ];
|
||||
};
|
||||
};
|
||||
}
|
||||
# A start or restart of the firewall, which flushes the ruleset on some hosts, reloads
|
||||
# what reloadAfterFirewall covers; a reload does nothing to a unit that is not up.
|
||||
{
|
||||
enable = ctx.constants.privileged && firewallReapplyUnits != [ ];
|
||||
name = "proxy-suite-firewall-reapply";
|
||||
value = mkOneshotService {
|
||||
description = "proxy-suite - put its nftables tables back after the firewall starts";
|
||||
after = [ "nftables.service" ];
|
||||
wantedBy = [ "nftables.service" ];
|
||||
# --no-block: the units it reloads are ordered after nftables, whose start this is
|
||||
# part of.
|
||||
execStart = "-${ctx.constants.systemctl} try-reload-or-restart --no-block ${lib.concatStringsSep " " firewallReapplyUnits}";
|
||||
# Inactive once done, so the firewall's next start runs it again.
|
||||
extraServiceConfig.RemainAfterExit = false;
|
||||
};
|
||||
}
|
||||
# The daemon guard (constants.daemonMetadataGuard) on its own as well, so that a firewall
|
||||
# that flushed the ruleset gets it back, not only the next start of the units that load it.
|
||||
{
|
||||
enable = ctx.constants.privileged && (proxyEnabled || proxyInboundsEnabled);
|
||||
name = "proxy-suite-daemon-guard";
|
||||
value =
|
||||
let
|
||||
load = [
|
||||
(ctx.constants.daemonMetadataGuard ctx.pkgs)
|
||||
]
|
||||
++ lib.optional firewallIncludes "-${routingScripts.persistDaemonGuardScript}";
|
||||
in
|
||||
mkOneshotService {
|
||||
description = "proxy-suite - keep cloud metadata and the loopback hops from other users";
|
||||
after = [ "nftables.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = load;
|
||||
extraServiceConfig.ExecReload = load;
|
||||
}
|
||||
// {
|
||||
reloadIfChanged = true;
|
||||
}
|
||||
// lib.optionalAttrs (!firewallIncludes) {
|
||||
unitConfig.ReloadPropagatedFrom = [ "nftables.service" ];
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = proxyEnabled && globalTproxy.enable;
|
||||
name = serviceNames.tproxy;
|
||||
value = mkOneshotService {
|
||||
description = "proxy-suite TProxy - nftables rules and policy routing";
|
||||
after = [
|
||||
"network.target"
|
||||
"${serviceNames.socks}.service"
|
||||
];
|
||||
wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ];
|
||||
requires = [ "${serviceNames.socks}.service" ];
|
||||
wants = lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
|
||||
conflicts = [
|
||||
"${serviceNames.tun}.service"
|
||||
"${serviceNames.perAppTproxy}.service"
|
||||
];
|
||||
execStart = tproxyUpScript;
|
||||
execStop = tproxyDownScript;
|
||||
};
|
||||
# Put back with the firewall: all the host's (and the LAN's) traffic, otherwise.
|
||||
value = restartOnSwitch (
|
||||
reloadAfterFirewallUnlessIncluded tproxyReloadScript (mkOneshotService {
|
||||
description = "proxy-suite TProxy - nftables rules and policy routing";
|
||||
after = [
|
||||
"network.target"
|
||||
"${serviceNames.socks}.service"
|
||||
];
|
||||
wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ];
|
||||
# Wants=, not Requires=: a restart of the backend would restart this too, and the
|
||||
# host's traffic go direct until it is back.
|
||||
wants = [
|
||||
"${serviceNames.socks}.service"
|
||||
]
|
||||
++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
|
||||
conflicts = [ "${serviceNames.tun}.service" ];
|
||||
execStartPre = ctx.constants.stopPerAppUnits ctx.pkgs perAppUnderGlobalModes;
|
||||
execStart = tproxyUpScript;
|
||||
# Post: also after a start that failed partway, whose marking table would
|
||||
# otherwise outlive it and send marked traffic out past the kill switch.
|
||||
execStopPost = tproxyDownScript;
|
||||
})
|
||||
);
|
||||
}
|
||||
{
|
||||
enable = proxyEnabled && globalTun.enable;
|
||||
name = serviceNames.tun;
|
||||
value = mkRestartingService {
|
||||
description = "${backendDescription} TUN proxy client";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [
|
||||
"network-online.target"
|
||||
]
|
||||
++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
|
||||
wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ];
|
||||
conflicts = [ "${serviceNames.tproxy}.service" ];
|
||||
execStartPre = tunCleanupScript;
|
||||
execStart = scripts.startTun;
|
||||
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
|
||||
execStopPost = tunCleanupScript;
|
||||
runtimeDirectory = serviceNames.tun;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
value = restartOnSwitch (
|
||||
(if pureXrayEnabled then reloadAfterFirewallUnlessIncluded xrayTunReloadScript else lib.id)
|
||||
(mkRestartingService {
|
||||
description = "${backendDescription} TUN proxy client";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [
|
||||
"network-online.target"
|
||||
]
|
||||
++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
|
||||
wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ];
|
||||
conflicts = [ "${serviceNames.tproxy}.service" ];
|
||||
execStartPre = [
|
||||
(ctx.constants.stopPerAppUnits ctx.pkgs perAppUnderGlobalModes)
|
||||
tunCleanupScript
|
||||
(ctx.constants.ensureHopLogin ctx.pkgs)
|
||||
];
|
||||
execStart = scripts.startTun;
|
||||
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
|
||||
execStopPost = tunCleanupScript;
|
||||
runtimeDirectory = serviceNames.tun;
|
||||
stateDirectory = "proxy-suite";
|
||||
})
|
||||
);
|
||||
}
|
||||
{
|
||||
enable = proxyEnabled && perAppRoutingTun.enable;
|
||||
name = serviceNames.perAppTun;
|
||||
value = mkRestartingService {
|
||||
description = "proxy-suite per-app-routing TUN backend";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
execStartPre = perAppRouting.perAppTunDownScript;
|
||||
execStart = scripts.startPerAppTun;
|
||||
execStartPost = perAppRouting.perAppTunUpScript;
|
||||
execStopPost = perAppRouting.perAppTunDownScript;
|
||||
runtimeDirectory = serviceNames.perAppTun;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
value = reloadAfterFirewall perAppRouting.perAppTunReloadScript (
|
||||
perAppSharedBackend (mkRestartingService {
|
||||
description = "proxy-suite per-app-routing TUN backend";
|
||||
after = [
|
||||
"network-online.target"
|
||||
(perAppDnsUnit "tun")
|
||||
];
|
||||
wants = [
|
||||
"network-online.target"
|
||||
(perAppDnsUnit "tun")
|
||||
];
|
||||
execStartPre = [
|
||||
perAppRouting.perAppTunDownScript
|
||||
(ctx.constants.ensureHopLogin ctx.pkgs)
|
||||
];
|
||||
execStart = scripts.startPerAppTun;
|
||||
execStartPost = perAppRouting.perAppTunUpScript;
|
||||
execStopPost = perAppRouting.perAppTunDownScript;
|
||||
runtimeDirectory = serviceNames.perAppTun;
|
||||
stateDirectory = "proxy-suite";
|
||||
})
|
||||
);
|
||||
}
|
||||
{
|
||||
enable = proxyEnabled && perAppRoutingTun.enable;
|
||||
name = "${serviceNames.perAppTun}-user@";
|
||||
value = mkUserRuleService {
|
||||
# Its rules back in after the backend's table, and the hold's, came back (After=).
|
||||
value = reloadAfterFirewall "${perAppRouting.perAppTunUserRuleStart} %i" (mkUserRuleService {
|
||||
description = "Enable proxy-suite app TUN marking for user %i";
|
||||
backendService = serviceNames.perAppTun;
|
||||
execStart = "${perAppRouting.perAppTunUserRuleStart} %i";
|
||||
execStop = "${perAppRouting.perAppTunUserRuleStop} %i";
|
||||
};
|
||||
});
|
||||
}
|
||||
{
|
||||
enable = proxyEnabled && perAppRoutingTproxy.enable;
|
||||
name = serviceNames.perAppTproxy;
|
||||
value = mkOneshotService {
|
||||
description = "proxy-suite per-app-routing TProxy backend";
|
||||
after = [
|
||||
"network.target"
|
||||
"${serviceNames.socks}.service"
|
||||
];
|
||||
requires = [ "${serviceNames.socks}.service" ];
|
||||
conflicts = [
|
||||
"${serviceNames.tproxy}.service"
|
||||
"${serviceNames.tun}.service"
|
||||
];
|
||||
execStart = perAppRouting.perAppTproxyUpScript;
|
||||
execStop = perAppRouting.perAppTproxyDownScript;
|
||||
value = reloadAfterFirewall perAppRouting.perAppTproxyReloadScript (
|
||||
perAppSharedBackend (mkOneshotService {
|
||||
description = "proxy-suite per-app-routing TProxy backend";
|
||||
after = [
|
||||
"network.target"
|
||||
"${serviceNames.socks}.service"
|
||||
(perAppDnsUnit "tproxy")
|
||||
];
|
||||
requires = [ "${serviceNames.socks}.service" ];
|
||||
wants = [ (perAppDnsUnit "tproxy") ];
|
||||
execStartPre = ctx.constants.refuseUnderGlobal ctx.pkgs globalModeUnits;
|
||||
execStart = perAppRouting.perAppTproxyUpScript;
|
||||
# Post: after a start that failed partway too (see the global TProxy unit).
|
||||
execStopPost = perAppRouting.perAppTproxyDownScript;
|
||||
})
|
||||
);
|
||||
}
|
||||
{
|
||||
enable = proxyEnabled && perAppRoutingTun.enable;
|
||||
name = "proxy-suite-per-app-tun-dns";
|
||||
value = mkPerAppDnsForwarder {
|
||||
route = "tun";
|
||||
mark = perAppRoutingTun.fwmark;
|
||||
basePort = ctx.constants.perAppTunDnsBasePort;
|
||||
pinMarkBase = ctx.constants.perAppPinTunFwmarkBase;
|
||||
pins = ctx.perAppPinTun;
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = proxyEnabled && perAppRoutingTproxy.enable;
|
||||
name = "proxy-suite-per-app-tproxy-dns";
|
||||
value = mkPerAppDnsForwarder {
|
||||
route = "tproxy";
|
||||
mark = perAppRoutingTproxy.fwmark;
|
||||
basePort = ctx.constants.perAppTproxyDnsBasePort;
|
||||
pinMarkBase = ctx.constants.perAppPinTproxyFwmarkBase;
|
||||
pins = ctx.perAppPinTproxy;
|
||||
# The mark takes the queries to a local route (see per_app_dns.py's BIND).
|
||||
bind = [ "127.0.0.1" ];
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = proxyEnabled && perAppRoutingTproxy.enable;
|
||||
name = "${serviceNames.perAppTproxy}-user@";
|
||||
value = mkUserRuleService {
|
||||
# Its rules back in after the backend's table, and the hold's, came back (After=).
|
||||
value = reloadAfterFirewall "${perAppRouting.perAppTproxyUserRuleStart} %i" (mkUserRuleService {
|
||||
description = "Enable proxy-suite app TProxy marking for user %i";
|
||||
backendService = serviceNames.perAppTproxy;
|
||||
execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
|
||||
execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
|
||||
};
|
||||
});
|
||||
}
|
||||
# Declared with zapret's own units (zapret.nix, zapret2.nix).
|
||||
{
|
||||
enable = perAppZapretEnabled;
|
||||
name = serviceNames.perAppZapret;
|
||||
value = perAppSharedBackend { };
|
||||
}
|
||||
{
|
||||
enable = perAppZapretEnabled;
|
||||
@@ -306,31 +577,54 @@ let
|
||||
{
|
||||
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" ];
|
||||
};
|
||||
};
|
||||
# Its table, rules and users' rules back after a firewall reload that flushed them.
|
||||
value = restartOnSwitch (
|
||||
reloadAfterFirewall
|
||||
[
|
||||
"${perAppRouting.viaUp} %i"
|
||||
"${perAppRouting.viaReapply} %i"
|
||||
]
|
||||
(mkRestartingService {
|
||||
description = "proxy-suite per-app routing via %i";
|
||||
execStartPre = "${perAppRouting.viaUp} %i";
|
||||
execStart = "${perAppRouting.viaDns} %i";
|
||||
# viaUp starts the table empty: after a restart, the users' rules go back in.
|
||||
execStartPost = "${perAppRouting.viaReapply} %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;
|
||||
# Root still, though with one capability: the disks' device nodes, /proc/sys and
|
||||
# cgroups are root's to write without any, and the forwarder answers apps.
|
||||
PrivateDevices = true;
|
||||
ProtectKernelTunables = true;
|
||||
ProtectKernelModules = true;
|
||||
ProtectControlGroups = true;
|
||||
RestrictRealtime = true;
|
||||
RestrictSUIDSGID = true;
|
||||
LockPersonality = true;
|
||||
# nft and ip rules, and SO_MARK on the forwarder's sockets.
|
||||
CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
|
||||
# Netlink for nft and ip, unix for the readiness notice, IP for the forwarder.
|
||||
RestrictAddressFamilies = [
|
||||
"AF_UNIX"
|
||||
"AF_INET"
|
||||
"AF_INET6"
|
||||
"AF_NETLINK"
|
||||
];
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
]
|
||||
# `apps run --via <tag>` for any other outbound: a pin slot of per-app TProxy or TUN for
|
||||
@@ -343,21 +637,34 @@ let
|
||||
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 ];
|
||||
};
|
||||
# Its table and its users' rules back after a firewall reload that flushed them. The
|
||||
# users' holds keep their apps in while it rebuilds.
|
||||
restartOnSwitch (
|
||||
reloadAfterFirewall
|
||||
[
|
||||
"${perAppRouting.pinUp.${route}} %i"
|
||||
"${perAppRouting.viaReapply} ${route}-%i"
|
||||
]
|
||||
(
|
||||
mkOneshotService {
|
||||
description = "proxy-suite per-app ${route} pin for the outbound %i (in hex)";
|
||||
execStart = "${perAppRouting.pinUp.${route}} %i";
|
||||
execStartPost = "${perAppRouting.viaReapply} ${route}-%i";
|
||||
execStop = "${perAppRouting.pinDown.${route}} %i";
|
||||
after = [
|
||||
backend
|
||||
(perAppDnsUnit route)
|
||||
];
|
||||
requires = [ backend ];
|
||||
wants = [ (perAppDnsUnit route) ];
|
||||
# As per-app TProxy: under a global mode, proxy-ctl runs the app without its route.
|
||||
execStartPre = ctx.constants.refuseUnderGlobal ctx.pkgs globalModeUnits;
|
||||
}
|
||||
// {
|
||||
partOf = [ backend ];
|
||||
}
|
||||
)
|
||||
);
|
||||
}) (builtins.attrNames perAppRouting.pinUp)
|
||||
++ [
|
||||
{
|
||||
@@ -367,6 +674,12 @@ let
|
||||
description = "Enable proxy-suite per-app via marking for %i";
|
||||
execStart = "${perAppRouting.viaUserStart} %i";
|
||||
execStop = "${perAppRouting.viaUserStop} %i";
|
||||
# No unit names the via unit from <uid>-<key>, so no Requires= can hold it for
|
||||
# StopWhenUnneeded=: the last user's unit takes it down itself.
|
||||
execStopPost = "${perAppRouting.viaRetire} %i";
|
||||
# A switch's stop would take the via unit down under the running apps; a new via
|
||||
# unit puts the rules back itself (viaReapply). In [Service], where the switch reads it.
|
||||
extraServiceConfig.X-RestartIfChanged = false;
|
||||
};
|
||||
}
|
||||
{
|
||||
@@ -392,7 +705,20 @@ let
|
||||
value = mkOneshotService {
|
||||
description = "Set proxy-suite route mode to %i";
|
||||
execStart = "${scripts.setRouteModeScript} %i";
|
||||
extraServiceConfig.RemainAfterExit = false;
|
||||
# Root, started by userControl's group: it writes the mode file and restarts the
|
||||
# proxy, nothing else.
|
||||
extraServiceConfig = {
|
||||
RemainAfterExit = false;
|
||||
}
|
||||
// spoolReaderSandbox [ ]
|
||||
// lib.optionalAttrs ctx.constants.privileged {
|
||||
# Where the mode file lives, which nothing else makes: kept between runs, and
|
||||
# writable under ProtectSystem, whether or not it exists yet.
|
||||
RuntimeDirectory = "proxy-suite";
|
||||
RuntimeDirectoryPreserve = "yes";
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
};
|
||||
};
|
||||
}
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user