feat: allow using suite on non-nixos systems

This commit is contained in:
FUFSoB committed 2026-09-17 13:27:08 +05:00
1 parent e852bef400
commit 3b568bb54e
63 files changed
+3572 -523

No files matched your search

+32 -16
View File
@@ -1,6 +1,5 @@
# Native AmneziaWG client profile services.
{
config,
lib,
pkgs,
cfg,
@@ -12,7 +11,15 @@ let
profiles = awgCfg.profiles;
profileNames = builtins.attrNames profiles;
globalProfileNames = builtins.attrNames derived.awgGlobalProfiles;
singBoxOutbounds = builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds;
# Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick.
tunnelOutbounds = derived.awgTunnelOutbounds;
interfaceProfiles = lib.filterAttrs (
_: profile:
!builtins.elem profile.asOutbound [
"singBox"
"userspace"
]
) profiles;
serviceName = name: "proxy-suite-awg-${name}";
globalServiceNames = map serviceName globalProfileNames;
allProfileConflicts =
@@ -172,7 +179,7 @@ let
| ${pkgs.gnugrep}/bin/grep -F " wg-quick-${profile.interfaceName}" \
| while read -r _ family table; do nft delete table "$family" "$table" 2>/dev/null || true; done
fi
${config.networking.resolvconf.package}/bin/resolvconf -d "${profile.interfaceName}" -f 2>/dev/null || true
${cfg.host.resolvconfPackage}/bin/resolvconf -d "${profile.interfaceName}" -f 2>/dev/null || true
${pkgs.iproute2}/bin/ip link delete dev ${lib.escapeShellArg profile.interfaceName} 2>/dev/null || true
}
trap cleanup ERR
@@ -255,8 +262,8 @@ let
pkgs.iproute2
pkgs.iputils
pkgs.kmod
config.networking.firewall.package
config.networking.resolvconf.package
cfg.host.firewallPackage
cfg.host.resolvconfPackage
];
serviceConfig = {
Type = "oneshot";
@@ -286,7 +293,7 @@ let
};
};
mkSingBoxService =
mkTunnelService =
ob:
let
profile = profiles.${ob.name};
@@ -294,8 +301,16 @@ let
mkTunnel {
description = "proxy-suite AmneziaWG tunnel behind the ${ob.name} outbound";
unit = serviceName ob.name;
engine = ob.kind;
inherit (ob) tag tunnelPort directPort;
profile = ''
${lib.optionalString (profile.configFile != null) ''
# It may not exist yet: WARP's appears once proxy-suite-warp has registered.
if [ ! -s ${lib.escapeShellArg profile.configFile} ]; then
echo "proxy-suite: waiting for the AmneziaWG profile at ${profile.configFile}" >&2
until [ -s ${lib.escapeShellArg profile.configFile} ]; do sleep 5; done
fi
''}
profile="$RUNTIME_DIRECTORY/profile.conf"
${prepareCommand profile ''"$profile"''}
'';
@@ -424,28 +439,29 @@ let
globalAutostartCount = builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
in
{
environment.systemPackages = [
services.proxy-suite.internal.packages = [
awgCfg.toolsPackage
awgCfg.userspacePackage
];
]
++ lib.optional (builtins.any (ob: ob.kind == "userspace") tunnelOutbounds) awgCfg.wireproxyPackage;
boot.extraModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [
services.proxy-suite.internal.kernelModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [
awgCfg.kernelModulePackage
];
# Replies to the proxy's sockets come in on an interface the host has no route through.
networking.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: ''
services.proxy-suite.internal.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: ''
iifname "${ob.interface}" accept
'') derived.awgInterfaceOutbounds;
systemd.services = lib.mkMerge [
(lib.mapAttrs' (name: profile: lib.nameValuePair (serviceName name) (mkService name profile)) (
lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles
))
services.proxy-suite.internal.services = lib.mkMerge [
(lib.mapAttrs' (
name: profile: lib.nameValuePair (serviceName name) (mkService name profile)
) interfaceProfiles)
(lib.mapAttrs' (
name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile)
) (lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles))
(lib.listToAttrs (map (ob: lib.nameValuePair (serviceName ob.name) (mkSingBoxService ob)) singBoxOutbounds))
) interfaceProfiles)
(lib.listToAttrs (map (ob: lib.nameValuePair (serviceName ob.name) (mkTunnelService ob)) tunnelOutbounds))
(lib.mkIf cfg.proxy.tun.enable {
proxy-suite-tun.conflicts = map (name: "${name}.service") globalServiceNames;
})
+6 -2
View File
@@ -4,7 +4,11 @@
# because sing-box refuses to start when a local rule-set path is missing, so
# every file it will be told about must exist first; the prober needs it to
# publish what it learns, which sing-box then picks up without a restart.
{ pkgs, serviceUser }:
{
pkgs,
serviceUser,
ifPrivileged,
}:
pkgs.writeShellScript "proxy-suite-autoproxy" ''
set -euo pipefail
@@ -21,7 +25,7 @@ pkgs.writeShellScript "proxy-suite-autoproxy" ''
# files: that takes read on it, not just the search the state dir grants.
# Asserted on every render, since StateDirectory= re-owns the tree when the
# units' Group= changes.
install -d -m 0750 -g ${serviceUser} "$(dirname "$path")"
install -d -m 0750 ${ifPrivileged "-g ${serviceUser} "}"$(dirname "$path")"
# Written aside and renamed into place: sing-box reloads on rename (as well
# as on in-place writes), and it never reads a half-written file.
jq -c --arg t "$tag" '
+11 -9
View File
@@ -7,6 +7,8 @@
cfg,
proxyCtl,
autoProxyStateDir,
runtimeDir,
journalctl,
userControlAllows,
}:
@@ -16,7 +18,7 @@ let
stateDirMode = if userControlAllows "autoProxy" then "0771" else "0751";
render = import ./autoproxy-render.nix {
inherit pkgs;
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser;
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser ifPrivileged;
};
jqFile =
path:
@@ -52,7 +54,7 @@ let
set -euo pipefail
export PATH=${bin}
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
index=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}
index=''${PROBE_EXITS_FILE:-${runtimeDir}/proxy-suite-socks/probe-exits.json}
${clashApiBlock}
if [ -z "$clash_api" ]; then
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
@@ -81,7 +83,7 @@ let
# Overridable to rehearse a run against a scratch copy; the units never set them.
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
export PROBE_EXITS_FILE=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}
export PROBE_EXITS_FILE=''${PROBE_EXITS_FILE:-${runtimeDir}/proxy-suite-socks/probe-exits.json}
index=$PROBE_EXITS_FILE
state="$state_dir/state.json"
requests="$state_dir/requests"
@@ -273,7 +275,7 @@ let
last=$(jq -r '.lastRun // 0' "$state")
if [ "$last" -gt 0 ]; then since="@$last"; else since="-${apCfg.interval}"; fi
dialled=$(
journalctl -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null |
${journalctl} -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null |
sed -n 's/.* accepted tcp:\([a-zA-Z0-9._-]*\):[0-9]*.*/\1/p' |
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' |
${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |"}
@@ -442,13 +444,13 @@ let
};
in
{
systemd.services.proxy-suite-autoproxy =
services.proxy-suite.internal.services.proxy-suite-autoproxy =
mkUnit "proxy-suite - find the exit that reaches each destination, and remember it" "";
systemd.services.proxy-suite-autoproxy-learn =
services.proxy-suite.internal.services.proxy-suite-autoproxy-learn =
mkUnit "proxy-suite - probe the destinations asked for with proxy-ctl proxy auto learn" " --requests-only";
systemd.services.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
services.proxy-suite.internal.services.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
description = "proxy-suite - watch live transfers for destinations that crawl directly";
after = [ "proxy-suite-socks.service" ];
serviceConfig = {
@@ -458,7 +460,7 @@ in
// stateDirConfig;
};
systemd.timers.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
services.proxy-suite.internal.timers.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
description = "proxy-suite autoProxy transfer sampling";
wantedBy = [ "timers.target" ];
timerConfig = {
@@ -468,7 +470,7 @@ in
};
};
systemd.timers.proxy-suite-autoproxy = {
services.proxy-suite.internal.timers.proxy-suite-autoproxy = {
description = "proxy-suite autoProxy probe schedule";
wantedBy = [ "timers.target" ];
timerConfig = {
@@ -212,10 +212,12 @@ let
});
in
{
# The local proxy, ready for TProxy. A rootless host can neither take transparent
# connections nor mark sockets: there it is the SOCKS/HTTP listener alone.
tproxy = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
enableTProxy = constants.privileged;
useOutboundRoutingMark = constants.privileged;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
};
@@ -264,10 +264,11 @@ in
# shape out of the same backend primitives.
inherit mkDnsServer;
# As sing-box's: without TProxy and marks on a rootless host.
tproxy = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
enableTProxy = constants.privileged;
useOutboundRoutingMark = constants.privileged;
};
tun = mkConfig {
+173
View File
@@ -0,0 +1,173 @@
# The host-neutral part of proxy-suite: options, generated configs and scripts, and
# the services to run, declared under services.proxy-suite.internal for a host adapter
# (./hosts) to install.
{
zapret,
nixpkgs,
nfqws2-keenetic,
z2k,
}:
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
packages = import ../../pkgs/default.nix { inherit pkgs; };
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
derived = import ./derived.nix { inherit lib cfg; };
in
{
imports = [
./options
];
config = lib.mkMerge [
{
# xray and sing-box default to this flake's own nixpkgs (redirect it
# with inputs.nixpkgs.follows), not the system's: a stable release lags
# both by months, and current xray needs a newer Go than stable ships.
_module.args.proxySuiteUpstream =
let
upstream = nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system};
in
{
xray = import ../../pkgs/xray.nix { pkgs = upstream; };
# AWG 3.1 userspace; its kernel module has to match the system's kernel instead.
amneziaWg = import ../../pkgs/amneziawg.nix { pkgs = upstream; };
inherit (upstream) sing-box;
};
}
(lib.mkIf cfg.enable (
let
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
};
configs = import ./config.nix {
inherit
lib
pkgs
cfg
rules
;
};
in
lib.mkMerge [
(import ./service {
inherit
lib
pkgs
packages
cfg
;
inherit (configs)
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit (nftr)
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
})
(lib.mkIf
(
cfg.zapret.engine == "zapret-discord-youtube"
&& (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)
)
(
import ./zapret.nix {
inherit
lib
pkgs
cfg
zapret
;
inherit (nftr) perAppZapretRulesFile nft;
}
)
)
(lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable))
(
import ./zapret2.nix {
inherit
lib
pkgs
cfg
packages
;
inherit (nftr) perAppZapretRulesFile nft;
zapret2Sources = { inherit nfqws2-keenetic z2k; };
}
)
)
(lib.mkIf cfg.tgWsProxy.enable (
(import ./tg-ws-proxy.nix {
inherit
lib
pkgs
packages
cfg
derived
;
}).config
))
# SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH
# outbound, and a standalone tunnel has no backend at all, so both keep it.
(lib.mkIf derived.sshProxyUnitEnabled (
import ./ssh-proxy.nix {
inherit
lib
pkgs
cfg
derived
;
}
))
(lib.mkIf cfg.warp.enable (
import ./warp.nix {
inherit
lib
pkgs
cfg
derived
;
}
))
(lib.mkIf cfg.amneziaWg.enable (
import ./amnezia-wg.nix {
inherit
lib
pkgs
cfg
derived
;
}
))
]
))
];
}
+14 -189
View File
@@ -1,195 +1,20 @@
# Factory function – receives the zapret flake and this flake's own nixpkgs,
# returns a NixOS module. This lets consumers add a single flake input and get
# everything transitively.
{
zapret,
nixpkgs,
nfqws2-keenetic,
z2k,
}:
{
config,
options,
lib,
pkgs,
...
}:
# Factory: receives the zapret flake and this flake's own nixpkgs, and returns the
# proxy-suite module for each supported host. Consumers add a single flake input and
# get everything transitively.
inputs:
let
cfg = config.services.proxy-suite;
packages = import ../../pkgs/default.nix { inherit pkgs; };
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
derived = import ./derived.nix { inherit lib cfg; };
# Scripts share one store name per block, and journald names a unit's output
# after its ExecStart basename; tag each unit with its own name instead.
unitsWithOwnSyslogIdentifier = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule (
{ name, ... }:
{
config.serviceConfig.SyslogIdentifier = lib.mkIf (lib.hasPrefix "proxy-suite-" name) (
lib.mkDefault (lib.removeSuffix "@" name)
);
}
)
);
core = import ./core.nix inputs;
forHost = adapter: {
imports = [
core
adapter
];
};
in
{
imports = [
./options
];
options.systemd.services = unitsWithOwnSyslogIdentifier;
options.systemd.user.services = unitsWithOwnSyslogIdentifier;
config = lib.mkMerge [
{
# xray and sing-box default to this flake's own nixpkgs (redirect it
# with inputs.nixpkgs.follows), not the system's: a stable release lags
# both by months, and current xray needs a newer Go than stable ships.
_module.args.proxySuiteUpstream =
let
upstream = nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system};
in
{
xray = import ../../pkgs/xray.nix { pkgs = upstream; };
# AWG 3.1 userspace; its kernel module has to match the system's kernel instead.
amneziaWg = import ../../pkgs/amneziawg.nix { pkgs = upstream; };
inherit (upstream) sing-box;
};
}
(lib.mkIf cfg.enable (
let
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
};
configs = import ./config.nix {
inherit
lib
pkgs
cfg
rules
;
};
in
lib.mkMerge [
(import ./service {
inherit
config
options
lib
pkgs
packages
cfg
;
inherit (configs)
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit (nftr)
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
})
(lib.mkIf
(
cfg.zapret.engine == "zapret-discord-youtube"
&& (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)
)
(
import ./zapret.nix {
inherit
lib
pkgs
cfg
zapret
;
inherit (nftr) perAppZapretRulesFile nft;
}
)
)
(lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable))
(
import ./zapret2.nix {
inherit
lib
pkgs
cfg
packages
;
inherit (nftr) perAppZapretRulesFile nft;
zapret2Sources = { inherit nfqws2-keenetic z2k; };
}
)
)
(lib.mkIf cfg.tgWsProxy.enable (
(import ./tg-ws-proxy.nix {
inherit
lib
pkgs
packages
cfg
derived
;
}).config
))
# SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH
# outbound, and a standalone tunnel has no backend at all, so both keep it.
(lib.mkIf derived.sshProxyUnitEnabled (
import ./ssh-proxy.nix {
inherit
lib
pkgs
cfg
derived
;
}
))
(lib.mkIf cfg.warp.enable (
import ./warp.nix {
inherit
lib
pkgs
cfg
derived
;
}
))
(lib.mkIf cfg.amneziaWg.enable (
import ./amnezia-wg.nix {
inherit
config
lib
pkgs
cfg
derived
;
}
))
]
))
];
nixos = forHost ./hosts/nixos.nix;
homeManager = forHost ./hosts/home-manager.nix;
systemManager = forHost ./hosts/system-manager.nix;
nixOnDroid = forHost ./hosts/nix-on-droid.nix;
}
+36 -19
View File
@@ -5,6 +5,8 @@
let
proxyCfg = cfg.proxy;
# Host paths: /var/lib/proxy-suite and /run on a system install.
inherit (cfg.host) stateDir runtimeDir;
singBoxCfg = proxyCfg // {
enable = singBoxEnabled;
package = proxyCfg.singBox.package;
@@ -38,20 +40,17 @@ let
# Without a configFile, proxy-suite-warp registers with wgcf into its state dir.
autoRegister = cfg.warp.enable && cfg.warp.configFile == null;
profilePath =
if cfg.warp.configFile != null then
cfg.warp.configFile
else
"/var/lib/proxy-suite/warp/wgcf-profile.conf";
if cfg.warp.configFile != null then cfg.warp.configFile else "${stateDir}/warp/wgcf-profile.conf";
# Loopback SOCKS listener of proxy-suite-warp-tunnel, which the "warp" outbound dials.
tunnelPort = 18538;
# Its "direct-in" listener, which tells a blocked WARP from a dead uplink.
directPort = 18539;
};
warpOutboundTag = "warp";
# The sing-box tunnel; asOutbound = "interface" comes in through the AmneziaWG profile list.
# The sing-box tunnel; "userspace" and "interface" come in through the AmneziaWG profile list.
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound == "singBox";
# Two ports per "singBox" AmneziaWG outbound, above the autoProxy prober's own
# Two ports per "singBox" or "userspace" AmneziaWG outbound, above the autoProxy prober's own
# listeners (proxy.autoProxy.probeBasePort, 18540 by default, one per exit):
# both bind loopback, so an overlap leaves whichever unit starts second dead.
awgTunnelBasePort = 18600;
@@ -69,12 +68,15 @@ let
tag = name;
kind = profile.asOutbound;
interface = profile.interfaceName;
# Loopback listeners of a "singBox" tunnel, as warpCfg.tunnelPort/directPort.
# Loopback listeners of a "singBox" or "userspace" tunnel, as warpCfg.tunnelPort/directPort
# (only sing-box listens on directPort).
tunnelPort = awgTunnelBasePort + 2 * index;
directPort = awgTunnelBasePort + 1 + 2 * index;
}
) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles));
awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds;
# Profiles run behind a loopback SOCKS hop rather than an interface.
awgTunnelOutbounds = builtins.filter (ob: ob.kind != "interface") awgOutbounds;
proxyInboundsCfg = cfg.inbounds;
proxyInboundsEnabled = proxyInboundsCfg.enable;
@@ -202,19 +204,33 @@ let
userControlAllows =
scope:
userControlEnabled && (userControlCfg.scopes == [ ] || builtins.elem scope userControlCfg.scopes);
managerFlag = lib.optionalString (cfg.host.serviceManager == "systemd-user") " --user";
constants = {
inherit stateDir runtimeDir;
inherit (cfg.host) privileged serviceManager;
# Daemons (sing-box, XRay, the WARP tunnel, OpenSSH, tg-ws-proxy, wgcf) run as this
# user. Its group is not the userControl group: backend configs hold credentials. Start
# scripts still read secrets and program routing as root, then exec the daemon through
# runAsServiceUser with only the capabilities it needs.
# On a rootless host everything already runs as the user: no service user, and
# nothing to hand files over to it.
serviceUser = "proxy-suite-daemon";
# Shell text that only matters when the services run as root.
ifPrivileged = lib.optionalString cfg.host.privileged;
# The commands scripts manage units and read their logs with: the units live in the
# user's manager on a home-manager host, and in proxy-suitectl on nix-on-droid.
systemctl = cfg.host.systemctl + managerFlag;
journalctl = cfg.host.journalctl + managerFlag;
runAsServiceUser =
pkgs: caps:
let
keep = lib.concatMapStrings (cap: ",+${cap}") caps;
in
"${pkgs.util-linux}/bin/setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon --clear-groups"
+ " --inh-caps=-all${keep} --ambient-caps=-all${keep} --bounding-set=-all${keep} --no-new-privs --";
lib.optionalString cfg.host.privileged (
"${pkgs.util-linux}/bin/setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon --clear-groups"
+ " --inh-caps=-all${keep} --ambient-caps=-all${keep} --bounding-set=-all${keep} --no-new-privs --"
);
# The same for a unit that needs no root at all; "+" ExecStartPre/ExecStopPost
# commands still run privileged.
unprivilegedServiceConfig =
@@ -222,7 +238,7 @@ let
let
systemdCaps = map (cap: "CAP_${lib.toUpper cap}") caps;
in
{
lib.optionalAttrs cfg.host.privileged {
User = "proxy-suite-daemon";
Group = "proxy-suite-daemon";
AmbientCapabilities = systemdCaps;
@@ -244,8 +260,8 @@ let
"net_raw"
];
zapret2StateDir = "/var/lib/proxy-suite/zapret2";
zapret2CutoffDir = "/var/lib/proxy-suite/zapret2/cutoff";
zapret2StateDir = "${stateDir}/zapret2";
zapret2CutoffDir = "${stateDir}/zapret2/cutoff";
# Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone.
zapret2CutoffProbeCtMark = 33554432; # 0x2000000
@@ -257,23 +273,23 @@ let
zapret2 = 300;
};
autoProxyStateDir = "/var/lib/proxy-suite/autoproxy";
autoProxyStateDir = "${stateDir}/autoproxy";
# Runtime outbound control. The spool dirs hold one proxy URL per file and are
# group-writable when userControl is on, so proxy-ctl edits them without sudo;
# the pin outlives a reboot, unlike the per-boot route-mode override.
pinnedOutboundFile = "/var/lib/proxy-suite/pinned-outbound";
runtimeOutboundsDir = "/var/lib/proxy-suite/outbounds.d";
runtimeSubscriptionsDir = "/var/lib/proxy-suite/subscriptions.d";
pinnedOutboundFile = "${stateDir}/pinned-outbound";
runtimeOutboundsDir = "${stateDir}/outbounds.d";
runtimeSubscriptionsDir = "${stateDir}/subscriptions.d";
# Written by every backend start script; proxy-ctl reads the socks copy.
outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json";
outboundInventoryFile = "${runtimeDir}/proxy-suite-socks/outbounds.json";
inboundStatsApiPort = 18536;
# sing-box's fake IP caches, one per TUN config; the start script hands it to the backend.
fakeIpCacheDir = "/var/lib/proxy-suite/fakeip";
fakeIpCacheDir = "${stateDir}/fakeip";
# Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches.
outboundTestPort = 18537;
inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json";
inboundStatsFile = "${stateDir}/inbound-stats.json";
# sing-box DNS server resolving through an "interface" AmneziaWG outbound.
awgDnsServerTag = tag: "awg-dns-${tag}";
@@ -360,6 +376,7 @@ in
awgGlobalProfiles
awgOutbounds
awgInterfaceOutbounds
awgTunnelOutbounds
proxyInboundsCfg
proxyInboundsEnabled
proxyInbounds
+30
View File
@@ -0,0 +1,30 @@
# Shared by the adapters whose host runs NixOS's own systemd unit options (NixOS,
# system-manager).
{ lib }:
rec {
# Only what the core set: an internal option's default would add a definition of its
# own. Definitions are forwarded rather than values, so priorities nested inside them
# (mkDefault in a unit, say) still meet the rest of the host's.
forwardWith =
wrap: option:
lib.mkIf (option.highestPrio < (lib.mkOptionDefault null).priority) (
lib.mkMerge (map wrap option.definitions)
);
forward = forwardWith lib.id;
# Scripts share one store name per block, and journald names a unit's output
# after its ExecStart basename; tag each unit with its own name instead.
unitsWithOwnSyslogIdentifier = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule (
{ name, ... }:
{
config.serviceConfig.SyslogIdentifier = lib.mkIf (lib.hasPrefix "proxy-suite-" name) (
lib.mkDefault (lib.removeSuffix "@" name)
);
}
)
);
};
}
@@ -0,0 +1,64 @@
# home-manager: the services run rootless in the user's systemd manager, rendered into
# home-manager's INI form by ./user-units.nix.
{
config,
options,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
host = cfg.host;
internal = cfg.internal;
inherit
(import ./user-units.nix {
inherit lib pkgs;
inherit (host) runtimeDir;
stateDir = dirOf host.stateDir;
})
toService
toTimer
toPath
;
enabled = lib.filterAttrs (_: unit: unit.enable);
in
{
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "home-manager";
privileged = false;
serviceManager = "systemd-user";
stateDir = lib.mkDefault "${config.xdg.stateHome}/proxy-suite";
# A literal path the scripts and proxy-ctl can share: the user's runtime
# directory is only known once the manager runs. Point it at /run/user/UID to
# have it cleared on reboot.
runtimeDir = lib.mkDefault "${config.xdg.cacheHome}/proxy-suite/run";
};
}
(lib.mkIf cfg.enable (
lib.mkMerge [
{
systemd.user.services = lib.mapAttrs toService (
enabled (internal.services // internal.userServices)
);
systemd.user.timers = lib.mapAttrs toTimer (enabled internal.timers);
systemd.user.paths = lib.mapAttrs toPath (enabled internal.paths);
home.packages = lib.mkMerge [
(lib.mkBefore internal.earlyPackages)
internal.packages
];
}
(lib.optionalAttrs (options.systemd.user ? tmpfiles) {
systemd.user.tmpfiles.rules = internal.tmpfiles;
})
]
))
];
}
+123
View File
@@ -0,0 +1,123 @@
# nix-on-droid: no systemd and no root. The units run under proxy-suitectl, a small
# supervisor that reads them, rendered as for a user manager, from a manifest the
# activation links into place; proxy-ctl and the scripts talk to it in systemctl's words.
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
host = cfg.host;
internal = cfg.internal;
home = config.user.home;
inherit
(import ./user-units.nix {
inherit lib pkgs;
inherit (host) runtimeDir;
stateDir = dirOf host.stateDir;
hostPath = "${home}/.nix-profile/bin";
})
toService
toTimer
toPath
;
enabled = lib.filterAttrs (_: unit: unit.enable);
supervisorDir = "${host.runtimeDir}/proxy-suite-supervisor";
# Outside the store, so proxy-suitectl stays the same from one generation to the next.
manifestLink = "${host.stateDir}/supervisor/manifest.json";
manifest = pkgs.writeText "proxy-suite-units.json" (
builtins.toJSON {
services = lib.mapAttrs toService (enabled (internal.services // internal.userServices));
timers = lib.mapAttrs toTimer (enabled internal.timers);
paths = lib.mapAttrs toPath (enabled internal.paths);
inherit (internal) tmpfiles;
}
);
suitectl = import ../../../pkgs/proxy-suite-supervisor.nix { inherit lib pkgs; } {
inherit supervisorDir;
manifest = manifestLink;
inherit (host) runtimeDir;
stateDir = dirOf host.stateDir;
};
suitectlBin = "${suitectl}/bin/proxy-suitectl";
# Once per session tree: nested shells find it exported.
sessionStart = ''
if [ -z "''${__PROXY_SUITE_SESSION:-}" ]; then
export __PROXY_SUITE_SESSION=1
( ${suitectlBin} ensure >/dev/null 2>&1 & )
fi
'';
in
{
options.services.proxy-suite.nixOnDroid.startWithSession = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Start the services when a Nix-on-Droid shell opens, if they are not running yet.
Android offers the app no boot hook, so without this they only start on
`nix-on-droid switch` or `proxy-suitectl boot`. Android may still stop them in
the background: keep the app's wake lock on and exempt it from battery optimisation.
'';
};
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "nix-on-droid";
privileged = false;
serviceManager = "supervisor";
stateDir = lib.mkDefault "${home}/.local/state/proxy-suite";
runtimeDir = lib.mkDefault "${home}/.cache/proxy-suite/run";
systemctl = suitectlBin;
journalctl = "${suitectlBin} journal";
enableIPv6 = true;
# Android's kernel, resolver and firewall are not the app's to change.
kernelPackages = null;
firewallPackage = null;
resolvconfPackage = null;
};
}
(lib.mkIf cfg.enable {
assertions = [
{
assertion = !cfg.gui.enable;
message = "proxy-suite: the GUI needs a desktop session, which a nix-on-droid host does not have; use proxy-ctl or proxy-tui";
}
];
environment.packages = internal.earlyPackages ++ internal.packages ++ [ suitectl ];
build.activationAfter.proxySuite = ''
$DRY_RUN_CMD mkdir -p ${lib.escapeShellArg (dirOf manifestLink)}
$DRY_RUN_CMD ln -sfn ${manifest} ${lib.escapeShellArg manifestLink}
# Starts the supervisor, or restarts what changed under a running one.
if ! $DRY_RUN_CMD ${suitectlBin} boot; then
warnEcho "proxy-suite: some units did not start; see proxy-ctl status"
fi
'';
environment.etc = lib.mkIf cfg.nixOnDroid.startWithSession {
"profile".text = lib.mkAfter sessionStart;
"zshenv".text = lib.mkAfter sessionStart;
};
})
(lib.mkIf (!cfg.enable) {
# Disabled since the last generation: nothing should keep running.
build.activationAfter.proxySuite = ''
if [ -S ${lib.escapeShellArg "${supervisorDir}/control.sock"} ]; then
$DRY_RUN_CMD ${suitectlBin} shutdown || true
fi
'';
})
];
}
+75
View File
@@ -0,0 +1,75 @@
# NixOS: the core's declarations become NixOS settings as they are.
{
config,
options,
lib,
...
}:
let
cfg = config.services.proxy-suite;
internal = options.services.proxy-suite.internal;
inherit (import ./common.nix { inherit lib; })
forwardWith
forward
unitsWithOwnSyslogIdentifier
;
in
{
options.systemd.services = unitsWithOwnSyslogIdentifier;
options.systemd.user.services = unitsWithOwnSyslogIdentifier;
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "nixos";
privileged = true;
serviceManager = "systemd";
inherit (config.networking) enableIPv6;
inherit (config.boot) kernelPackages;
firewallPackage = config.networking.firewall.package;
resolvconfPackage = config.networking.resolvconf.package;
};
}
(lib.mkIf cfg.enable {
systemd.services = forward internal.services;
systemd.user.services = forward internal.userServices;
systemd.timers = forward internal.timers;
systemd.paths = forward internal.paths;
systemd.tmpfiles.rules = forward internal.tmpfiles;
environment.systemPackages = lib.mkMerge [
(forwardWith lib.mkBefore internal.earlyPackages)
(forward internal.packages)
];
users.users = lib.genAttrs cfg.internal.systemUsers (name: {
isSystemUser = true;
group = name;
description = "proxy-suite daemons";
});
users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { });
security.polkit.enable = lib.mkIf cfg.internal.polkit.enable true;
security.polkit.extraConfig = forwardWith lib.mkAfter internal.polkit.rules;
networking.nftables.enable = lib.mkIf cfg.internal.nftables (lib.mkDefault true);
networking.firewall = {
allowedTCPPorts = forward internal.firewall.allowedTCPPorts;
allowedUDPPorts = forward internal.firewall.allowedUDPPorts;
extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules;
};
boot.extraModulePackages = forward internal.kernelModulePackages;
})
# Off by default since nixpkgs 26.11, and always there before, where the option does
# not exist.
(lib.optionalAttrs (options.security.polkit ? enablePkexecWrapper) {
security.polkit.enablePkexecWrapper = lib.mkIf (
cfg.enable && cfg.internal.polkit.pkexecWrapper
) true;
})
];
}
@@ -0,0 +1,118 @@
# system-manager (numtide/system-manager): root services on another distribution. Its
# systemd options are NixOS's own, so units are forwarded as on NixOS; what it lacks
# (user units, polkit, nftables, the firewall, kernel modules) is written to /etc or
# left to the host.
{
config,
options,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
internal = options.services.proxy-suite.internal;
inherit (import ./common.nix { inherit lib; })
forwardWith
forward
unitsWithOwnSyslogIdentifier
;
# For the user manager each session runs: units go to /etc/systemd/user, which it reads
# alongside the distribution's own.
userUnits = import ./user-units.nix {
inherit lib pkgs;
runtimeDir = "%t";
stateDir = "%S";
# The GUI escalates through the distribution's setuid pkexec.
hostPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
};
toINI = lib.generators.toINI { listsAsDuplicateKeys = true; };
userServiceFiles = lib.concatMapAttrs (
name: unit:
let
fileName = "${name}.service";
rendered = userUnits.toService name unit;
file = pkgs.writeText fileName (toINI rendered);
link = target: lib.nameValuePair "systemd/user/${target}/${fileName}" { source = file; };
in
{
"systemd/user/${fileName}".source = file;
}
// lib.listToAttrs (
map (target: link "${target}.wants") (rendered.Install.WantedBy or [ ])
++ map (target: link "${target}.requires") (rendered.Install.RequiredBy or [ ])
)
) (lib.filterAttrs (_: unit: unit.enable) cfg.internal.userServices);
# awg-quick pushes DNS through resolvconf: resolvectl stands in for it where
# systemd-resolved owns resolv.conf, openresolv everywhere else.
resolvconf = pkgs.writeShellScriptBin "resolvconf" ''
if [ -d /run/systemd/resolve ]; then
exec -a resolvconf ${pkgs.systemd}/bin/resolvectl "$@"
fi
exec ${pkgs.openresolv}/bin/resolvconf "$@"
'';
in
{
options.systemd.services = unitsWithOwnSyslogIdentifier;
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "system-manager";
privileged = true;
serviceManager = "systemd";
inherit (config.networking) enableIPv6;
# The host's kernel is not Nix's to extend: AmneziaWG runs in userspace.
kernelPackages = null;
firewallPackage = pkgs.nftables;
resolvconfPackage = resolvconf;
};
}
(lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.internal.kernelModulePackages == [ ];
message = "proxy-suite: system-manager cannot load kernel modules from Nix; leave amneziaWg.kernelModulePackage at null";
}
];
systemd.services = forward internal.services;
systemd.timers = forward internal.timers;
systemd.paths = forward internal.paths;
systemd.tmpfiles.rules = forward internal.tmpfiles;
environment.systemPackages = lib.mkMerge [
(forwardWith lib.mkBefore internal.earlyPackages)
(forward internal.packages)
];
environment.etc = lib.mkMerge [
userServiceFiles
# Read by polkit 0.106 and later; the distribution runs the daemon. The rules
# go through the host's setuid pkexec: nothing here needs a wrapper.
(lib.mkIf cfg.internal.polkit.enable {
"polkit-1/rules.d/50-proxy-suite.rules".text = cfg.internal.polkit.rules;
})
];
users.users = lib.genAttrs cfg.internal.systemUsers (name: {
isSystemUser = true;
group = name;
description = "proxy-suite daemons";
});
users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { });
# Only reported: system-manager leaves the host firewall alone. The routing modes
# load their own nftables tables, and the distribution's loose reverse-path filter
# already lets AmneziaWG replies in.
networking.firewall = {
allowedTCPPorts = forward internal.firewall.allowedTCPPorts;
allowedUDPPorts = forward internal.firewall.allowedUDPPorts;
};
})
];
}
+217
View File
@@ -0,0 +1,217 @@
# Renders the core's systemd-shaped units into a user manager's INI sections
# ({ Unit, Service, Install }), with what only NixOS's unit options provide spelled out:
# the directories systemd would create and the PATH NixOS would set. runtimeDir and
# stateDir are the bases of RuntimeDirectory= and StateDirectory= (specifiers allowed);
# hostPath ends every PATH, for the host's own setuid binaries.
{
lib,
pkgs,
runtimeDir,
stateDir,
hostPath ? null,
}:
let
# The user manager has none of the system targets; the default target stands in for
# multi-user.target.
systemTargets = [
"network.target"
"network-online.target"
"nss-lookup.target"
"sysinit.target"
];
userTargets = {
"multi-user.target" = "default.target";
};
toUserUnits =
units: lib.unique (map (unit: userTargets.${unit} or unit) (lib.subtractLists systemTargets units));
# Identity, capabilities and sandboxing: a user manager can apply them only partly
# (and ProtectHome would hide the state directory), and the core sets none of them
# for a rootless host itself.
systemOnlyKeys = [
"User"
"Group"
"DynamicUser"
"SupplementaryGroups"
"AmbientCapabilities"
"CapabilityBoundingSet"
"PrivateTmp"
"PrivateDevices"
"ProtectSystem"
"ProtectHome"
"ProtectClock"
"ProtectHostname"
"ProtectKernelModules"
"ProtectKernelLogs"
"ProtectKernelTunables"
"ProtectControlGroups"
"RestrictSUIDSGID"
"RestrictRealtime"
"LockPersonality"
"ReadWritePaths"
"ReadOnlyPaths"
# Rendered below against runtimeDir and stateDir: a user manager resolves them
# against XDG directories, which need not be where the core looks.
"RuntimeDirectory"
"RuntimeDirectoryMode"
"StateDirectory"
"StateDirectoryMode"
];
# home-manager takes plain values only.
iniValue =
value:
if lib.isList value then
map iniValue value
else if lib.isBool value || lib.isInt value then
value
else
toString value;
iniSection = section: lib.mapAttrs (_: iniValue) (lib.filterAttrs (_: v: v != null) section);
# As NixOS's service `path` default.
defaultPath = with pkgs; [
coreutils
findutils
gnugrep
gnused
systemd
];
# As NixOS: "@" is not allowed in a store path name.
jobScript =
name: text: pkgs.writeShellScript (lib.replaceStrings [ "@" ] [ "_" ] name) "set -e\n${text}";
dirsScript = pkgs.writeShellScript "proxy-suite-dirs" ''
while (( $# )); do
${pkgs.coreutils}/bin/install -d -m "$1" -- "$2"
shift 2
done
'';
removeDirsScript = pkgs.writeShellScript "proxy-suite-remove-dirs" ''
${pkgs.coreutils}/bin/rm -rf -- "$@"
'';
directories =
serviceConfig: key: base:
map (dir: {
path = "${base}/${dir}";
mode = serviceConfig."${key}Mode" or "0755";
}) (lib.concatMap (lib.splitString " ") (lib.toList (serviceConfig.${key} or [ ])));
unitSection =
unit:
iniSection (
{
Description = unit.description;
}
// lib.filterAttrs (_: v: v != [ ]) {
After = toUserUnits unit.after;
Before = toUserUnits unit.before;
Wants = toUserUnits unit.wants;
Requires = toUserUnits unit.requires;
BindsTo = toUserUnits unit.bindsTo;
PartOf = toUserUnits unit.partOf;
Conflicts = toUserUnits unit.conflicts;
}
// lib.optionalAttrs (unit.startLimitIntervalSec != null) {
StartLimitIntervalSec = unit.startLimitIntervalSec;
}
// unit.unitConfig
);
installSection =
unit:
lib.filterAttrs (_: v: v != [ ]) {
WantedBy = toUserUnits unit.wantedBy;
RequiredBy = toUserUnits unit.requiredBy;
};
withInstall =
unit: attrs:
attrs
// lib.optionalAttrs (installSection unit != { }) {
Install = installSection unit;
};
toService =
name: unit:
let
sc = unit.serviceConfig;
runtimeDirs = directories sc "RuntimeDirectory" runtimeDir;
stateDirs = directories sc "StateDirectory" stateDir;
dirs = runtimeDirs ++ stateDirs;
joinPaths = ds: lib.concatMapStringsSep ":" (d: d.path) ds;
# Paths go on the command line, where systemd expands specifiers such as %t.
commandLine =
script: args: lib.concatStringsSep " " ([ "${script}" ] ++ map (arg: ''"${arg}"'') args);
makeDirs = commandLine dirsScript (
lib.concatMap (d: [
d.mode
d.path
]) dirs
);
removeRuntimeDirs = commandLine removeDirsScript (map (d: d.path) runtimeDirs);
path = unit.path ++ defaultPath;
environment = {
PATH = lib.concatStringsSep ":" (
[
(lib.makeBinPath path)
(lib.makeSearchPathOutput "bin" "sbin" path)
]
++ lib.optional (hostPath != null) hostPath
);
}
// lib.optionalAttrs (runtimeDirs != [ ]) { RUNTIME_DIRECTORY = joinPaths runtimeDirs; }
// lib.optionalAttrs (stateDirs != [ ]) { STATE_DIRECTORY = joinPaths stateDirs; }
// lib.filterAttrs (_: v: v != null) unit.environment;
optionalScript = suffix: text: lib.optional (text != "") (jobScript "${name}-${suffix}" text);
in
withInstall unit {
Unit = unitSection unit;
Service = iniSection (
builtins.removeAttrs sc systemOnlyKeys
// lib.optionalAttrs (sc ? WorkingDirectory && !lib.hasPrefix "-" sc.WorkingDirectory) {
# Created by the first ExecStartPre, which already runs in it.
WorkingDirectory = "-${sc.WorkingDirectory}";
}
// lib.filterAttrs (_: v: v != [ ]) {
Environment =
lib.mapAttrsToList (n: v: builtins.toJSON "${n}=${toString v}") environment
++ lib.toList (sc.Environment or [ ]);
ExecStartPre =
lib.optional (dirs != [ ]) makeDirs
++ optionalScript "pre-start" unit.preStart
++ lib.toList (sc.ExecStartPre or [ ]);
ExecStart = optionalScript "start" unit.script ++ lib.toList (sc.ExecStart or [ ]);
ExecStartPost = optionalScript "post-start" unit.postStart ++ lib.toList (sc.ExecStartPost or [ ]);
ExecStop = optionalScript "pre-stop" unit.preStop ++ lib.toList (sc.ExecStop or [ ]);
ExecStopPost =
optionalScript "post-stop" unit.postStop
++ lib.toList (sc.ExecStopPost or [ ])
++ lib.optional (runtimeDirs != [ ]) removeRuntimeDirs;
}
);
};
toTimer =
_: unit:
withInstall unit {
Unit = unitSection unit;
Timer = iniSection unit.timerConfig;
};
toPath =
_: unit:
withInstall unit {
Unit = unitSection unit;
Path = iniSection unit.pathConfig;
};
in
{
inherit toService toTimer toPath;
}
+11 -1
View File
@@ -30,9 +30,19 @@ in
description = "AWG 3.1 userspace implementation used when the kernel interface is unavailable.";
};
wireproxyPackage = mkOption {
type = types.package;
default = awgPackages.wireproxy;
description = "wireproxy build with AWG 3.1 and FwMark, which runs profiles with asOutbound = \"userspace\".";
};
kernelModulePackage = mkOption {
type = types.nullOr types.package;
default = awgPackages.kernelModule config.boot.kernelPackages;
default =
let
kernelPackages = config.services.proxy-suite.host.kernelPackages;
in
if kernelPackages == null then null else awgPackages.kernelModule kernelPackages;
description = "AWG 3.1 kernel module package. Set null to use userspace-only fallback.";
};
+1
View File
@@ -21,6 +21,7 @@
./tray.nix
./tui.nix
./user-control.nix
./host.nix
];
options.services.proxy-suite.enable = lib.mkEnableOption "proxy-suite";
+74
View File
@@ -0,0 +1,74 @@
# What the host adapter (modules/proxy-suite/hosts/*.nix) tells the core about the
# host, and what the core hands back for the adapter to turn into host settings.
# Nothing here is user-facing.
{ lib, pkgs, ... }:
let
inherit (lib) mkOption types;
unitType = import ./types/unit.nix { inherit lib; };
internalOption =
type: default:
mkOption {
inherit type default;
internal = true;
visible = false;
};
units = internalOption (types.attrsOf unitType) { };
in
{
options.services.proxy-suite.host = {
kind = internalOption (types.enum [
"nixos"
"system-manager"
"home-manager"
"nix-on-droid"
]) "nixos";
# Whether the services run as root and may program routing, firewalls and interfaces.
privileged = internalOption types.bool true;
# Persistent state; units name the proxy-suite subdirectory of their host's state dir.
stateDir = internalOption types.str "/var/lib/proxy-suite";
# Parent of the per-unit runtime directories (proxy-suite-socks, …).
runtimeDir = internalOption types.str "/run";
# Which manager runs the units: proxy-ctl and the control scripts talk to it.
serviceManager = internalOption (types.enum [
"systemd"
"systemd-user"
"supervisor"
]) "systemd";
# The commands that manage the units and show their logs, without a --user of their own.
systemctl = internalOption types.str "${pkgs.systemd}/bin/systemctl";
journalctl = internalOption types.str "journalctl";
# Host facts a few option defaults read.
enableIPv6 = internalOption types.bool true;
kernelPackages = internalOption (types.nullOr types.raw) null;
firewallPackage = internalOption (types.nullOr types.package) null;
resolvconfPackage = internalOption (types.nullOr types.package) null;
};
options.services.proxy-suite.internal = {
# systemd-shaped unit declarations; the adapter installs or converts them.
services = units;
userServices = units;
timers = units;
paths = units;
tmpfiles = internalOption (types.listOf types.str) [ ];
packages = internalOption (types.listOf types.package) [ ];
# Ahead of the host's own packages (zapret's binaries shadow same-named ones).
earlyPackages = internalOption (types.listOf types.package) [ ];
systemUsers = internalOption (types.listOf types.str) [ ];
groups = internalOption (types.listOf types.str) [ ];
polkit = {
enable = internalOption types.bool false;
pkexecWrapper = internalOption types.bool false;
rules = internalOption types.lines "";
};
nftables = internalOption types.bool false;
firewall = {
allowedTCPPorts = internalOption (types.listOf types.port) [ ];
allowedUDPPorts = internalOption (types.listOf types.port) [ ];
extraReversePathFilterRules = internalOption types.lines "";
};
kernelModulePackages = internalOption (types.listOf types.package) [ ];
};
}
+1 -1
View File
@@ -49,7 +49,7 @@ in
ipv6 = mkOption {
type = types.bool;
default = config.networking.enableIPv6;
default = config.services.proxy-suite.host.enableIPv6;
defaultText = literalExpression "config.networking.enableIPv6";
description = ''
Carry IPv6 in the transparent modes: TProxy through a second listener on ::1, the TUNs
@@ -273,6 +273,7 @@ let
type = types.nullOr (
types.enum [
"singBox"
"userspace"
"interface"
]
);
@@ -283,6 +284,11 @@ let
`proxy-ctl awg`. Requires proxy.enable.
- "singBox": a WireGuard endpoint in its own sing-box process, reached as a loopback SOCKS
hop. sing-box speaks plain WireGuard: AmneziaWG obfuscation is dropped with a warning.
- "userspace": the same hop served by wireproxy on AmneziaWG's userspace implementation, so
obfuscation works. It needs no interface or root: the only AmneziaWG mode on
home-manager and nix-on-droid. A declared or profile ListenPort is used as is. An
Endpoint hostname resolves through the system resolver: give an address where that
resolver cannot reach the name.
- "interface": the AmneziaWG interface comes up without routes (Table = off), and the
outbound binds to it, so obfuscation works. With the sing-box backend its DNS goes
through the interface too (proxy.dns.remote); XRay resolves as usual.
@@ -0,0 +1,84 @@
# The subset of NixOS's systemd unit options proxy-suite declares units with, merged
# the same way, so hosts without NixOS's systemd module can read them back.
{ lib }:
let
inherit (lib) mkOption types;
# As nixos/lib/systemd-lib.nix: lists concatenate, anything else must agree.
unitOption = lib.mkOptionType {
name = "systemd option";
merge =
loc: defs:
let
defs' = lib.filterOverrides defs;
in
if lib.any (def: lib.isList def.value) defs' then
lib.concatMap (def: lib.toList def.value) defs'
else
lib.mergeEqualOption loc defs';
};
list = mkOption {
type = types.listOf types.str;
default = [ ];
};
lines = mkOption {
type = types.lines;
default = "";
};
section = mkOption {
type = types.attrsOf unitOption;
default = { };
};
in
types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = true;
};
description = mkOption {
type = types.str;
default = "";
};
after = list;
before = list;
wants = list;
requires = list;
bindsTo = list;
partOf = list;
conflicts = list;
wantedBy = list;
requiredBy = list;
path = mkOption {
type = types.listOf (types.either types.package types.str);
default = [ ];
};
environment = mkOption {
type = types.attrsOf (
types.nullOr (
types.oneOf [
types.str
types.path
types.package
]
)
);
default = { };
};
script = lines;
preStart = lines;
postStart = lines;
preStop = lines;
postStop = lines;
startLimitIntervalSec = mkOption {
type = types.nullOr types.int;
default = null;
};
unitConfig = section;
serviceConfig = section;
timerConfig = section;
pathConfig = section;
};
}
+3
View File
@@ -39,6 +39,7 @@ in
type = types.nullOr (
types.enum [
"singBox"
"userspace"
"interface"
]
);
@@ -49,6 +50,8 @@ in
endpoint on 127.0.0.1:18538, as the proxy-suite-daemon user. The tunnel starts again on a
new source port when WARP does not answer within 15 seconds of a start, or misses three
probes later on, unless the uplink itself is down.
- "userspace": an AmneziaWG profile named "warp" with asOutbound = "userspace", which honours
the AmneziaWG lines of the profile without an interface or root. Requires amneziaWg.enable.
- "interface": an AmneziaWG profile named "warp" with asOutbound = "interface", which honours
the AmneziaWG lines of the profile. Requires amneziaWg.enable.
'';
+64 -4
View File
@@ -71,7 +71,66 @@ let
++ lib.concatMap (ob: [
ob.tunnelPort
ob.directPort
]) (builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds);
]) derived.awgTunnelOutbounds;
# A rootless host (home-manager, nix-on-droid) runs everything as the user: nothing
# that programs routing, firewalls or interfaces, and no privileged ports.
rootless = !constants.privileged;
hostKind = cfg.host.kind;
rootlessForbids =
used: feature:
mkAssertion (
!(rootless && used)
) "proxy-suite: ${feature} needs root, which services on a ${hostKind} host do not have";
rootlessPorts =
lib.optional proxyEnabled {
name = "proxy.listener.port";
port = proxyCfg.listener.port;
}
++ lib.optional tgWsProxyCfg.enable {
name = "tgWsProxy.listener.port";
port = tgWsProxyCfg.listener.port;
}
++ lib.optional cfg.sshProxy.enable {
name = "sshProxy.listener.port";
port = cfg.sshProxy.listener.port;
}
++ lib.optionals cfg.inbounds.enable (
lib.mapAttrsToList (name: listener: {
name = "inbounds.listeners.${name}.port";
inherit (listener) port;
}) cfg.inbounds.listeners
);
rootlessAssertions = [
(rootlessForbids (proxyEnabled && globalTun.enable) "proxy.tun")
(rootlessForbids (proxyEnabled && globalTproxy.enable) "proxy.tproxy")
(rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTun.enable) "perAppRouting.tun")
(rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTproxy.enable) "perAppRouting.tproxy")
(rootlessForbids perAppZapretCfg.enable "perAppRouting.zapret")
(rootlessForbids zapretCfg.enable "zapret")
(rootlessForbids (
derived.awgGlobalProfiles != { } || derived.awgInterfaceOutbounds != [ ]
) ''an AmneziaWG interface (a global profile, or asOutbound = "interface"; use "userspace")'')
(mkAssertion (!(rootless && cfg.userControl.enable))
"proxy-suite: userControl has nothing to grant on a ${hostKind} host, whose services already belong to the user"
)
(mkAssertion
(
!(
rootless
&& cfg.sshProxy.enable
&& cfg.sshProxy.serviceUser != null
&& cfg.sshProxy.serviceUser != constants.serviceUser
)
)
"proxy-suite: sshProxy.serviceUser cannot switch users on a ${hostKind} host; leave it at its default"
)
]
++ map (
item:
mkAssertion (!(rootless && item.port < 1024))
"proxy-suite: ${item.name} = ${toString item.port} is a privileged port, which services on a ${hostKind} host cannot bind; pick one from 1024 up"
) rootlessPorts;
featureAssertions = [
# Declaring no outbound at all is legal: they can be added at runtime with
@@ -108,8 +167,8 @@ let
"proxy-suite: warp.asOutbound requires proxy.enable = true"
)
(requireEnabled (
cfg.warp.enable && cfg.warp.asOutbound == "interface"
) cfg.amneziaWg.enable ''proxy-suite: warp.asOutbound = "interface" requires amneziaWg.enable = true'')
cfg.warp.enable && builtins.elem cfg.warp.asOutbound [ "userspace" "interface" ]
) cfg.amneziaWg.enable ''proxy-suite: warp.asOutbound = "${toString cfg.warp.asOutbound}" requires amneziaWg.enable = true'')
(requireEnabled (
cfg.warp.enable && cfg.warp.asAmneziaWg
) cfg.amneziaWg.enable "proxy-suite: warp.asAmneziaWg requires amneziaWg.enable = true")
@@ -730,7 +789,8 @@ let
}
];
in
featureAssertions
rootlessAssertions
++ featureAssertions
++ perAppRoutingAssertions
++ localProxyAuthAssertions
++ secretAssertions
@@ -12,10 +12,10 @@
mkSubscriptionFetchBlock,
runtimeSubscriptionsFetchBlock,
jq,
systemctl,
}:
let
systemctl = "${pkgs.systemd}/bin/systemctl";
curl = "${pkgs.curl}/bin/curl";
restartActiveBlock = lib.concatMapStrings (svc: ''
+3
View File
@@ -63,6 +63,9 @@
if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl;
autoProxyEnabled = if proxyCfg.autoProxy.enable then "1" else "0";
autoProxyStateDir = constants.autoProxyStateDir;
inherit (constants) stateDir runtimeDir serviceManager;
privileged = if constants.privileged then "1" else "0";
supervisorCtl = if constants.serviceManager == "supervisor" then constants.systemctl else "";
singBox = "${singBoxCfg.package}/bin/sing-box";
localProxyUrl = "http://${
if proxyCfg.listener.address == "0.0.0.0" then "127.0.0.1" else proxyCfg.listener.address
+92 -98
View File
@@ -1,7 +1,6 @@
# Assembles proxy-suite systemd services from the sub-modules.
# Assembles proxy-suite services from the sub-modules, as host-neutral declarations
# under services.proxy-suite.internal (see ../hosts).
{
config,
options,
lib,
pkgs,
packages,
@@ -130,60 +129,51 @@ let
import ../autoproxy.nix {
inherit lib pkgs cfg;
inherit (control) proxyCtl;
inherit (constants) autoProxyStateDir;
inherit (constants) autoProxyStateDir runtimeDir journalctl;
inherit userControlAllows;
}
);
in
lib.mkMerge [
autoProxyUnits
# The GUI's pkexec needs its setuid wrapper, off by default since nixpkgs 26.11 (and
# always there before, where the option does not exist).
(lib.optionalAttrs (options.security.polkit ? enablePkexecWrapper) {
security.polkit.enablePkexecWrapper = lib.mkIf (cfg.enable && cfg.gui.enable) true;
})
{
# See constants.serviceUser.
users.users.${constants.serviceUser} = {
isSystemUser = true;
group = constants.serviceUser;
description = "proxy-suite daemons";
};
users.groups.${constants.serviceUser} = { };
}
{
environment.systemPackages = [
control.proxyCtl
]
++ lib.optional cfg.tui.enable control.proxyCtl.tui
++ lib.optional cfg.gui.enable control.proxyCtl.gui;
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 ];
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
networking.nftables.enable = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) (lib.mkDefault true);
packages = [
control.proxyCtl
]
++ lib.optional cfg.tui.enable control.proxyCtl.tui
++ lib.optional cfg.gui.enable control.proxyCtl.gui;
# Inbound listeners are reached from outside, so their ports have to be open.
networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
nftables = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) true;
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
"${userControlCfg.group}" = { };
};
# Inbound listeners are reached from outside, so their ports have to be open.
firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
security.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.
security.polkit.extraConfig = lib.mkMerge [
(lib.mkIf (cfg.enable && cfg.gui.enable) (
lib.mkAfter ''
groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) [
userControlCfg.group
];
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.
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") {
@@ -191,10 +181,8 @@ lib.mkMerge [
}
return null;
});
''
))
(lib.mkIf (cfg.enable && userControlEnabled) (
lib.mkAfter ''
'')
(lib.mkIf (cfg.enable && userControlEnabled) ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) {
return null;
@@ -209,50 +197,60 @@ lib.mkMerge [
return null;
});
''
))
];
'')
];
# Spool dirs for outbounds and subscriptions added at runtime. Setgid so the
# files proxy-ctl drops here inherit the group; without the outbounds scope
# only root writes them. tmpfiles rather than the start scripts, so the group can add an
# outbound before the proxy has ever run.
systemd.tmpfiles.rules = lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlAllows "outbounds" then "2770 root ${userControlCfg.group}" else "0700 root root"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
);
# Spool dirs for outbounds and subscriptions added at runtime. Setgid so the
# files proxy-ctl drops here inherit the group; without the outbounds scope
# only root writes them. tmpfiles rather than the start scripts, so the group can add an
# outbound before the proxy has ever run.
tmpfiles = lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlAllows "outbounds" then
"2770 root ${userControlCfg.group}"
else if constants.privileged then
"0700 root root"
else
"0700 - -"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
);
systemd.user.services = lib.mkMerge [
(mkNamedUnits userServiceEntries)
(lib.mkIf (cfg.gui.enable && cfg.gui.autostart) {
# Starts hidden in the tray with every graphical session.
proxy-suite-gui = {
description = "Proxy Suite GUI (tray icon)";
wantedBy = [ "graphical-session.target" ];
partOf = [ "graphical-session.target" ];
after = [ "graphical-session.target" ];
unitConfig.ConditionEnvironment = [
"|WAYLAND_DISPLAY"
"|DISPLAY"
];
serviceConfig = {
ExecStart = "${control.proxyCtl.gui}/bin/proxy-suite-gui --hidden";
Restart = "on-failure";
RestartSec = 3;
userServices = lib.mkMerge [
(mkNamedUnits userServiceEntries)
(lib.mkIf (cfg.gui.enable && cfg.gui.autostart) {
# Starts hidden in the tray with every graphical session.
proxy-suite-gui = {
description = "Proxy Suite GUI (tray icon)";
wantedBy = [ "graphical-session.target" ];
partOf = [ "graphical-session.target" ];
after = [ "graphical-session.target" ];
unitConfig.ConditionEnvironment = [
"|WAYLAND_DISPLAY"
"|DISPLAY"
];
serviceConfig = {
ExecStart = "${control.proxyCtl.gui}/bin/proxy-suite-gui --hidden";
Restart = "on-failure";
RestartSec = 3;
};
};
};
})
];
})
];
services = mkNamedUnits systemServiceEntries;
timers = mkNamedUnits timerEntries;
};
}
{
assertions = import ../service-assertions.nix {
inherit lib cfg derived;
tgWsProxyCfg = cfg.tgWsProxy;
@@ -276,10 +274,6 @@ 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`"
);
systemd.services = mkNamedUnits systemServiceEntries;
systemd.timers = mkNamedUnits timerEntries;
}
# A certificate or key XRay cannot read is copied in at start (proxy-inbounds-scripts.nix),
@@ -298,20 +292,20 @@ lib.mkMerge [
);
in
lib.mkIf (cfg.enable && proxyInboundsEnabled && certFiles != [ ]) {
systemd.paths.proxy-suite-inbounds-certs = {
services.proxy-suite.internal.paths.proxy-suite-inbounds-certs = {
description = "proxy-suite - watch the inbounds' TLS certificates for renewals";
wantedBy = [ "paths.target" ];
pathConfig.PathChanged = certFiles;
};
systemd.services.proxy-suite-inbounds-certs = {
services.proxy-suite.internal.services.proxy-suite-inbounds-certs = {
description = "proxy-suite - restart the inbounds onto a renewed certificate";
serviceConfig.Type = "oneshot";
script = ''
# XRay reloads the files it reads itself; only copies go stale.
[ -d /run/proxy-suite-inbounds/tls ] || exit 0
[ -d ${constants.runtimeDir}/proxy-suite-inbounds/tls ] || exit 0
# A renewal writes the chain and the key one after the other.
sleep 10
${pkgs.systemd}/bin/systemctl try-restart proxy-suite-inbounds.service
${constants.systemctl} try-restart proxy-suite-inbounds.service
'';
};
}
@@ -32,6 +32,7 @@ let
perAppZapretSliceName = "proxy-suite-per-app-zapret.slice";
profiles = import ./per-app-routing/profiles.nix {
inherit (constants) runtimeDir;
inherit
lib
pkgs
@@ -7,6 +7,7 @@
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
runtimeDir,
}:
let
@@ -55,7 +56,7 @@ let
proxychainsConfigFile =
if localProxyAuthEnabled then
"/run/proxy-suite-socks/proxychains.conf"
"${runtimeDir}/proxy-suite-socks/proxychains.conf"
else
pkgs.writeText "proxy-suite-per-app" ''
strict_chain
@@ -24,7 +24,7 @@
}:
let
runtimeDir = "/run/proxy-suite-inbounds";
runtimeDir = "${constants.runtimeDir}/proxy-suite-inbounds";
linksFile = "${runtimeDir}/links.json";
subscriptionsFile = "${runtimeDir}/subscriptions.json";
subsCfg = proxyInboundsCfg.subscriptions;
@@ -108,8 +108,9 @@ let
printf '%s' "$body" > "$SUB_DIR.new/$token"
done
chmod -R u=rwX,g=rX,o= "$SUB_DIR.new"
${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
${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''}
rm -rf "$SUB_DIR"
mv "$SUB_DIR.new" "$SUB_DIR"
${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}"
@@ -163,10 +164,10 @@ let
while IFS= read -r source; do
[ -n "$source" ] || continue
if ! ${runXray} ${pkgs.coreutils}/bin/test -r "$source"; then
[ -d "$CERT_DIR" ] || install -d -m 0750 -g ${constants.serviceUser} "$CERT_DIR"
[ -d "$CERT_DIR" ] || install -d -m 0750 ${constants.ifPrivileged "-g ${constants.serviceUser} "}"$CERT_DIR"
index=$((index + 1))
copy="$CERT_DIR/$index-$(basename "$source")"
install -m 0640 -g ${constants.serviceUser} "$source" "$copy"
install -m 0640 ${constants.ifPrivileged "-g ${constants.serviceUser} "}"$source" "$copy"
echo "proxy-suite: ${constants.serviceUser} cannot read $source; XRay uses a copy until the next restart" >&2
${jq} --arg from "$source" --arg to "$copy" '
(.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile)
@@ -187,7 +188,7 @@ let
''
else
''
${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"''}
chmod 640 "$RUNTIME_DIR/config.json.tmp"
''
}
@@ -25,13 +25,13 @@ lib.optionalString hybridEnabled ''
local batch
batch=$(${jq} -c \
--argjson base "$XRAY_SIDECAR_NEXT_PORT" \
--argjson mark ${toString xraySidecarRoutingMark} '
--argjson mark ${if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark} '
to_entries | map(
($base + .key) as $port
| ("proxy-suite-xray-" + ($port | tostring)) as $auth
| .value.tag as $tag
| {outbound: (.value
| .streamSettings.sockopt.mark = $mark
${lib.optionalString (xraySidecarRoutingMark != null) "| .streamSettings.sockopt.mark = $mark"}
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
inbound: {tag: ($tag + "-inbound"), listen: "127.0.0.1", port: $port, protocol: "socks",
settings: {auth: "password", udp: true, accounts: [{user: $auth, pass: $auth}]}},
@@ -160,7 +160,9 @@ let
}
_proxy_suite_parse_xray_url() {
${parse "--backend xray" " --routing-mark ${toString xraySidecarRoutingMark}"}
${parse "--backend xray" (
lib.optionalString (xraySidecarRoutingMark != null) " --routing-mark ${toString xraySidecarRoutingMark}"
)}
}
''
else
@@ -331,7 +333,7 @@ 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 -g ${constants.serviceUser} ${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY"
install -m 0640 ${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}
@@ -357,7 +359,7 @@ let
_proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source}
'';
# WARP and "singBox" AmneziaWG profiles run in a tunnel unit, which restarts them when the
# 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.
mkTunnelOutboundBlock =
unit: source: tag: port:
@@ -10,6 +10,7 @@
hybridEnabled,
mainBackend,
backend,
stateDir,
runtimeSubscriptionsDir,
jq,
python3,
@@ -21,7 +22,7 @@
let
subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend;
subscriptionBackendArg = "--backend ${subscriptionBackend}";
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
subscriptionCacheDir = "${stateDir}/subscriptions/${backend}";
mkSubscriptionUrlSource =
sub:
+6 -4
View File
@@ -56,7 +56,7 @@ let
pkgs.writeText "proxy-suite-core" localProxyAuth.password
else
null;
routeModeStateFile = "/run/proxy-suite/route-mode";
routeModeStateFile = "${constants.runtimeDir}/proxy-suite/route-mode";
inherit (constants)
pinnedOutboundFile
runtimeOutboundsDir
@@ -64,9 +64,9 @@ let
outboundInventoryFile
;
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = globalTproxy.proxyMark;
xrayLoglevelFile = "${constants.runtimeDir}/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "${constants.runtimeDir}/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = if constants.privileged then globalTproxy.proxyMark else null;
routingMarkJq =
routingMark:
@@ -78,6 +78,7 @@ let
" | .routing_mark = ${toString routingMark}";
subscriptionScripts = import ./script-blocks/subscriptions.nix {
inherit (constants) stateDir;
inherit
lib
pkgs
@@ -220,6 +221,7 @@ let
proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile;
controlScripts = import ./control-scripts.nix {
inherit (constants) systemctl;
inherit
lib
pkgs
+10 -9
View File
@@ -42,7 +42,7 @@ let
autoProxyRender = import ../autoproxy-render.nix {
inherit pkgs;
inherit (constants) serviceUser;
inherit (constants) serviceUser ifPrivileged;
};
runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
userControlGroup = lib.escapeShellArg userControlCfg.group;
@@ -136,7 +136,7 @@ let
${lib.escapeShellArg localProxyAuth.username} \
"$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}"
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"''}
chmod 640 "${runtimeProxychainsConfig}"
'';
@@ -258,7 +258,7 @@ let
${
if userControlCfg.enable || localProxyAuthEnabled then
''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP"
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP"''}
chmod 640 "$ENDPOINTS_TMP"
''
else
@@ -358,14 +358,14 @@ let
''
else
''
${chgrp} ${constants.serviceUser} "$backend_config"
${constants.ifPrivileged ''${chgrp} ${constants.serviceUser} "$backend_config"''}
chmod 640 "$backend_config"
''
}
done
FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json")
if [ -n "$FAKE_IP_CACHE" ]; then
install -d -m 0700 -o ${constants.serviceUser} -g ${constants.serviceUser} "$(dirname "$FAKE_IP_CACHE")"
install -d -m 0700 ${constants.ifPrivileged "-o ${constants.serviceUser} -g ${constants.serviceUser} "}"$(dirname "$FAKE_IP_CACHE")"
fi
${
@@ -409,9 +409,10 @@ let
'';
startSocks = mkStartScript {
runtimeDir = "/run/proxy-suite-socks";
runtimeDir = "${constants.runtimeDir}/proxy-suite-socks";
configFile = tproxyFile;
routingMark = globalTproxy.proxyMark;
# Rootless hosts cannot set SO_MARK, and have no TProxy rules to escape anyway.
routingMark = if constants.privileged then globalTproxy.proxyMark else null;
enableLocalProxyAuth = localProxyAuthEnabled;
# TProxy takes the system resolver's own upstream queries too, so a proxy server's name
# has to resolve inside XRay, as under the TUN.
@@ -425,7 +426,7 @@ let
};
startTun = mkStartScript {
runtimeDir = "/run/proxy-suite-tun";
runtimeDir = "${constants.runtimeDir}/proxy-suite-tun";
configFile = tunFile;
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
xrayTunDnsRuntime = pureXrayEnabled;
@@ -436,7 +437,7 @@ let
};
startPerAppTun = mkStartScript {
runtimeDir = "/run/proxy-suite-per-app-tun";
runtimeDir = "${constants.runtimeDir}/proxy-suite-per-app-tun";
configFile = perAppTunFile;
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunDnsRuntime = pureXrayEnabled;
+1 -1
View File
@@ -40,7 +40,7 @@ let
'';
in
{
systemd.services.proxy-suite-ssh-proxy = {
services.proxy-suite.internal.services.proxy-suite-ssh-proxy = {
description = "SSH dynamic SOCKS5 proxy";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
+1 -1
View File
@@ -88,7 +88,7 @@ in
# For the checks: ExecStartPre/ExecStopPost carry these behind "+".
inherit bypassUpScript bypassDownScript;
config.systemd.services.proxy-suite-tg-ws-proxy = {
config.services.proxy-suite.internal.services.proxy-suite-tg-ws-proxy = {
description = "Telegram MTProto WebSocket proxy";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
+9 -5
View File
@@ -86,16 +86,20 @@ let
'';
inherit (import ./wg-tunnel.nix { inherit lib pkgs cfg derived; }) mkTunnel;
viaAmneziaWg = builtins.elem w.asOutbound [
"userspace"
"interface"
];
in
{
services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") {
services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) {
warp = {
configFile = w.profilePath;
asOutbound = lib.mkIf (w.asOutbound == "interface") "interface";
asOutbound = lib.mkIf viaAmneziaWg w.asOutbound;
};
};
systemd.services = lib.mkMerge [
services.proxy-suite.internal.services = lib.mkMerge [
(lib.mkIf (w.asOutbound == "singBox") {
proxy-suite-warp-tunnel = mkTunnel {
description = "proxy-suite - Cloudflare WARP tunnel behind the warp outbound";
@@ -129,7 +133,7 @@ in
RestartSec = 30;
StateDirectory = "proxy-suite/warp";
StateDirectoryMode = "0700";
WorkingDirectory = "/var/lib/proxy-suite/warp";
WorkingDirectory = "${derived.constants.stateDir}/warp";
UMask = "0077";
LoadCredential = lib.optional (cfg.proxy.enable && withProxyAuth) "proxy-password:${passwordSource}";
ExecStart = registerScript;
@@ -137,7 +141,7 @@ in
};
# Only pulls registration in: a simple unit gives the profile no ordering guarantee.
proxy-suite-awg-warp = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") {
proxy-suite-awg-warp = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) {
wants = [ "proxy-suite-warp.service" ];
};
})
+89 -38
View File
@@ -1,6 +1,6 @@
# A WireGuard profile as a sing-box endpoint in its own process, behind a loopback SOCKS
# listener the proxy outbound dials: the WARP tunnel and AmneziaWG profiles with
# asOutbound = "singBox".
# A WireGuard profile in its own process, behind a loopback SOCKS listener the proxy
# outbound dials: the WARP tunnel and AmneziaWG profiles with asOutbound = "singBox"
# (a sing-box endpoint) or "userspace" (wireproxy, which keeps AmneziaWG's obfuscation).
{
lib,
pkgs,
@@ -9,7 +9,7 @@
}:
let
inherit (derived.constants) serviceUser runAsServiceUser;
inherit (derived.constants) serviceUser runAsServiceUser ifPrivileged;
scriptsDir = builtins.path {
name = "proxy-suite-scripts";
path = ../../scripts;
@@ -24,74 +24,75 @@ let
server = upstream.address;
server_port = upstream.port;
};
mark = cfg.proxy.tproxy.proxyMark;
# Past TUN and TProxy. Setting a mark takes CAP_NET_ADMIN, which a rootless host lacks,
# and has nothing to capture its traffic anyway.
mark = if cfg.host.privileged then cfg.proxy.tproxy.proxyMark else null;
probe = port: url: ''
${pkgs.curl}/bin/curl -s --noproxy "" -x socks5h://127.0.0.1:${toString port} -m "$timeout" \
-o /dev/null ${url}'';
# Some lines drop a share of fresh handshakes for good, and sing-box retries on the same
# source port forever. A new process binds a new port, so the watchdog exits when the peer
# stops answering and systemd starts the tunnel again. A healthy handshake takes a fraction
# of a second, so a start gets 15 seconds; a running tunnel gets three misses. The
# "direct-in" listener reaches Cloudflare through the uplink with the backend's mark (not
# urlTest.url, which is picked to be blocked here): when that fails too, the tunnel could
# not work from a new port either.
# Some lines drop a share of fresh handshakes for good, and both engines retry on the
# same source port forever. A new process binds a new port, so the watchdog exits when
# the peer stops answering and the service manager starts the tunnel again. A healthy
# handshake takes a fraction of a second, so a start gets 15 seconds; a running tunnel
# gets three misses. sing-box's "direct-in" listener reaches Cloudflare through the uplink
# with the backend's mark (not urlTest.url, which is picked to be blocked here): when that
# fails too, the tunnel could not work from a new port either. wireproxy has no such
# listener (directPort = null), so it is restarted either way.
mkWatchdog =
{
tag,
command,
tunnelPort,
directPort,
}:
pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
set -uo pipefail
${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json" &
singbox=$!
${command} &
tunnel=$!
healthy=0
failures=0
uplink_down=0
since=0
while sleep $(( healthy ? 10 : 2 )); do
kill -0 "$singbox" 2>/dev/null || { wait "$singbox"; exit 1; }
kill -0 "$tunnel" 2>/dev/null || { wait "$tunnel"; exit 1; }
timeout=$(( healthy ? 10 : 4 ))
if ${probe tunnelPort "-f ${lib.escapeShellArg cfg.proxy.urlTest.url}"}; then
(( healthy )) || echo "proxy-suite: ${tag} is answering" >&2
healthy=1 failures=0 uplink_down=0
continue
fi
if ! ${probe directPort "https://1.1.1.1/cdn-cgi/trace"}; then
(( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging ${tag}" >&2
uplink_down=1 failures=0 since=$SECONDS
continue
fi
${lib.optionalString (directPort != null) ''
if ! ${probe directPort "https://1.1.1.1/cdn-cgi/trace"}; then
(( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging ${tag}" >&2
uplink_down=1 failures=0 since=$SECONDS
continue
fi
''}
uplink_down=0
if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then
echo "proxy-suite: ${tag} is not answering; restarting the tunnel on a new source port" >&2
kill "$singbox"
wait "$singbox"
kill "$tunnel"
wait "$tunnel"
exit 1
fi
done
'';
# `profile` is a shell snippet, run as root, that sets $profile to the WireGuard .conf.
mkTunnel =
markArg = flag: lib.optionalString (mark != null) " ${flag} ${toString mark}";
# The profile is a secret, so it is converted at start, by root on a privileged host,
# rather than baked into the store; the engine itself runs as ${serviceUser}.
singBoxEngine =
{
description,
unit,
tag,
profile,
tunnelPort,
directPort,
}:
let
tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
set -euo pipefail
${profile}
# The profile is a secret, so it is converted here, as root, rather than baked into
# the store; sing-box itself runs as ${serviceUser}.
endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag} --routing-mark ${toString mark} < "$profile")
{
convert = ''
endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag}${markArg "--routing-mark"} < "$profile")
(umask 027 && ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{
log: {level: "warn"},
dns: {servers: [
@@ -107,12 +108,62 @@ let
{type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString tunnelPort}},
{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString directPort}}
],
outbounds: [{type: "direct", tag: "direct", routing_mark: ${toString mark}}],
outbounds: [{type: "direct", tag: "direct"${
lib.optionalString (mark != null) ", routing_mark: ${toString mark}"
}}],
endpoints: [$ep + {domain_resolver: "local"}]
}' > "$RUNTIME_DIRECTORY/config.json")
${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/config.json"
'';
config = "config.json";
command = ''${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json"'';
inherit directPort;
};
exec ${runAsServiceUser pkgs [ "net_admin" ]} ${mkWatchdog { inherit tag tunnelPort directPort; }}
wireproxyEngine =
{ tunnelPort, ... }:
{
convert = ''
${pkgs.python3}/bin/python3 ${scriptsDir}/amneziawg_config.py --config "$profile" \
--output "$RUNTIME_DIRECTORY/wireproxy.conf" \
--wireproxy 127.0.0.1:${toString tunnelPort}${markArg "--outbound-fwmark"}
'';
config = "wireproxy.conf";
command = ''${cfg.amneziaWg.wireproxyPackage}/bin/wireproxy -c "$RUNTIME_DIRECTORY/wireproxy.conf"'';
directPort = null;
};
# `profile` is a shell snippet, run as root on a privileged host, that sets $profile to
# the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort.
mkTunnel =
{
description,
unit,
tag,
profile,
tunnelPort,
directPort ? null,
engine ? "singBox",
}:
let
chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) {
inherit tag tunnelPort directPort;
};
tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
set -euo pipefail
${profile}
${chosen.convert}
${ifPrivileged ''
${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/${chosen.config}"
${pkgs.coreutils}/bin/chmod g+r "$RUNTIME_DIRECTORY/${chosen.config}"
''}
exec ${runAsServiceUser pkgs [ "net_admin" ]} ${
mkWatchdog {
inherit tag tunnelPort;
inherit (chosen) command directPort;
}
}
'';
in
{
+38 -34
View File
@@ -79,46 +79,50 @@ in
{
assertions = zapretPackages.assertions;
environment.systemPackages = lib.mkBefore (
services.proxy-suite.internal.earlyPackages = (
lib.optionals zapretCfg.enable [ globalZapretPackage ]
++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
);
systemd.services.proxy-suite-zapret = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = zapretCommonPreStart globalZapretPackage;
runtimeDirectory = "proxy-suite-zapret";
execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
extraServiceConfig = {
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = globalZapretEnv;
};
});
services.proxy-suite.internal.services.proxy-suite-zapret =
lib.mkIf zapretCfg.enable
(mkOneshotService {
description = "zapret DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = zapretCommonPreStart globalZapretPackage;
runtimeDirectory = "proxy-suite-zapret";
execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
extraServiceConfig = {
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = globalZapretEnv;
};
});
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
description = "proxy-suite per-app-routing zapret backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = zapretCommonPreStart perAppZapretPackage;
runtimeDirectory = "proxy-suite-per-app-zapret";
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = perAppZapretEnv;
});
services.proxy-suite.internal.services.proxy-suite-per-app-zapret =
lib.mkIf perAppZapretCfg.enable
(mkOneshotService {
description = "proxy-suite per-app-routing zapret backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = zapretCommonPreStart perAppZapretPackage;
runtimeDirectory = "proxy-suite-per-app-zapret";
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = perAppZapretEnv;
});
systemd.services.proxy-suite-zapret-vm-exempt =
services.proxy-suite.internal.services.proxy-suite-zapret-vm-exempt =
lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable)
(
mkOneshotService {
+49 -43
View File
@@ -103,50 +103,56 @@ let
'';
in
{
environment.systemPackages = lib.mkBefore [ runtime.package ];
services.proxy-suite.internal.earlyPackages = [ runtime.package ];
systemd.services.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.service;
systemd.timers.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.timer;
services.proxy-suite.internal.services.proxy-suite-zapret2-cutoff =
lib.mkIf cutoffCfg.enable cutoff.service;
services.proxy-suite.internal.timers.proxy-suite-zapret2-cutoff =
lib.mkIf cutoffCfg.enable cutoff.timer;
systemd.services.proxy-suite-zapret = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret2 DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
extraServiceConfig = {
ExecReload = "${runtime.initScript} restart";
Environment = runtime.mkEnv {
runtime = globalRuntime;
pidDir = "/run/proxy-suite-zapret";
};
};
});
services.proxy-suite.internal.services.proxy-suite-zapret =
lib.mkIf zapretCfg.enable
(mkOneshotService {
description = "zapret2 DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
extraServiceConfig = {
ExecReload = "${runtime.initScript} restart";
Environment = runtime.mkEnv {
runtime = globalRuntime;
pidDir = "/run/proxy-suite-zapret";
};
};
});
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
description = "proxy-suite per-app-routing zapret2 backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
};
});
services.proxy-suite.internal.services.proxy-suite-per-app-zapret =
lib.mkIf perAppZapretCfg.enable
(mkOneshotService {
description = "proxy-suite per-app-routing zapret2 backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
};
});
}