Files
proxy-suite-flake/modules/proxy-suite/service/units.nix
T

501 lines
18 KiB
Nix

# Systemd unit definitions for proxy-suite services and timers.
{ ctx }:
let
inherit (ctx)
lib
builders
proxyCfg
proxyEnabled
hybridEnabled
pureXrayEnabled
globalTun
globalTproxy
killSwitchEnabled
awgGlobalProfiles
perAppRoutingTun
perAppRoutingTproxy
perAppZapretEnabled
perAppViaInterfaceOutbounds
perAppViaRuntime
sshProxyOutboundEnabled
sshProxyUnitEnabled
torOutboundEnabled
torOnionEnabled
whitelistBypassJoiners
proxyInboundsEnabled
proxyInboundsRuntimeEnabled
proxyInboundsNeedLocalProxy
scripts
perAppRouting
routingScripts
cfg
;
inherit (cfg) geodata;
inherit (builders)
mkAnchorService
mkRestartingService
mkOneshotService
mkUserRuleService
;
inherit (routingScripts)
xrayTunUpScript
tproxyUpScript
tproxyDownScript
killSwitchUpScript
killSwitchDownScript
tunCleanupScript
;
serviceNames = {
socks = "proxy-suite-socks";
tproxy = "proxy-suite-tproxy";
tun = "proxy-suite-tun";
killSwitch = "proxy-suite-killswitch";
perAppTun = "proxy-suite-per-app-tun";
perAppTproxy = "proxy-suite-per-app-tproxy";
perAppZapret = "proxy-suite-per-app-zapret";
subscriptionUpdate = "proxy-suite-subscription-update";
inbounds = "proxy-suite-inbounds";
inboundStats = "proxy-suite-inbound-stats";
};
backendDescription =
if pureXrayEnabled then
"XRay"
else if hybridEnabled then
"sing-box + XRay sidecar"
else
"sing-box";
localProxyAuthEnabled = ctx.localProxy.authEnabled;
# `apps run --via`: an "interface" AmneziaWG outbound to run through, declared or to come.
perAppViaAwg = perAppViaInterfaceOutbounds != [ ] || perAppViaRuntime || ctx.perAppViaProfiles;
# Or any outbound, through a pin slot: either way, the apps' slices and their marking.
perAppViaEnabled = perAppViaAwg || perAppRouting.pinUp != { };
# For the root units reading what userControl's group writes (outbounds.d,
# subscriptions.d): the file system read-only but for their own directories, so no
# mistake in reading those spools can write anywhere else. Reads are untouched, secrets
# under /root or /home included. `extra`: other paths they update.
spoolReaderSandbox =
extra:
lib.optionalAttrs ctx.constants.privileged (
{
ProtectSystem = "strict";
}
# "-": the socks unit may not have made its runtime directory yet.
// lib.optionalAttrs (extra != [ ]) { ReadWritePaths = map (path: "-${path}") extra; }
);
socksRuntimeDir = "${ctx.constants.runtimeDir}/${serviceNames.socks}";
# XRay finds geoip.dat/geosite.dat through this; sing-box ignores it.
xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) {
Environment = [ "XRAY_LOCATION_ASSET=${geodata.xray.assets}/share/v2ray" ];
};
systemServiceEntries = [
{
enable = proxyEnabled;
name = serviceNames.socks;
value = mkRestartingService {
description = "${backendDescription} proxy client (SOCKS + TProxy-ready)";
# Only XRay goes through the OpenSSH unit's listener.
after = [
"network-online.target"
]
++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service";
# Not after Tor: it may reach its relays through this listener.
wants = [
"network-online.target"
]
++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service"
++ lib.optional torOutboundEnabled "proxy-suite-tor.service"
++ map (j: "proxy-suite-wb-joiner-${j.tag}.service") whitelistBypassJoiners;
wantedBy = [ "multi-user.target" ];
execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite";
extraServiceConfig = xrayAssetEnv // spoolReaderSandbox [ ];
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inbounds;
value = mkRestartingService {
description = "XRay server inbounds (accept connections from outside)";
after = [
"network-online.target"
]
# After the client stack, but not `requires`: direct listeners keep serving
# without it.
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service"
# For the onion address in the share links.
++ lib.optional torOnionEnabled "proxy-suite-tor.service";
wants = [
"network-online.target"
]
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service"
++ lib.optional torOnionEnabled "proxy-suite-tor.service";
wantedBy = [ "multi-user.target" ];
execStart = scripts.startInbounds;
# inbounds.routing.serverSource's dummy interface.
execStopPost = scripts.stopInboundsInterface;
runtimeDirectory = serviceNames.inbounds;
# The collector's file.
stateDirectory = "proxy-suite";
# While XRay still runs: what it counted since the last timer run.
extraServiceConfig = xrayAssetEnv // {
ExecStop = scripts.collectInboundStats;
};
};
}
{
enable = proxyInboundsRuntimeEnabled;
name = "proxy-suite-inbounds-reload";
value = mkOneshotService {
description = "Apply proxy-suite inbound users and listeners added at runtime";
execStart = scripts.reloadInbounds;
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inboundStats;
value = mkOneshotService {
description = "proxy-suite - add up per-user traffic through the inbounds";
after = [ "${serviceNames.inbounds}.service" ];
execStart = scripts.collectInboundStats;
stateDirectory = "proxy-suite";
# Run by a timer: a unit left "active" would never be started again.
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.
{
enable = killSwitchEnabled;
name = serviceNames.killSwitch;
value =
mkOneshotService {
description = "proxy-suite kill switch - reject traffic outside the global tunnel";
after = [
"${serviceNames.socks}.service"
"${serviceNames.tun}.service"
]
++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles);
execStart = killSwitchUpScript;
execStop = killSwitchDownScript;
extraServiceConfig.ExecReload = killSwitchUpScript;
}
# A restart runs ExecStop, which lifts the kill switch until ExecStart puts it back:
# new rules from a switch are swapped in by a reload instead, in one transaction.
// {
reloadIfChanged = true;
};
}
{
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;
};
}
{
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";
};
}
{
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";
};
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-user@";
value = 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;
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app TProxy marking for user %i";
backendService = serviceNames.perAppTproxy;
execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
};
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app zapret marking for user %i";
backendService = serviceNames.perAppZapret;
execStart = "${perAppRouting.perAppZapretUserRuleStart} %i";
execStop = "${perAppRouting.perAppZapretUserRuleStop} %i";
};
}
# `apps run --via <tag>`: an instance per outbound, up while anyone runs through it: its
# rules, and the forwarder its apps' lookups go to. Each user's apps in its slice are
# marked by the next unit (<uid>-<instance>).
{
enable = perAppViaAwg;
name = "proxy-suite-per-app-via@";
value = mkRestartingService {
description = "proxy-suite per-app routing via %i";
execStartPre = "${perAppRouting.viaUp} %i";
execStart = "${perAppRouting.viaDns} %i";
execStopPost = "${perAppRouting.viaDown} %i";
runtimeDirectory = "proxy-suite-per-app-via-%i";
extraServiceConfig = {
# Ready once the forwarder listens, so the app's first lookup finds it.
Type = "notify";
NotifyAccess = "main";
RestartSec = 2;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
ProtectClock = true;
ProtectHostname = true;
ProtectKernelLogs = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
LockPersonality = true;
# nft and ip rules, and SO_MARK on the forwarder's sockets.
CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
};
};
}
]
# `apps run --via <tag>` for any other outbound: a pin slot of per-app TProxy or TUN for
# each outbound apps run through. Part of the backend whose selector it switches: a
# restart of that switches it again.
++ map (route: {
enable = true;
name = "proxy-suite-per-app-via-${route}@";
value =
let
backend = perAppRouting.pinRoutes.${route}.backend;
in
mkOneshotService {
description = "proxy-suite per-app ${route} pin for the outbound %i (in hex)";
execStart = "${perAppRouting.pinUp.${route}} %i";
execStop = "${perAppRouting.pinDown.${route}} %i";
after = [ backend ];
requires = [ backend ];
# As per-app TProxy: under a global mode, proxy-ctl runs the app without its route.
conflicts = [
"${serviceNames.tproxy}.service"
"${serviceNames.tun}.service"
];
}
// {
partOf = [ backend ];
};
}) (builtins.attrNames perAppRouting.pinUp)
++ [
{
enable = perAppViaEnabled;
name = "proxy-suite-per-app-via-user@";
value = mkOneshotService {
description = "Enable proxy-suite per-app via marking for %i";
execStart = "${perAppRouting.viaUserStart} %i";
execStop = "${perAppRouting.viaUserStop} %i";
};
}
{
# Not gated on hasSubscriptions: runtime subscriptions need refreshing too.
enable = proxyEnabled;
name = serviceNames.subscriptionUpdate;
value = mkOneshotService {
description = "Refresh proxy-suite subscription caches";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStart = scripts.subscriptionUpdateScript;
stateDirectory = "proxy-suite";
# Run by a timer and by `proxy subs update`: a unit left "active" would never run again.
extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ ];
};
}
{
enable = proxyEnabled;
name = "proxy-suite-route-mode@";
value = mkOneshotService {
description = "Set proxy-suite route mode to %i";
execStart = "${scripts.setRouteModeScript} %i";
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-pin@";
value = mkOneshotService {
# %I: proxy-ctl systemd-escapes the tag, so "ssh-proxy" arrives as ssh\x2dproxy.
description = "Pin the proxy-suite outbound to %I";
execStart = "${scripts.pinOutboundScript} %I";
stateDirectory = "proxy-suite";
# It updates the pin in the running proxy's inventory.
extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ socksRuntimeDir ];
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-unpin";
value = mkOneshotService {
description = "Unpin the proxy-suite outbound";
execStart = "${scripts.pinOutboundScript}";
stateDirectory = "proxy-suite";
extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ socksRuntimeDir ];
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-reload";
value = mkOneshotService {
description = "Apply proxy-suite outbounds and subscriptions added at runtime";
execStart = scripts.reloadOutboundsScript;
stateDirectory = "proxy-suite";
extraServiceConfig = {
RemainAfterExit = false;
}
// spoolReaderSandbox [ ];
};
}
];
userServiceEntries = [
{
enable = perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-anchor";
value = mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
}
{
enable = perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-anchor";
value = mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-anchor";
value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
}
{
enable = perAppViaEnabled;
name = "proxy-suite-per-app-via-anchor@";
value = mkAnchorService "proxy-suite-per-app-via-%i.slice" "Anchor service for the proxy-suite per-app via %i slice";
}
];
timerEntries = [
{
enable = proxyEnabled;
name = serviceNames.subscriptionUpdate;
value = {
description = "Periodic proxy-suite subscription refresh";
wantedBy = [ "timers.target" ];
timerConfig = {
# OnActiveSec, not OnBootSec: see the autoProxy timer.
OnActiveSec = "5m";
OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
};
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inboundStats;
value = {
description = "proxy-suite per-user inbound traffic collection";
wantedBy = [ "timers.target" ];
timerConfig = {
# OnActiveSec, not OnBootSec: see the autoProxy timer.
OnActiveSec = "5m";
OnUnitActiveSec = "5m";
};
};
}
];
in
{
inherit
localProxyAuthEnabled
systemServiceEntries
userServiceEntries
timerEntries
;
}