fix: hardening

This commit is contained in:
FUFSoB committed 2026-10-05 22:44:09 +05:00
1 parent 017a947a18
commit a435942b4f
168 files changed
+9166 -1644

No files matched your search

+3
View File
@@ -66,6 +66,9 @@ moduleSuiteChecks
proxy-suite-hosts = builtins.seq (builtins.deepSeq hostChecks.assertions true) (
pkgs.writeText "proxy-suite-hosts-check" "ok"
);
backend-config-validation = import ./checks/backend-config-validation.nix {
inherit pkgs checkLib;
};
proxy-helpers = import ./checks/proxy-helpers.nix {
inherit pkgs;
inherit (checkLib) evalProxySuite;
+3 -2
View File
@@ -158,9 +158,10 @@ in
singBoxStart;
assert hasInfix "_proxy_suite_record_tag_source plain awg" singBoxStart;
assert hasInfix "--output \"$profile\"" plainTunnel && !(hasInfix "--outbound-fwmark" plainTunnel);
assert hasInfix "warp_outbound.py --tag plain --routing-mark 2" plainTunnel;
assert hasInfix "TUNNEL_TAG=plain\n" plainTunnel;
assert hasInfix ''warp_outbound.py --tag "$TUNNEL_TAG" --routing-mark 2'' plainTunnel;
assert hasInfix "listen_port: 18602" plainTunnel;
assert hasInfix ''detour: "plain"'' plainTunnel;
assert hasInfix "detour: $tag" plainTunnel;
assert !(services ? proxy-suite-awg-plain-watchdog);
true
)
+17 -8
View File
@@ -288,11 +288,16 @@ in
assert builtins.elem "proxy-suite-tun.service" homeService.conflicts;
assert builtins.elem "proxy-suite-tproxy.service" homeService.conflicts;
assert builtins.elem "proxy-suite-zapret.service" homeService.conflicts;
assert builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts;
# Per-app zapret never takes a global profile down: the profile stops it as it starts.
assert !(builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts);
assert pkgs.lib.hasInfix "proxy-suite-per-app-zapret.service proxy-suite-awg-app@home.service" (
pkgs.lib.last homeService.serviceConfig.ExecStartPre
);
assert workService.wantedBy == [ ];
assert homeService.serviceConfig.NoNewPrivileges;
# Rendering, then stopping any profile added at runtime: they share an interface.
assert builtins.length homeService.serviceConfig.ExecStartPre == 2;
# Rendering, stopping any profile added at runtime (they share an interface), then
# per-app zapret and the profile's copy for apps.
assert builtins.length homeService.serviceConfig.ExecStartPre == 3;
assert pkgs.lib.hasInfix "proxy-suite-awg@*.service" (
generated.readDerivation (builtins.elemAt homeService.serviceConfig.ExecStartPre 1)
);
@@ -365,11 +370,13 @@ in
withGlobalTun.config.systemd.services.proxy-suite-tproxy.conflicts;
assert builtins.elem "proxy-suite-awg-home.service"
withGlobalTun.config.systemd.services.proxy-suite-zapret.conflicts;
assert builtins.elem "proxy-suite-awg-home.service"
withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts;
assert
!(builtins.elem "proxy-suite-awg-home.service" withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts);
assert builtins.any (pkgs.lib.hasInfix "proxy-suite-awg-home.service")
withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.serviceConfig.ExecStartPre;
assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.after;
assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.wants;
assert builtins.length withGlobalAwgStartPre == 3;
assert builtins.length withGlobalAwgStartPre == 4;
assert pkgs.lib.hasInfix "rule add" withGlobalAwgBypassUp;
assert pkgs.lib.hasInfix "pref 8998" withGlobalAwgBypassUp;
assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassUp;
@@ -385,7 +392,8 @@ in
(
assert runtimeTemplate.wantedBy == [ ];
assert builtins.elem "proxy-suite-awg-watchdog@%i.service" runtimeTemplate.wants;
assert builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.before;
# Not before it: the kill switch comes up ahead of the network these wait for.
assert !builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.before;
assert builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.wants;
assert builtins.elem "proxy-suite-tun.service" runtimeTemplate.conflicts;
assert runtimeTemplate.serviceConfig.Group == "proxy-suite-awg";
@@ -435,9 +443,10 @@ in
assert runtimeCtl.awgProfiles == [ ];
# Declared profiles only in a configuration that turns the runtime ones off.
assert !(awgOnlyNoRuntime.config.systemd.services ? "proxy-suite-awg@");
# Rendering, and taking down the per-app units it carries for.
assert
builtins.length awgOnlyNoRuntime.config.systemd.services.proxy-suite-awg-home.serviceConfig.ExecStartPre
== 1;
== 2;
true
)
]
+115
View File
@@ -0,0 +1,115 @@
# The generated configs through the backends' own checks: `xray run -test` and `sing-box
# check`. Nothing else catches a value a backend refuses (its whole start fails over one
# rule), only the string assertions that pin what we meant to write.
{
pkgs,
checkLib,
}:
let
inherit (checkLib) evalProxySuite mkAssembly baseModule;
inherit (pkgs) lib;
proxy =
backend:
evalProxySuite [
baseModule
{
services.proxy-suite = {
killSwitch.enable = true;
proxy = {
backend = lib.mkForce backend;
selection = "urltest";
tproxy.enable = true;
tun.enable = true;
dns.fakeIp.enable = true;
};
perAppRouting = {
enable = true;
tun.enable = true;
tproxy.enable = true;
};
};
}
];
# Its routing.default "direct" leaves out the proxied DNS bridge, and urltest's balancer.
direct =
backend:
evalProxySuite [
baseModule
{
services.proxy-suite.proxy = {
backend = lib.mkForce backend;
routing.default = "direct";
tproxy.enable = true;
};
}
];
inbounds = evalProxySuite [
baseModule
{
services.proxy-suite.inbounds = {
enable = true;
serverAddress = "vpn.example.com";
users.user.uuidFile = "/run/secrets/uuid";
listeners.vless-in = {
type = "vless";
port = 443;
users = [ "user" ];
reality = {
enable = true;
serverNames = [ "www.microsoft.com" ];
privateKeyFile = "/run/secrets/reality-key";
publicKey = "public-key";
shortIds = [ "0123abcd" ];
};
};
};
}
];
configsOf =
fixture: attrs:
let
configs = (mkAssembly fixture).configs;
in
map (attr: configs.${attr}) (builtins.filter (attr: configs ? ${attr}) attrs);
proxyAttrs = [
"tproxyFile"
"tunFile"
"perAppTunFile"
];
xrayConfigs =
configsOf (proxy "xray") proxyAttrs
++ configsOf (direct "xray") proxyAttrs
++ configsOf inbounds [ "proxyInboundsFile" ];
singBoxConfigs =
configsOf (proxy "sing-box") proxyAttrs ++ configsOf (direct "sing-box") proxyAttrs;
xray = "${(proxy "xray").config.services.proxy-suite.proxy.xray.package}/bin/xray";
singBox = "${(proxy "sing-box").config.services.proxy-suite.proxy.singBox.package}/bin/sing-box";
in
pkgs.runCommand "proxy-suite-backend-config-validation-check" { nativeBuildInputs = [ pkgs.jq ]; }
''
export HOME=$PWD
# The outbounds come at start: one of each kind the rules and balancers name stands in.
for config in ${lib.escapeShellArgs xrayConfigs}; do
jq '.outbounds += [{tag: "proxy-suite-ob-check", protocol: "freedom"}]
| if any(.outbounds[]; .tag == "proxy") or (.routing.balancers // [] | any(.tag == "proxy")) then .
else .outbounds += [{tag: "proxy", protocol: "freedom"}] end' "$config" > config.json
if ! ${xray} run -test -format json -c config.json > log 2>&1; then
echo "xray refuses $config:" >&2
cat log >&2
exit 1
fi
done
for config in ${lib.escapeShellArgs singBoxConfigs}; do
if ! ${singBox} check -c "$config" > log 2>&1; then
echo "sing-box refuses $config:" >&2
cat log >&2
exit 1
fi
done
touch "$out"
''
+101 -20
View File
@@ -41,6 +41,11 @@ let
tproxyLanStartScript
killSwitchFixture
killSwitchNftRules
killSwitchTproxyNftRules
killSwitchUpScript
killSwitchSubscriptionUpdate
tunSubscriptionUpdate
tproxyKillSwitchNftRules
awgKillSwitchFixture
awgKillSwitchNftRules
awgKillSwitchPrepare
@@ -91,12 +96,15 @@ in
pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix needle) null (pkgs.lib.splitString "\n" rules);
in
assert pkgs.lib.hasInfix
''iifname { "br0" } meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:1085 meta mark set 1''
''iifname { "br0" } meta nfproto ipv4 meta l4proto { tcp, udp } meta mark set 1 tproxy ip to 127.0.0.1:1085''
rules;
assert pkgs.lib.hasInfix
''iifname { "br0" } meta nfproto ipv6 meta l4proto { tcp, udp } meta mark set 1 tproxy ip6''
rules;
assert pkgs.lib.hasInfix ''iifname { "br0" } meta l4proto { tcp, udp } tproxy ip6'' rules;
assert at "ip daddr 192.168.0.0/16 tcp dport != 53 return" < at ''iifname { "br0" }'';
assert at ''iifname { "br0" }'' < at "ip saddr $RESERVED_IP return";
assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 accept''
assert !(pkgs.lib.hasInfix "ip saddr" rules);
# Into the backend's transparent socket alone, not any listener while it restarts.
assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 socket transparent 1 accept''
cfg.networking.firewall.extraInputRules;
assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 accept''
cfg.networking.firewall.extraReversePathFilterRules;
@@ -107,30 +115,72 @@ in
assert !(pkgs.lib.hasInfix "sysctl" tproxyManualStartScript);
true
)
# The kill switch: pulled in by both modes, but not stopped with them; it lets the proxy's
# own traffic and its DNS hand-off past, and cuts gateway clients off from the internet.
# The kill switch: up from boot ahead of the network, pulled in again by both modes, and
# not stopped with them; it lets the proxy's own traffic and its DNS hand-off past, and
# cuts gateway clients and containers off from the internet.
(
let
units = killSwitchFixture.config.systemd.services;
ks = units."proxy-suite-killswitch";
rules = killSwitchNftRules;
before =
a: b:
pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix a) null (pkgs.lib.splitString "\n" rules)
< pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix b) null (pkgs.lib.splitString "\n" rules);
lines = pkgs.lib.splitString "\n" rules;
at = needle: pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix needle) null lines;
before = a: b: at a < at b;
in
assert builtins.elem "proxy-suite-killswitch.service" units."proxy-suite-tun".wants;
assert builtins.elem "proxy-suite-killswitch.service" units."proxy-suite-tproxy".wants;
assert !(units."proxy-suite-tun" ? bindsTo) || units."proxy-suite-tun".bindsTo == [ ];
assert !(ks ? partOf) || ks.partOf == [ ];
assert builtins.elem "proxy-suite-tun.service" ks.after;
assert ks.wantedBy == [ ];
assert pkgs.lib.hasInfix ''meta skuid "proxy-suite-daemon" accept'' rules;
assert ks.wantedBy == [ "multi-user.target" ];
assert builtins.elem "network-pre.target" ks.before;
assert builtins.elem "network-pre.target" ks.wants;
assert ks.unitConfig.DefaultDependencies == false;
assert builtins.elem "nftables.service" ks.after;
# Nothing that waits for the network: that would be an ordering cycle.
assert !builtins.elem "proxy-suite-tun.service" ks.after;
assert !builtins.elem "proxy-suite-socks.service" ks.after;
assert pkgs.lib.hasInfix ''meta skuid { "proxy-suite-daemon" } accept'' rules;
assert pkgs.lib.hasInfix "meta mark { 1, 2 } accept" rules;
assert pkgs.lib.hasInfix ''oifname "singtun0" accept'' rules;
assert before "ip daddr 172.19.0.1/30 accept" "th dport 53 reject";
assert before "th dport 53 reject" "ip daddr $RESERVED_IP accept";
assert pkgs.lib.hasInfix ''iifname { "br0" } reject'' rules;
# DHCP and NTP only from privileged ports or the time daemons: no STUN past it.
assert !(pkgs.lib.hasInfix "udp dport { 67, 68, 123 }" rules);
assert pkgs.lib.hasInfix "meta nfproto ipv4 udp sport 68 udp dport 67 accept" rules;
assert pkgs.lib.hasInfix "meta nfproto ipv6 udp sport 546 udp dport 547 accept" rules;
assert pkgs.lib.hasInfix "meta skuid @time_sync_uids udp dport 123 accept" rules;
assert
killSwitchFixture.config.services.proxy-suite.killSwitch.timeSyncUsers == [ "systemd-timesync" ];
assert pkgs.lib.hasInfix "for user in systemd-timesync; do" killSwitchUpScript;
assert pkgs.lib.hasInfix "time_sync_uids {" killSwitchUpScript;
# Forwarded traffic leaves by the TUN or not at all, gateway clients' included.
assert before "chain forward" ''oifname { "singtun0" } accept'';
assert builtins.any (line: pkgs.lib.trim line == "reject with icmpx admin-prohibited") (
pkgs.lib.drop (at "chain forward") lines
);
assert !(pkgs.lib.hasInfix ''iifname { "br0" } reject'' rules);
# Containers' traffic passes while TProxy, which tags it, is up instead of the TUN.
assert before "chain forward" "meta mark and 16777216 != 0 accept";
assert pkgs.lib.hasInfix ''iifname != { "br0" } meta mark set meta mark or 16777216''
killSwitchTproxyNftRules;
# TProxy alone: only the gateway clients are held.
assert pkgs.lib.hasInfix ''iifname { "br0" } reject'' tproxyKillSwitchNftRules;
assert !(pkgs.lib.hasInfix "oifname {" tproxyKillSwitchNftRules);
# Subscriptions are fetched as proxy-suite-fetch, through whatever tunnel is up; only
# when that fails under the kill switch with no cache, as the service user. Without
# the kill switch, never.
assert pkgs.lib.hasInfix ''_proxy_suite_run_fetcher tunnel "$tag"'' killSwitchSubscriptionUpdate;
assert pkgs.lib.hasInfix ''{ true && ! _proxy_suite_valid_subscription_cache "$cache" &&''
killSwitchSubscriptionUpdate;
assert pkgs.lib.hasInfix "fetching it directly, past the kill switch" killSwitchSubscriptionUpdate;
assert pkgs.lib.hasInfix "as=(" killSwitchSubscriptionUpdate;
assert pkgs.lib.hasInfix "setpriv --reuid=proxy-suite-daemon" killSwitchSubscriptionUpdate;
assert pkgs.lib.hasInfix "unshare --mount" killSwitchSubscriptionUpdate;
assert pkgs.lib.hasInfix "--links-fd 3" killSwitchSubscriptionUpdate;
assert pkgs.lib.hasInfix "{ false &&" tunSubscriptionUpdate;
assert !(pkgs.lib.hasInfix "unshare --mount" tunSubscriptionUpdate);
assert !(pkgs.lib.hasInfix "setpriv --reuid=proxy-suite-daemon" tunSubscriptionUpdate);
assert pkgs.lib.hasInfix "setpriv --reuid=proxy-suite-fetch" tunSubscriptionUpdate;
# A switch reloads it: the new rules replace the old in one transaction, never a stop
# that lifts it first.
assert ks.reloadIfChanged;
@@ -148,7 +198,8 @@ in
rules = awgKillSwitchNftRules;
in
assert builtins.elem "proxy-suite-killswitch.service" home.wants;
assert builtins.elem "proxy-suite-awg-home.service" units.proxy-suite-killswitch.after;
assert !builtins.elem "proxy-suite-awg-home.service" units.proxy-suite-killswitch.after;
assert units.proxy-suite-killswitch.wantedBy == [ "multi-user.target" ];
assert !builtins.elem "proxy-suite-killswitch.service" (home.conflicts or [ ]);
assert (units.proxy-suite-killswitch.conflicts or [ ]) == [ ];
assert home.serviceConfig.Group == "proxy-suite-awg";
@@ -159,7 +210,17 @@ in
assert pkgs.lib.hasInfix
''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}", "awg-rt" } accept''
rules;
# Forwarded traffic too, through either.
assert pkgs.lib.hasInfix "chain forward" rules;
assert
builtins.length (
pkgs.lib.splitString ''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}", "awg-rt" } accept'' rules
) == 3;
assert pkgs.lib.hasInfix "meta mark { 1, 2, 51820 } accept" rules;
# killSwitch.allowedSubnets in place of TProxy's localSubnets, out and forwarded.
assert builtins.length (pkgs.lib.splitString "ip6 daddr 2001:db8:1::/64 accept" rules) == 3;
assert !(pkgs.lib.hasInfix "ip daddr 192.168.0.0/16 accept" rules);
assert pkgs.lib.hasInfix "ip daddr 192.168.0.0/16 accept" killSwitchNftRules;
assert !(pkgs.lib.hasInfix "skgid" killSwitchNftRules);
assert !(units.proxy-suite-awg-home-watchdog.serviceConfig ? Group);
true
@@ -176,20 +237,34 @@ in
assert pkgs.lib.hasInfix "-6 rule add fwmark 1 table 100" tproxyManualStartScript;
assert pkgs.lib.hasInfix "-6 rule del fwmark 1 table 100" tproxyManualStopScript;
assert pkgs.lib.hasInfix "table inet singbox" tproxyManualNftRules;
assert pkgs.lib.hasInfix "meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:1085 meta mark set 1"
# Only what the output chain marked, this host's own traffic: a neighbour routing
# through this host is not handed the proxy.
assert pkgs.lib.hasInfix
"meta mark 1 meta nfproto ipv4 meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:1085"
tproxyManualNftRules;
assert pkgs.lib.hasInfix "meta l4proto { tcp, udp } tproxy ip6 to [::1]:1085 meta mark set 1"
assert pkgs.lib.hasInfix
"meta mark 1 meta nfproto ipv6 meta l4proto { tcp, udp } tproxy ip6 to [::1]:1085"
tproxyManualNftRules;
# Marked traffic that leaves anywhere but lo lost its ip rule: dropped, not sent direct.
assert pkgs.lib.hasInfix ''meta mark 1 oifname != { "lo" } drop'' tproxyManualNftRules;
assert
tproxyTags tproxyManualConfig == [
"tproxy-in"
"tproxy-in6"
];
assert !(pkgs.lib.hasInfix "-6 rule add" tproxyIPv4OnlyStartScript);
# IPv4 only: IPv6 is not taken by the proxy, but marked into an unreachable route rather
# than left to go out directly.
assert !(pkgs.lib.hasInfix "-6 route replace local default" tproxyIPv4OnlyStartScript);
assert pkgs.lib.hasInfix "-6 route replace unreachable default table 100" tproxyIPv4OnlyStartScript;
assert pkgs.lib.hasInfix "-6 rule add fwmark 1 table 100" tproxyIPv4OnlyStartScript;
assert pkgs.lib.hasInfix "-6 rule del fwmark 1 table 100" tproxyIPv4OnlyStartScript;
assert !(pkgs.lib.hasInfix "tproxy ip6" tproxyIPv4OnlyNftRules);
assert pkgs.lib.hasInfix "meta nfproto ipv4 meta l4proto { tcp, udp } meta mark set 1"
tproxyIPv4OnlyNftRules;
assert pkgs.lib.hasInfix "meta nfproto ipv6 meta mark set 1" tproxyIPv4OnlyNftRules;
# On-link IPv6 leaves marked by the main table: not dropped as misrouted.
assert pkgs.lib.hasInfix ''meta nfproto ipv4 meta mark 1 oifname != { "lo" } drop''
tproxyIPv4OnlyNftRules;
assert tproxyTags tproxyIPv4OnlyConfig == [ "tproxy-in" ];
true
)
@@ -215,7 +290,9 @@ in
assert !(pkgs.lib.hasInfix "-6 addr replace" ipv4OnlyPerAppTunUpScript);
assert xrayGateway xrayIPv4OnlyTunConfig == [ "172.19.0.1/30" ];
assert !(pkgs.lib.hasInfix "-6 addr replace" xrayIPv4OnlyTunUpScript);
assert !(pkgs.lib.hasInfix "-6 route replace" xrayIPv4OnlyTunUpScript);
# IPv6 only into an unreachable route, as the sing-box and per-app TUNs have it.
assert !(pkgs.lib.hasInfix "-6 route replace default dev" xrayIPv4OnlyTunUpScript);
assert pkgs.lib.hasInfix "-6 route replace unreachable default table" xrayIPv4OnlyTunUpScript;
assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStopScript;
true
)
@@ -235,7 +312,11 @@ in
)
(ok (tunManualFixture.config.networking.nftables.enable))
(
assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost;
# Per-app units it carries for go first (they never take it down), then the clean-up.
assert builtins.elemAt tunServiceConfig.ExecStartPre 1 == tunServiceConfig.ExecStopPost;
assert pkgs.lib.hasInfix "proxy-suite-per-app-tproxy.service" (
builtins.head tunServiceConfig.ExecStartPre
);
assert pkgs.lib.hasInfix "delete table inet sing-box" tunCleanupScript;
assert pkgs.lib.hasInfix "rule del table ${toString checkConstants.tunAutoRouteTableIndex}"
tunCleanupScript;
+26 -2
View File
@@ -42,7 +42,7 @@ let
tproxyManualServiceConfig =
tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig;
tproxyManualStartScript = generated.readDerivation tproxyManualServiceConfig.ExecStart;
tproxyManualStopScript = generated.readDerivation tproxyManualServiceConfig.ExecStop;
tproxyManualStopScript = generated.readDerivation tproxyManualServiceConfig.ExecStopPost;
tproxyManualConfig = mkTProxyConfig tproxyManualFixture;
tproxyManualNftRules = mkTProxyNftRules tproxyManualFixture;
@@ -74,6 +74,22 @@ let
}
];
killSwitchNftRules = mkNftRules killSwitchFixture "killSwitchRulesFile";
killSwitchTproxyNftRules = mkTProxyNftRules killSwitchFixture;
killSwitchUpScript = generated.readDerivation killSwitchFixture.config.systemd.services.proxy-suite-killswitch.serviceConfig.ExecStart;
killSwitchSubscriptionUpdate = generated.readDerivation killSwitchFixture.config.systemd.services.proxy-suite-subscription-update.serviceConfig.ExecStart;
tunSubscriptionUpdate = generated.readDerivation tunManualFixture.config.systemd.services.proxy-suite-subscription-update.serviceConfig.ExecStart;
# TProxy alone diverts no forwarded traffic: only the gateway clients are held to the LAN.
tproxyKillSwitchNftRules = mkNftRules (evalProxySuite [
baseModule
{
services.proxy-suite.killSwitch.enable = true;
services.proxy-suite.proxy.tproxy = {
enable = true;
lanInterfaces = [ "br0" ];
};
}
]) "killSwitchRulesFile";
# A global AmneziaWG profile alone, no proxy.
awgKillSwitchFixture = evalProxySuite [
@@ -81,7 +97,10 @@ let
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
killSwitch.enable = true;
killSwitch = {
enable = true;
allowedSubnets = [ "2001:db8:1::/64" ];
};
amneziaWg = {
enable = true;
kernelModulePackage = null;
@@ -208,6 +227,11 @@ in
tproxyLanStartScript
killSwitchFixture
killSwitchNftRules
killSwitchTproxyNftRules
killSwitchUpScript
killSwitchSubscriptionUpdate
tunSubscriptionUpdate
tproxyKillSwitchNftRules
awgKillSwitchFixture
awgKillSwitchNftRules
awgKillSwitchPrepare
+26 -9
View File
@@ -37,6 +37,7 @@ let
];
guiPackage = ".*/[^/]*proxy-suite-gui(-[0-9.]+)?$";
inherit (import ./read-generated.nix) readDerivation;
in
{
assertions = [
@@ -61,19 +62,35 @@ in
true
)
(
# pkexec of this proxy-ctl, and only it, keeps the admin password for a while.
# pkexec of this proxy-ctl, and only it, keeps the admin password for a while: an action
# of its own, not a rule on org.freedesktop.policykit.exec, whose kept authorization
# would cover any program the GUI ran through pkexec next.
let
rules = guiFixture.config.security.polkit.extraConfig;
cfg = guiFixture.config;
actions = cfg.services.proxy-suite.internal.polkit.actions;
policy = readDerivation actions."io.github.FUFSoB.ProxySuite.proxy-ctl.policy";
proxyCtl = builtins.head (
builtins.filter (p: builtins.match ".*/[^/]*-proxy-ctl$" p != null) (
map (p: builtins.unsafeDiscardStringContext (toString p)) cfg.environment.systemPackages
)
);
has = text: builtins.match ".*${text}.*" (builtins.unsafeDiscardStringContext policy) != null;
in
assert guiFixture.config.security.polkit.enable;
assert cfg.security.polkit.enable;
# nixpkgs 26.11+: no setuid pkexec unless asked for, and without it pkexec refuses to run.
assert cfg.security.wrappers ? pkexec && cfg.security.wrappers.pkexec.enable;
assert
guiFixture.config.security.wrappers ? pkexec && guiFixture.config.security.wrappers.pkexec.enable;
assert
builtins.match ''.*action\.lookup\("program"\) === "/nix/store/[^"]*proxy-ctl/bin/proxy-ctl".*AUTH_ADMIN_KEEP.*'' rules
!= null;
assert
builtins.match ".*AUTH_ADMIN_KEEP.*" tuiOffFixture.config.security.polkit.extraConfig == null;
builtins.match ".*(policykit\\.exec|AUTH_ADMIN_KEEP).*" cfg.security.polkit.extraConfig == null;
# The path the GUI runs proxy-ctl by, which pkexec matches after realpath.
assert has
''<annotate key="org\.freedesktop\.policykit\.exec\.path">${proxyCtl}/bin/proxy-ctl</annotate>'';
# Never kept: a kept grant is the whole session's, and proxy-ctl as root runs commands.
assert has "<allow_active>auth_admin</allow_active>";
assert has "<allow_any>auth_admin</allow_any>";
assert has "<allow_inactive>auth_admin</allow_inactive>";
# Where NixOS's polkitd reads actions: the system profile's share/polkit-1/actions.
assert packagePathMatches cfg.environment.systemPackages ".*-proxy-suite-polkit-actions$";
assert tuiOffFixture.config.services.proxy-suite.internal.polkit.actions == { };
true
)
(
+29
View File
@@ -87,6 +87,7 @@ let
fixture: map (a: a.message) (lib.filter (a: !a.assertion) fixture.config.assertions);
# Through JSON: derivations stop at their store paths, which is where the scripts get built.
forced = value: builtins.isString (builtins.toJSON value);
packageNamed = name: lib.findFirst (p: lib.getName p == name) null;
proxy = {
enable = true;
@@ -238,7 +239,12 @@ in
assert
smCfg.systemd.services.proxy-suite-socks.serviceConfig.SyslogIdentifier == "proxy-suite-socks";
assert smCfg.systemd.services ? proxy-suite-tproxy;
# No NixOS time daemon options to read: the kill switch tries the usual users.
assert builtins.elem "chrony" smCfg.services.proxy-suite.killSwitch.timeSyncUsers;
assert builtins.elem "systemd-timesync" smCfg.services.proxy-suite.killSwitch.timeSyncUsers;
assert smCfg.environment.etc ? "polkit-1/rules.d/50-proxy-suite.rules";
# The GUI's pkexec action, where the distribution's polkit (126+) reads it.
assert smCfg.environment.etc ? "polkit-1/actions/io.github.FUFSoB.ProxySuite.proxy-ctl.policy";
assert smCfg.environment.etc ? "systemd/user/proxy-suite-gui.service";
assert forced smCfg.systemd.services;
true
@@ -257,6 +263,29 @@ in
# Android bans apps from netlink's route groups, which stock sing-box subscribes to.
assert nodCfg.services.proxy-suite.proxy.singBox.package.passthru.rootlessNetlink or false;
assert !(hmCfg.services.proxy-suite.proxy.singBox.package.passthru.rootlessNetlink or false);
# Space on a phone: no systemd (proxy-suitectl stands in), lnav or curl-impersonate.
assert lib.all
(
name:
let
wrapper = (packageNamed name nodCfg.environment.packages).buildCommand;
in
lib.all (dep: !(lib.hasInfix dep wrapper)) [
"-systemd-"
"-lnav-"
"-curl-impersonate-"
]
)
[
"proxy-ctl"
"proxy-tui"
];
# Elsewhere they stay.
assert lib.all (dep: lib.hasInfix dep (packageNamed "proxy-ctl" hmCfg.home.packages).buildCommand) [
"-systemd-"
"-lnav-"
"-curl-impersonate-"
];
true
)
(
+1 -1
View File
@@ -107,7 +107,7 @@ in
# Authenticated mixed inbound is injected at runtime.
(
assert pkgs.lib.hasInfix ''LOCAL_PROXY_PASSWORD="$(cat "'' localProxyAuthStartScript;
assert pkgs.lib.hasInfix ''LOCAL_PROXY_PASSWORD="$(cat '' localProxyAuthStartScript;
assert pkgs.lib.hasInfix "BACKEND_JQ_FILTER=" localProxyAuthStartScript;
assert pkgs.lib.hasInfix ''-f "$BACKEND_JQ_FILTER"'' localProxyAuthStartScript;
assert pkgs.lib.hasInfix "--arg user local-user" localProxyAuthStartScript;
+3
View File
@@ -65,6 +65,8 @@ let
};
inherit (coreProxyChecks) ruDefaultConfig;
optionTypeChecks = import ./option-types.nix { inherit checkLib minimal; };
routeModeChecks = import ./route-mode.nix {
inherit checkLib;
inherit
@@ -342,6 +344,7 @@ let
++ guiChecks.assertions
++ subscriptionChecks.assertions
++ routeModeChecks.assertions
++ optionTypeChecks.assertions
++ perAppRoutingChecks.assertions
++ perAppRoutingAwgChecks.assertions
++ serverModuleChecks.assertions
+112
View File
@@ -0,0 +1,112 @@
# Interface names, addresses and CIDRs go into nft rules and scripts as they are: their
# types must turn away anything that would end the token there.
{ checkLib, minimal }:
let
opts = minimal.options.services.proxy-suite;
elemCheck = option: option.type.nestedTypes.elemType.check;
accepts = check: builtins.all check;
refuses = check: builtins.all (value: !(check value));
injected = [
""
"br0\" accept"
"br0 }"
"br0; flush ruleset"
"$(reboot)"
"eth0 eth1"
"a\nb"
];
in
{
assertions = [
(
let
check = elemCheck opts.proxy.tproxy.lanInterfaces;
in
assert accepts check [
"br0"
"br-lan"
"eth0.100"
"wlp3s0"
"a+b"
"123456789012345"
];
assert refuses check (
injected
++ [
"1234567890123456"
"."
"-x"
"eth*"
]
);
assert refuses opts.proxy.tun.interface.type.check injected;
assert refuses opts.perAppRouting.tun.interface.type.check injected;
true
)
(
let
subnets = [
opts.proxy.tproxy.localSubnets
opts.perAppRouting.tun.localSubnets
opts.perAppRouting.tproxy.localSubnets
opts.perAppRouting.via.localSubnets
opts.zapret.cidrExemption.cidrs
];
in
assert builtins.all (
option:
accepts (elemCheck option) [
"192.168.0.0/16"
"10.1.2.3"
"fd00::/8"
"::1"
"::ffff:10.0.0.1/128"
]
&& refuses (elemCheck option) (
injected
++ [
"10.0.0.0/8 accept"
"10.0.0.0/33"
"256.0.0.0/8"
"fd00::/129"
"example.com"
]
)
) subnets;
true
)
(
assert accepts opts.proxy.tun.address.type.check [ "172.19.0.1/30" ];
assert refuses opts.proxy.tun.address.type.check (
injected
++ [
"172.19.0.1"
"fd00::1/64"
"172.19.0.1/30 accept"
]
);
assert refuses opts.perAppRouting.tun.address.type.check [ "172.20.0.1/30; drop" ];
true
)
(
assert accepts opts.proxy.listener.address.type.check [
"127.0.0.1"
"::"
"localhost"
];
assert refuses opts.proxy.listener.address.type.check injected;
true
)
# A bad value stops the evaluation; it is not quietly left out.
(
assert
!(checkLib.forceEval
(minimal.extendModules {
modules = [ { services.proxy-suite.proxy.tproxy.lanInterfaces = [ "br0\" accept" ]; } ];
}).config.services.proxy-suite.proxy.tproxy.lanInterfaces
).success;
true
)
];
}
+62 -11
View File
@@ -51,7 +51,10 @@ let
viaDns = generated.readDerivation perAppRouting.viaDns;
appCopy = services."proxy-suite-awg-app@";
viaFile = builtins.fromJSON (generated.readDerivation perAppRouting.perAppViaFile);
viaUserRule = generated.readDerivation perAppRouting.viaUserRule;
viaUserStart = generated.readDerivation perAppRouting.viaUserStart;
viaRetire = generated.readDerivation perAppRouting.viaRetire;
viaReapply = generated.readDerivation perAppRouting.viaReapply;
anchor = fixture.config.systemd.user.services."proxy-suite-per-app-via-anchor@";
dePrepare = generated.readDerivation (
builtins.head services.proxy-suite-awg-de.serviceConfig.ExecStartPre
@@ -100,7 +103,7 @@ let
pinTproxyUp = generated.readDerivation pinPerApp.pinUp.tproxy;
pinTproxyDown = generated.readDerivation pinPerApp.pinDown.tproxy;
pinTunUp = generated.readDerivation pinPerApp.pinUp.tun;
pinUserStart = generated.readDerivation pinPerApp.viaUserStart;
pinUserStart = generated.readDerivation pinPerApp.viaUserRule;
pinTproxyConfig = checkLib.mkTProxyConfig pinFixture;
pinTunConfig = checkLib.mkPerAppTunConfig pinFixture;
pinNft = import ../../modules/proxy-suite/nftables.nix {
@@ -152,14 +155,41 @@ in
)
# Each user's apps, in the outbound's slice; the slice from a user unit.
(
assert hasInfix "^([0-9]+)-((awg|app|tproxy|tun)-[0-9a-f]+)$" viaUserStart;
assert hasInfix "nft_chain=app_mark" viaUserStart;
assert hasInfix ''-name "$slice_name"'' viaUserStart;
assert hasInfix "meta mark set $mark ct mark set $mark" viaUserStart;
assert hasInfix "^([0-9]+)-((awg|app|tproxy|tun)-[0-9a-f]+)$" viaUserRule;
assert hasInfix "nft_chain=app_mark" viaUserRule;
assert hasInfix ''-name "$slice_name"'' viaUserRule;
assert hasInfix "meta mark set $mark ct mark set $mark" viaUserRule;
assert anchor.serviceConfig.Slice == "proxy-suite-per-app-via-%i.slice";
assert services ? "proxy-suite-per-app-via-user@";
true
)
# The via unit is every user's: perApp members only start it (polkit.nix), and the last
# user's unit takes it down, under the lock a rule goes in by, so none lands in a table
# on its way out. A restart puts the users' rules back in its fresh table.
(
let
user = services."proxy-suite-per-app-via-user@".serviceConfig;
lock = ''exec 8>>"/run/proxy-suite-per-app-via/users-$key.lock"'';
in
assert pkgs.lib.hasSuffix " %i" user.ExecStopPost;
# Not on its own restart, nor through a switch's stop and start.
assert hasInfix ''$3 == "restart"'' viaRetire;
assert !services."proxy-suite-per-app-via-user@".serviceConfig.X-RestartIfChanged;
assert hasInfix lock viaUserStart && hasInfix lock viaRetire;
assert hasInfix ''show --property=ActiveState --value "$via_unit") != active'' viaUserStart;
assert hasInfix ''via_unit="proxy-suite-per-app-via@$key.service"'' viaRetire;
assert hasInfix ''via_unit="proxy-suite-per-app-via-''${key%%-*}@''${key#*-}.service"'' viaRetire;
assert hasInfix "--state=active,activating,reloading" viaRetire;
assert hasInfix "-v self=\"proxy-suite-per-app-via-user@$1.service\" '$1 != self')" viaRetire;
# The profile brought up for the apps after the via unit, whose stop reads its slot.
assert
builtins.match ''.*stop "\$via_unit".*stop "proxy-suite-awg-app@\$tag\.service".*'' viaRetire
!= null;
assert pkgs.lib.hasSuffix " %i" via.serviceConfig.ExecStartPost;
assert hasInfix ''"proxy-suite-per-app-via-user@*-''${1:-}.service"'' viaReapply;
assert hasInfix "--state=active " viaReapply;
true
)
# Global TProxy and the kill switch let the apps' mark past.
(
# And the slots of the outbounds added at runtime, on interfaces of their own.
@@ -175,9 +205,11 @@ in
(
assert appCopy.wantedBy == [ ];
assert appCopy.serviceConfig.Restart == "no";
assert
builtins.elem "proxy-suite-awg-%i.service" appCopy.conflicts
&& builtins.elem "proxy-suite-awg@%i.service" appCopy.conflicts;
# Never up with the profile itself, and never taking it down: refused while it is up.
assert (appCopy.conflicts or [ ]) == [ ];
assert hasInfix "proxy-suite-awg-%i.service proxy-suite-awg@%i.service" (
builtins.head appCopy.serviceConfig.ExecStartPre
);
assert builtins.elem "proxy-suite-awg-app-watchdog@%i.service" appCopy.wants;
assert services."proxy-suite-awg-app-watchdog@".bindsTo == [ "proxy-suite-awg-app@%i.service" ];
assert appCopy.serviceConfig.RuntimeDirectory == "proxy-suite-awg-app-%i";
@@ -198,8 +230,15 @@ in
assert pinServices ? "proxy-suite-per-app-via-tproxy@";
assert pinServices."proxy-suite-per-app-via-tproxy@".partOf == [ "proxy-suite-socks.service" ];
assert pinServices."proxy-suite-per-app-via-tun@".partOf == [ "proxy-suite-per-app-tun.service" ];
assert builtins.elem "proxy-suite-tproxy.service"
pinServices."proxy-suite-per-app-via-tun@".conflicts;
# Restarted with the backend, the slot's table comes back empty: the users' rules too.
assert pkgs.lib.hasSuffix " tun-%i"
pinServices."proxy-suite-per-app-via-tun@".serviceConfig.ExecStartPost;
assert pkgs.lib.hasSuffix " tproxy-%i"
pinServices."proxy-suite-per-app-via-tproxy@".serviceConfig.ExecStartPost;
# Under a global mode it stays down rather than take the mode down.
assert (pinServices."proxy-suite-per-app-via-tun@".conflicts or [ ]) == [ ];
assert pkgs.lib.hasInfix "proxy-suite-tproxy.service proxy-suite-tun.service"
pinServices."proxy-suite-per-app-via-tun@".serviceConfig.ExecStartPre;
assert pinServices ? "proxy-suite-per-app-via-user@";
# The kernel path's unit only with an "interface" AmneziaWG outbound to take.
assert !(pinServices ? "proxy-suite-per-app-via@");
@@ -248,7 +287,7 @@ in
);
# The user rule units find the slot a pin holds.
assert hasInfix "^([0-9]+)-((awg|app|tproxy|tun)-[0-9a-f]+)$" pinUserStart;
assert hasInfix "nft_chain=output" pinUserStart;
assert hasInfix "nft_chain=app_mark" pinUserStart;
assert hasInfix "23168" (checkLib.mkNftRules pinFixture "killSwitchRulesFile");
true
)
@@ -267,6 +306,18 @@ in
};
}
))
# A table a pin slot takes for itself, named by an option too: the two would flush each
# other's routes.
(rejectsProxySuite "route table 170 (proxy.tproxy.routeTable" (
pinConfig
// {
proxy = pinConfig.proxy // {
tproxy = pinConfig.proxy.tproxy // {
routeTable = 170;
};
};
}
))
(rejectsProxySuite "outbound 'plain' needs route \"tproxy\" or \"tun\"" (
config
// {
+17 -2
View File
@@ -29,7 +29,7 @@ let
perAppRoutingTproxyServiceConfig =
perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy".serviceConfig;
perAppRoutingTproxyStartScript = generated.readDerivation perAppRoutingTproxyServiceConfig.ExecStart;
perAppRoutingTproxyStopScript = generated.readDerivation perAppRoutingTproxyServiceConfig.ExecStop;
perAppRoutingTproxyStopScript = generated.readDerivation perAppRoutingTproxyServiceConfig.ExecStopPost;
perAppRoutingTproxyUserStartScript = generated.readDerivation (
(mkPerAppUserRules perAppRoutingTproxyFixture).perAppTproxyUserRuleStart
);
@@ -62,13 +62,19 @@ in
assert perAppRoutingTproxyFixture.config.systemd.services ? "proxy-suite-per-app-tproxy-user@";
assert
perAppRoutingTproxyFixture.config.systemd.user.services ? "proxy-suite-per-app-tproxy-anchor";
assert
perAppRoutingTproxyFixture.config.systemd.services.proxy-suite-per-app-tproxy.unitConfig.StopWhenUnneeded;
assert
perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy-user@".requires == [
"proxy-suite-per-app-tproxy.service"
];
true
)
# -- perAppRouting: app TProxy helper installs socket cgroup mark rules --
(
assert pkgs.lib.hasInfix "socket cgroupv2" perAppRoutingTproxyUserStartScript;
assert pkgs.lib.hasInfix "add rule inet proxy_suite_per_app_tproxy output"
assert pkgs.lib.hasInfix "add rule inet proxy_suite_per_app_tproxy app_mark"
perAppRoutingTproxyUserStartScript;
assert pkgs.lib.hasInfix "meta mark set" perAppRoutingTproxyUserStartScript;
assert pkgs.lib.hasInfix "ct mark set" perAppRoutingTproxyUserStartScript;
@@ -91,6 +97,15 @@ in
assert guardedBeforeMark (builtins.elemAt chains 1);
# This host's own addresses are not tproxied.
assert hasInfix "fib daddr type local return" (builtins.elemAt chains 0);
# Every lookup of a tproxied app, a LAN or loopback resolver's too, is marked, ahead
# of the reserved ranges, and goes to the route's DNS forwarder; its own do not.
assert hasInfix "th dport 53 goto app_mark" (
builtins.head (splitString "daddr $RESERVED_IP return" (builtins.elemAt chains 1))
);
assert hasInfix
"meta mark 17 meta l4proto { tcp, udp } th dport 53 ip daddr != 192.0.2.53 redirect to :19200"
perAppRoutingTproxyNftRules;
assert hasInfix "meta mark 17 ct mark set 17 return" perAppRoutingTproxyNftRules;
true
)
+14 -1
View File
@@ -145,8 +145,21 @@ in
(
assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun";
assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun-user@";
# Every user's: it goes once the last user's marking that requires it stops; never by a
# member's stop under the others' apps. Requires=, not BindsTo=, so the marking stays up
# through a crash and its automatic restart, which restarts the marking too.
assert
perAppRoutingTunFixture.config.systemd.services.proxy-suite-per-app-tun.unitConfig.StopWhenUnneeded;
assert
perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun-user@".requires == [
"proxy-suite-per-app-tun.service"
];
assert
perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun-user@".bindsTo == [ ];
assert perAppRoutingTunFixture.config.systemd.user.services ? "proxy-suite-per-app-tun-anchor";
assert perAppRoutingTunServiceConfig.ExecStartPre == perAppRoutingTunServiceConfig.ExecStopPost;
assert
builtins.head perAppRoutingTunServiceConfig.ExecStartPre
== perAppRoutingTunServiceConfig.ExecStopPost;
# With proxy.ipv6, wrapped apps' IPv6 goes through the app TUN too.
assert pkgs.lib.hasInfix "link set dev psperapptun0 up" perAppRoutingTunUpScript;
assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev psperapptun0'' perAppRoutingTunUpScript;
+6
View File
@@ -202,6 +202,12 @@ in
perAppRoutingZapretFixture.config.systemd.user.services ? "proxy-suite-per-app-zapret-anchor";
assert builtins.elem "network-online.target" perAppRoutingZapretService.after;
assert builtins.elem "network-online.target" perAppRoutingZapretService.wants;
# Declared with zapret's units; units.nix adds that it goes once no user needs it.
assert perAppRoutingZapretService.unitConfig.StopWhenUnneeded;
assert
perAppRoutingZapretFixture.config.systemd.services."proxy-suite-per-app-zapret-user@".requires == [
"proxy-suite-per-app-zapret.service"
];
true
)
+29 -2
View File
@@ -46,6 +46,8 @@ pkgs.testers.runNixOSTest {
inbounds = {
enable = true;
inherit serverAddress;
# The origin is this host's own web server: through the tunnel only as a listed port.
serverPorts = [ 80 ];
routing.via = "direct";
openFirewall = true;
users = {
@@ -74,6 +76,16 @@ pkgs.testers.runNixOSTest {
services.nginx = {
enable = true;
virtualHosts."origin".locations."/".return = "200 'served-from-origin'";
# On every address, kept from the internet by the firewall alone.
virtualHosts."internal" = {
listen = [
{
addr = "0.0.0.0";
port = 8080;
}
];
locations."/".return = "200 'internal-only'";
};
};
networking.firewall.allowedTCPPorts = [ 80 ];
# Written at boot, so the listener's spec carries only the paths.
@@ -149,6 +161,17 @@ pkgs.testers.runNixOSTest {
"curl -sS --fail --max-time 15 --proxy socks5h://127.0.0.1:1080"
" http://127.0.0.1/ 2>&1"
)
# Nor into a port of its own the firewall closes: "direct" would dial it over lo. The
# fence carries the addresses its interfaces had at start, the private one too.
cfg = "/run/proxy-suite-inbounds/config.json"
server.succeed(f"jq -e '[.outbounds[] | select(.tag == \"direct\") | .settings.finalRules[] | select(.ip and (.ip | index(\"${serverPrivateAddress}\")))] | length == 2' {cfg}")
server.succeed(f"jq -e '[.. | objects | select(has(\"_hostAddresses\"))] == []' {cfg}")
server.succeed("curl -sS --fail --max-time 5 http://${serverAddress}:8080/ | grep -q internal-only")
client.fail("curl -sS --fail --max-time 5 http://${serverAddress}:8080/")
client.fail(
"curl -sS --fail --max-time 15 --proxy socks5h://127.0.0.1:1080"
" http://${serverAddress}:8080/ 2>&1"
)
with subtest("share links are generated and readable by proxy-ctl"):
links = "/run/proxy-suite-inbounds/links.json"
@@ -171,13 +194,17 @@ pkgs.testers.runNixOSTest {
# The reload's restart returns once the start script is forked: config.json is
# gone until it renders it again.
server.wait_until_succeeds(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\", \"friend\"]' {cfg}")
server.succeed("proxy-ctl inbounds add rt vless --port 9001 --user friend --user tester")
server.succeed("proxy-ctl inbounds add rt vless --port 9001 --user friend")
server.wait_for_open_port(9001)
server.succeed("proxy-ctl inbounds users | grep friend | grep -q rt")
# Refused, and nothing else disturbed.
# Refused, and nothing else disturbed. A declared user's uuid stays off a plain listener.
server.fail("proxy-ctl inbounds add far vless --port 30000 --user friend")
server.fail("proxy-ctl inbounds add clear vless --port 9002 --user tester")
server.fail("proxy-ctl inbounds bind tester rt")
server.fail("proxy-ctl inbounds bind tester vless-in")
server.succeed("test ! -e /var/lib/proxy-suite/inbounds.d/listeners/far.json")
server.succeed("test ! -e /var/lib/proxy-suite/inbounds.d/listeners/clear.json")
server.succeed("jq -e '.users | index(\"tester\") == null' /var/lib/proxy-suite/inbounds.d/listeners/rt.json")
# The runtime user's link works from the client, as a runtime outbound there. XRay
# refuses plain VLESS to a public IP, so it dials the private one.
link = server.succeed("proxy-ctl inbounds link rt friend").strip()
+104 -2
View File
@@ -949,17 +949,93 @@ let
true
)
(ok ((ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ]))
# Names that resolve private are refused where XRay dials them itself.
# Names that resolve private are refused where XRay dials them itself. This host's own
# addresses only on its public ports: "direct" dials them over lo, past the firewall.
# The start script adds the interfaces' addresses to the marked rules. XRay's own resolvers
# stay reachable on their port, should one be on this host.
(
let
hostAddresses = [
"127.0.0.0/8"
"::1/128"
"0.0.0.0/32"
"::/128"
];
in
assert
(lib.findFirst (ob: ob.tag == "direct") null relayConfig.outbounds).settings.finalRules == [
{
action = "block";
ip = [ "geoip:private" ];
}
{
action = "allow";
ip = [ "1.1.1.1" ];
port = "53";
}
{
action = "allow";
ip = hostAddresses;
port = "443";
_hostAddresses = true;
}
{
action = "block";
ip = hostAddresses;
_hostAddresses = true;
}
];
true
)
# blockPrivate = false opens the LAN, not the rest of this host.
(
let
rules = (lib.findFirst (ob: ob.tag == "direct") null unguardedConfig.outbounds).settings.finalRules;
in
assert
map (rule: rule.action) rules == [
"block"
"allow"
"allow"
"block"
"allow"
];
# Nor cloud metadata.
assert builtins.elem "169.254.169.254" (builtins.elemAt rules 0).ip;
assert (builtins.elemAt rules 1).ip == [ "1.1.1.1" ];
assert (builtins.elemAt rules 2) ? _hostAddresses && (builtins.elemAt rules 2).port == "443";
assert (builtins.elemAt rules 3) ? _hostAddresses && !((builtins.elemAt rules 3) ? port);
assert lib.last rules == { action = "allow"; };
true
)
# The serverSource ranges and the IPs of serverAddress and serverAliases are this host's
# too; the fence takes the share ports the routing rules do.
(
let
fence =
builtins.elemAt
(lib.findFirst (ob: ob.tag == "direct") null selfSourceConfig.outbounds).settings.finalRules
2;
in
assert
lib.drop 4 fence.ip == [
"10.78.0.0/24"
"fd78:78:78::/64"
"203.0.113.10"
"2001:db8::10"
];
assert fence.port == (ruleByTag selfSourceConfig "inbound-server-address-direct-ip").port;
true
)
(
let
startScript = readInboundsStart relayFixture;
in
assert lib.hasInfix "addr show | " startScript;
assert lib.hasInfix "--argjson host_addresses \"$HOST_ADDRESSES\"" startScript;
assert lib.hasInfix "select(._hostAddresses)" startScript;
true
)
# Only the listener ports, not every service on this host.
(ok ((ruleByTag namedConfig "inbound-server-address-direct").port == "443"))
(ok ((ruleByTag blockedConfig "inbound-proxy-domain").inboundTag == [ "open" ]))
@@ -1149,7 +1225,21 @@ let
(ok (hasFailed runtimeNoPortsFixture "inbounds.runtime.enable needs inbounds.runtime.ports"))
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct").port == "443,993,7882-7885"))
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").port == "443,993,7882-7885"))
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").outboundTag == "direct"))
# One allowed UDP packet would carry its whole session direct (XRay routes it once): an
# address goes to an outbound dialing those alone, a name over TCP alone.
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").outboundTag == "direct-server"))
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct").network == "tcp"))
(ok (
(lib.findFirst (ob: ob.tag == "direct-server") null aliasedConfig.outbounds).settings.finalRules
== [
{
action = "allow";
ip = (ruleByTag aliasedConfig "inbound-server-address-direct-ip").ip;
port = "443,993,7882-7885";
}
{ action = "block"; }
]
))
(ok (!builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig)))
# A per-listener via becomes its own rule; listeners on the default do not.
@@ -1315,6 +1405,18 @@ let
assert lib.hasInfix "chmod 640 \"$tmp\"" (statsScript controlFixture);
assert !lib.hasInfix "chgrp" (statsScript relayFixture);
assert lib.hasInfix "chmod 600 \"$tmp\"" (statsScript relayFixture);
# Who is online goes in it too: the API, which can reset the counters, is root's.
assert lib.hasInfix ".online = (\\$online.users // [])" (statsScript controlFixture);
true
)
(
let
startScript = readInboundsStart controlFixture;
in
assert lib.hasSuffix ",0600" (builtins.head relayConfig.inbounds).listen;
assert lib.hasInfix "install -d -m 0700 -o proxy-suite-daemon -g proxy-suite-daemon \"$API_DIR\""
startScript;
assert !lib.hasInfix "setfacl" startScript;
true
)
+70
View File
@@ -56,6 +56,13 @@ let
constants.readSourceFunction = _: ''
_proxy_suite_read_source() { cat -- "$1"; }
'';
# The hop login, in the build directory.
constants.hopUser = "hop";
constants.hopLoginFile = "hop-login";
constants.ensureHopLogin =
_: pkgs.writeShellScript "proxy-suite-hop-login" "[ -s hop-login ] || printf s3cret > hop-login";
# The build runs as its own user: no one to drop to.
constants.runAsServiceUser = _: _: "";
pureXrayEnabled = false;
collapseNamedOutbounds = null;
backend = null;
@@ -68,6 +75,7 @@ let
mkSubscriptionBlock = null;
mkSubscriptionLoadHelperBlock = null;
runtimeSubscriptionsBlock = null;
singBoxBin = "${pkgs.sing-box}/bin/sing-box";
};
in
{
@@ -377,6 +385,65 @@ in
}
);
# The runner's spool, as members fill it: read through no link or FIFO, and emptied of
# what it took; and an install from before it, whose state dir the group wrote to.
autoproxy-spool =
let
runner = pkgs.writeShellScript "proxy-suite-autoproxy" (
fillTemplate ../../modules/proxy-suite/autoproxy-run.template.sh {
# The build dir's stub/ first: proxy-ctl answers every probe.
path = "$PWD/stub:${
pkgs.lib.makeBinPath [
pkgs.coreutils
pkgs.curl
pkgs.findutils
pkgs.gawk
pkgs.gnugrep
pkgs.gnused
pkgs.jq
pkgs.util-linux
]
}";
stateDir = "/nonexistent";
spoolDir = "/nonexistent";
runtimeDir = "/nonexistent";
ttlDays = "30";
migrate = import ../../modules/proxy-suite/autoproxy-migrate.nix { inherit pkgs; };
editJq = ../../modules/proxy-suite/autoproxy-edit.jq;
render = pkgs.writeShellScript "proxy-suite-autoproxy-render" (
fillTemplate ../../modules/proxy-suite/autoproxy-render.template.sh {
path = pkgs.lib.makeBinPath [
pkgs.coreutils
pkgs.jq
];
serviceUser = "proxy-suite-daemon";
groupArg = "";
}
);
strikeJq = ../../modules/proxy-suite/autoproxy-strike.jq;
roundsJq = ../../modules/proxy-suite/autoproxy-rounds.jq;
interval = "1h";
journalctl = "false";
excludeHosts = "";
excludeSampleHosts = "";
slowJudgeJq = ../../modules/proxy-suite/autoproxy-slow-judge.jq;
probesPerRun = "5";
publicSuffixes =
pkgs.runCommand "proxy-suite-autoproxy-public-suffixes" { nativeBuildInputs = [ pkgs.python3 ]; }
"python3 ${../../modules/proxy-suite/zapret2/public-suffixes.py} --private ${pkgs.publicsuffix-list}/share/publicsuffix/public_suffix_list.dat >$out";
}
);
in
pkgs.runCommand "proxy-suite-autoproxy-spool-check" {
nativeBuildInputs = [
pkgs.coreutils
pkgs.diffutils
pkgs.findutils
pkgs.gnugrep
pkgs.jq
];
} (fillTemplate ./repo/autoproxy-spool.template.sh { inherit runner; });
# A probe that exits 0 printing nothing: jq reads "" as no input at all, so the
# "error" guard downstream saw "" instead of "error" and let it through to
# `--argjson r ""`, which failed every autoProxy run until the state changed.
@@ -488,9 +555,12 @@ in
echo '{"type": "tor", "executable_path": "/tmp/x"}' > obd/tor.json
echo '{"type": "ssh", "server": "h", "private_key_path": "/root/.ssh/id_ed25519"}' > obd/ssh.json
echo '{"type": "vless", "server": "h", "tls": {"enabled": true, "certificate_path": "/etc/shadow"}}' > obd/cert.json
# A field the backend does not know would fail its whole start: this one alone goes.
echo '{"type": "socks", "server": "127.0.0.1", "server_prot": 1080}' > obd/typo.json
${loadRuntime} 2> err
cat err
jq -e '[.[].tag] == ["ok", "ws"]' outbounds.json > /dev/null
grep -q "runtime outbound 'typo' is not one the backend takes" err
grep -q "runtime outbound 'tor' names local files or programs (executable_path, type: tor)" err
grep -q "runtime outbound 'ssh' names local files or programs (private_key_path)" err
grep -q "runtime outbound 'cert' names local files or programs (certificate_path)" err
@@ -0,0 +1,62 @@
set -euo pipefail
# The runner as the units run it, against scratch dirs: what members queue in the spool,
# and an install from before it, whose state dir the group wrote to.
mkdir -p state spool run stub
export AUTOPROXY_STATE_DIR=$PWD/state AUTOPROXY_SPOOL_DIR=$PWD/spool PROBE_EXITS_FILE=$PWD/run/probe-exits.json
printf 'secret.example\n' > secret
# Every probe reaches its destination through exit x; each host asked for is logged.
cat > stub/proxy-ctl <<'EOF'
#!/bin/sh
for a; do host=$a; done
echo "$host" >> "$PROBED"
echo '{"verdict":"destination","exit":"x","path":"/"}'
EOF
chmod +x stub/proxy-ctl
export PROBED=$PWD/probed
# --- the old layout: queues, and what a member could leave, in a 0771 state dir ---
echo '{"domains":{"gone.example":{"verdict":"destination","exit":"x","host":"gone.example","at":1}},
"hosts":{},"exits":{"x":{"at":"a[$(touch pwned)]"}},"backlog":{}}' > state/state.json
printf 'old.example\n' > state/requests
printf 'forget gone.example\n' > state/edits.taking
# Root opens lock for writing, appends to samples and installs into rules/ by name.
ln -s "$PWD/secret" state/lock
ln -s "$PWD/secret" state/samples
ln -s "$PWD/run" state/rules
mkfifo state/fifo
chmod 0771 state
# No probe listeners yet: only the edits, which the old queue held.
timeout 60 @runner@ --requests-only > log
grep -q 'no probe listeners' log
test "$(stat -c %a state)" = 751
test -z "$(find state -mindepth 1 \( -type l -o -type p \))"
test "$(cat secret)" = secret.example
jq -e '.domains == {}' state/state.json > /dev/null
# The old requests wait in the spool, edits are applied and gone.
grep -qx old.example spool/requests.migrated.*
test -z "$(find spool -name 'edits*')"
test ! -e state/requests && test ! -e state/edits.taking
# --- what members queue now, and what one may leave in the spool besides ---
printf '[{"i":0,"tag":"direct","port":1,"path":"%s/state/rules/rs-0.json"},
{"i":1,"tag":"x","port":2,"path":"%s/state/rules/rs-1.json"}]\n' "$PWD" "$PWD" > run/probe-exits.json
printf 'new.example\n' > spool/requests.2.1
ln -s "$PWD/secret" spool/requests.3.1
mkfifo spool/requests.4.1
mkdir spool/requests.5.1
printf 'half.example\n' > spool/.requests.6.1.tmp
timeout 60 @runner@ --requests-only > log
# Never through the link, never stuck on the FIFO, never the file still being written.
sort -u probed > probed.sorted
printf 'new.example\nold.example\n' | cmp - probed.sorted
test "$(cat secret)" = secret.example
# Only that one is left; what the run took is gone, whatever it was.
test "$(ls -A spool)" = .requests.6.1.tmp
jq -e '.domains | keys == ["new.example", "old.example"]' state/state.json > /dev/null
jq -e '.rules[0].domain_suffix | sort == ["new.example", "old.example"]' state/rules/rs-1.json > /dev/null
test "$(stat -c %a state/state.json)" = 640
# The exit's "at" from the old state ran nothing.
test ! -e pwned
touch "$out"
@@ -59,6 +59,18 @@ grep -qx "$(printf 'own-vps\tproxy.outbounds')" words
run inbounds link > /dev/null
env AWG_PROFILES_FILE=/nonexistent python3 "$proxy_ctl" __complete awg on
# A candidate is whatever a group member named a file: never shell code to whoever completes.
mkdir -p fake
printf '%s\n' '#!/bin/sh' "printf '%s\\n' 'ok-tag' '\$(touch pwned)' '\`touch pwned\`'" > fake/proxy-ctl
chmod +x fake/proxy-ctl
PATH="$PWD/fake:$PATH" bash -c 'source @bashCompletion@; COMP_WORDS=(proxy-ctl proxy outbounds rm ""); COMP_CWORD=4; _proxy_ctl; printf "%s\n" "${COMPREPLY[@]}"' > completed
[ ! -e pwned ] || { echo "bash completion ran a candidate" >&2; exit 1; }
grep -qx ok-tag completed
mkdir -p spool
touch 'spool/$(touch pwned).url' spool/fine.url
env RUNTIME_OUTBOUNDS_DIR="$PWD/spool" python3 "$proxy_ctl" __complete proxy outbounds rm | cut -f1 > words
! grep -q 'pwned' words || { echo "__complete offered shell code" >&2; exit 1; }
# Every shell's completion file at least parses.
bash -n @bashCompletion@
@zsh@/bin/zsh -n @zshCompletion@
@@ -14,8 +14,7 @@ mkdir -p stub
printf '%s\n' 'fi'
printf '%s\n' 'exit 0'
} > stub/systemctl
printf '#!/bin/sh\nprintf %%s "$2"\n' > stub/systemd-escape
chmod +x stub/systemctl stub/systemd-escape
chmod +x stub/systemctl
export PATH="$PWD/stub:$PATH"
mkdir -p obd subd cache
@@ -68,10 +67,11 @@ done
# Removing something that was never added says so.
! run proxy outbounds rm nope 2>/dev/null
# A good add lands in the spool group-readable, not world-readable.
# A good add lands in the spool root's alone: the link holds credentials, which the rest of
# the group sees only with the "secrets" scope.
run proxy outbounds add spool-one http://example.com:1 | grep -q 'Added outbound: spool-one'
[ "$(cat obd/spool-one.url)" = "http://example.com:1" ]
[ "$(stat -c %a obd/spool-one.url)" = "640" ]
[ "$(stat -c %a obd/spool-one.url)" = "600" ]
run proxy outbounds | grep -q 'spool-one *runtime'
# Adding it twice is refused.
! run proxy outbounds add spool-one http://example.com:1 2>/dev/null
+7 -2
View File
@@ -109,12 +109,17 @@ in
true
)
# Setter unit is present and writes into /run.
# Setter unit is present and writes into /run: its directory outlives each run, and is
# the one place a root unit the group starts may write.
(
let
setterSvc = routeModeFixture.config.systemd.services."proxy-suite-route-mode@";
in
assert !(setterSvc.serviceConfig ? RuntimeDirectory);
assert setterSvc.serviceConfig.RuntimeDirectory == "proxy-suite";
assert setterSvc.serviceConfig.RuntimeDirectoryPreserve == "yes";
assert setterSvc.serviceConfig.ProtectSystem == "strict";
assert setterSvc.serviceConfig.NoNewPrivileges;
assert !(setterSvc.serviceConfig ? ReadWritePaths);
assert pkgs.lib.hasInfix "/run/proxy-suite/route-mode" routeModeSetterScript;
# One case arm lists every mode the setter accepts.
assert pkgs.lib.hasInfix "default | whitelist | blacklist | all-proxy | all-bypass)"
+6
View File
@@ -76,6 +76,12 @@ in
(ok (failedAssertions ipServer == [ ]))
(ok (failedAssertions domainServer == [ ]))
(ok (failedAssertions diskoServer == [ ]))
# SSH on the REALITY port: refused, not left for the two to fight over at boot.
(ok (
failedAssertions (mkServer {
sshPort = 443;
}) != [ ]
))
# disko: btrfs subvolumes, compressed, the swap file, and GRUB on the disk once.
(ok (diskoFs."/".fsType == "btrfs" && builtins.elem "subvol=@" diskoFs."/".options))
+68 -3
View File
@@ -134,12 +134,77 @@ in
true
)
# The fetcher's output must land in the cache, not after a stray newline.
# Private servers are kept only for a declared subscription that opts in: the flag rides
# both entry points to the fetcher; runtime subscriptions and the rest never pass it.
(
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"''
let
generated = import ./read-generated.nix;
fixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "sing-box";
subscriptions = [
{
tag = "lan";
url = "https://sub.lan.example/token";
allowPrivateServers = true;
}
{
tag = "community";
url = "https://example.com/sub/token";
}
];
};
};
}
];
unitScript =
unit: generated.readDerivation fixture.config.systemd.services.${unit}.serviceConfig.ExecStart;
linesWith =
infix: script: builtins.filter (pkgs.lib.hasInfix infix) (pkgs.lib.splitString "\n" script);
flagged = pkgs.lib.hasInfix " --allow-private-servers";
flaggedOnly =
call: script:
builtins.all flagged (linesWith "${call} lan " script)
&& linesWith "${call} lan " script != [ ]
&& !(builtins.any flagged (linesWith "${call} community " script))
&& !(builtins.any flagged (linesWith ''${call} "$RUNTIME_SUB_TAG"'' script));
start = unitScript "proxy-suite-socks";
update = unitScript "proxy-suite-subscription-update";
in
assert flaggedOnly "_proxy_suite_load_subscription" start;
assert flaggedOnly "_proxy_suite_fetch_subscription" update;
assert pkgs.lib.hasInfix ''_proxy_suite_fetch_subscription "$tag" "$src" "''${@:3}"'' start;
# Both the fetch through the tunnel and the kill switch's direct retry.
assert pkgs.lib.hasInfix
''_proxy_suite_run_fetcher tunnel "$tag" "$src" "$cache_tmp" "$links_tmp" "''${@:3}"''
update;
assert pkgs.lib.hasInfix
''_proxy_suite_run_fetcher direct "$tag" "$src" "$cache_tmp" "$links_tmp" "''${@:3}"''
update;
# Through the tunnel too, the subscription server's answer is not parsed as root.
assert pkgs.lib.hasInfix
"setpriv --reuid=proxy-suite-fetch --regid=proxy-suite-fetch --clear-groups"
update;
# Runtime ones over https only, unless the admin allows http.
assert pkgs.lib.hasInfix
''_proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC" --https-only''
update;
true
)
# The fetcher's output must land in the cache, not after a stray newline; each fetch in
# a temporary file of its own, which start scripts running at once do not share.
(
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-fd 3 "$@" > "$cache_tmp" 3> "$links_tmp"''
subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"''
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-fd 3 "$@" > "$cache_tmp" 3> "$links_tmp"''
subscriptionOnlyUpdateScript;
assert pkgs.lib.hasInfix ''tmp=$(mktemp "$1.XXXXXX")'' subscriptionOnlyUpdateScript;
true
)
+4 -2
View File
@@ -76,8 +76,10 @@ in
# Global TUN/TProxy bypass mark keeps relay traffic out of transparent capture.
(
assert !(tgWithGlobalTunServiceConfig ? SocketMark);
# The relay runs as the service user; only the bypass scripts are privileged.
assert tgWithGlobalTunServiceConfig.User == "proxy-suite-daemon";
# The relay runs as a user of its own, not the backends' (whose files and traffic
# exemptions it would share); only the bypass scripts are privileged.
assert !(tgWithGlobalTunServiceConfig ? User);
assert tgWithGlobalTunServiceConfig.DynamicUser;
assert tgWithGlobalTunServiceConfig.ExecStartPre == "+${tgWithGlobalTunModule.bypassUpScript}";
assert tgWithGlobalTunServiceConfig.ExecStopPost == "+${tgWithGlobalTunModule.bypassDownScript}";
assert pkgs.lib.hasInfix "\"system.slice/proxy-suite-tg-ws-proxy.service\" meta mark set 4"
+40 -18
View File
@@ -179,10 +179,11 @@ let
guardRuntime = pkgs.runCommand "proxy-suite-tor-guard-check" { nativeBuildInputs = [ pkgs.jq ]; } ''
echo '{"inbounds":[],"outbounds":[],"dns":{"rules":[]},"route":{"rules":[]}}' |
jq --slurpfile obs <(echo '[]') --argjson auth_enabled false --arg user "" --arg password "" \
--argjson route_enabled true --argjson route_rules "$(cat ${guardRouteRules})" \
--argjson route_enabled true --slurpfile route_rules ${guardRouteRules} \
--arg route_final proxy --arg dns_final remote --argjson clear_dns_rules false \
--argjson probe_inbounds '[]' --argjson autoproxy_rule_sets '[]' --argjson autoproxy_rules '[]' \
--argjson probe_pin_rules '[{"inbound":["probe-in-0"],"outbound":"direct"}]' \
--slurpfile probe_inbounds <(echo '[]') --slurpfile autoproxy_rule_sets <(echo '[]') \
--slurpfile autoproxy_rules <(echo '[]') \
--slurpfile probe_pin_rules <(echo '[{"inbound":["probe-in-0"],"outbound":"direct"}]') \
-f ${guardFilter} > rules.json
jq -e '
.route.rules as $r
@@ -381,16 +382,20 @@ in
true
)
(
# After the loopback guard, which every route mode keeps first.
assert
xrayRouting.xrayRouteModeRules.common == [
{
type = "field";
ruleTag = "tor-onion";
domain = [ "domain:onion" ];
outboundTag = "tor";
}
]
&& lib.head xrayRouting.xrayRoutingRules == lib.head xrayRouting.xrayRouteModeRules.common;
lib.last xrayRouting.xrayRouteModeRules.common == {
type = "field";
ruleTag = "tor-onion";
domain = [ "domain:onion" ];
outboundTag = "tor";
}
&&
lib.take (builtins.length xrayRouting.xrayRouteModeRules.common) xrayRouting.xrayRoutingRules
== xrayRouting.xrayRouteModeRules.common
# Sniffing must not turn a transparent client's connection into one to this host.
&& (lib.head xrayRouting.xrayRoutingRules).ruleTag == "guard-loopback-ip"
&& (lib.head xrayRouting.xrayRoutingRules).outboundTag == "block";
true
)
(
@@ -448,10 +453,12 @@ in
true
)
# Tor runs as the service user, which TUN and TProxy let through, and keeps its keys private.
# Tor runs as a user of its own, which TUN and TProxy let through as they do the service
# user, and keeps its keys private: no other daemon's compromise reaches its control
# socket or onion key.
(
assert
singBoxTorUnit.serviceConfig.User == "proxy-suite-daemon"
singBoxTorUnit.serviceConfig.User == "proxy-suite-tor"
&& singBoxTorUnit.serviceConfig.StateDirectory == "proxy-suite/tor"
&& singBoxTorUnit.serviceConfig.StateDirectoryMode == "0700";
true
@@ -470,15 +477,22 @@ in
)
# The control socket is Tor's alone, with userControl or without: with it the group could
# publish any loopback port as an onion service. `proxy-ctl tor newnym` goes through a
# root unit, which polkit's "services" scope may start.
# unit running as Tor's own user, which polkit's "services" scope may start.
(
assert
(services controlled).proxy-suite-tor.serviceConfig.Group == "proxy-suite-daemon"
(services controlled).proxy-suite-tor.serviceConfig.Group == "proxy-suite-tor"
&& hasInfix "mkdir -p -m 0700" (torStartOf controlled)
&& !(hasInfix "ControlSocketsGroupWritable" (torStartOf controlled))
&& (services controlled) ? proxy-suite-tor-newnym
&& (services controlled).proxy-suite-tor-newnym.serviceConfig.User == "proxy-suite-tor"
&& (services controlled).proxy-suite-tor-newnym.serviceConfig.NoNewPrivileges
&&
(services controlled).proxy-suite-tor-newnym.serviceConfig.RestrictAddressFamilies == [
"AF_UNIX"
]
&& hasInfix "\"proxy-suite-tor-newnym.service\"" (controlled.config.security.polkit.extraConfig)
&& singBoxTorUnit.serviceConfig.Group == "proxy-suite-daemon"
&& singBoxTorUnit.serviceConfig.Group == "proxy-suite-tor"
&& builtins.elem "proxy-suite-tor" singBox.config.services.proxy-suite.internal.systemUsers
&& !(singBoxTorUnit.serviceConfig ? ExecStartPre)
&&
(mkProxyCtlDerived singBox).wrapperEnv.TOR_CONTROL_SOCKET == "/run/proxy-suite-tor/control/socket";
@@ -499,11 +513,19 @@ in
(
assert
hasInfix "Socks5Proxy 127.0.0.1:1080" viaProxyStart
&& hasInfix ''echo "Socks5ProxyUsername "local-user'' viaProxyStart
&& hasInfix "echo 'Socks5ProxyUsername \"local-user\"'" viaProxyStart
&& hasInfix ''"$CREDENTIALS_DIRECTORY/proxy-password"'' viaProxyStart
&& builtins.elem "proxy-password:/run/secrets/local-proxy-password" viaProxyTor.serviceConfig.LoadCredential;
true
)
# Through the local proxy Tor still runs as its own user, which must exist.
(
assert
viaProxyTor.serviceConfig.User == "proxy-suite-tor"
&& viaProxy.config.users.users.proxy-suite-tor.isSystemUser
&& viaProxy.config.users.groups ? proxy-suite-tor;
true
)
# The onion service forwards each listener's share port to where it listens.
(
+35 -4
View File
@@ -118,6 +118,13 @@ in
assert hasInfix ''"proxy-suite-per-app-via-user@" ? instance.split("-")[0]'' (
polkitConfig allFixture
);
# What every user's apps share a member brings up, never down or through a restart:
# that would send the other users' apps out unmarked. Their own marking, either way.
assert hasInfix
''if (scope === "perApp" && !own && ["start","reset-failed"].indexOf(verb) === -1) {''
(polkitConfig allFixture);
assert hasInfix " own = true;\n }\n known = true;" (polkitConfig allFixture);
assert hasInfix "\"proxy-suite-per-app-\":\"perApp\"" (polkitConfig allFixture);
assert groupReadsSecrets allFixture;
assert hasInfix "chown proxy-suite-daemon:proxy-suite \"$backend_config\"" (socksStart allFixture);
assert
@@ -126,21 +133,34 @@ in
"proxy-suite"
"proxy-suite"
];
assert (service allFixture "proxy-suite-autoproxy").StateDirectoryMode == "0771";
# Root writes by fixed names in that group-writable directory: nowhere else.
# The state is root's to write, the group's to read; what members ask for goes to a
# sticky spool beside it, where no member takes away another's request.
assert (service allFixture "proxy-suite-autoproxy").StateDirectoryMode == "0751";
assert builtins.elem "d /var/lib/proxy-suite/autoproxy-requests 3770 root proxy-suite -" (
allFixture.config.systemd.tmpfiles.rules
);
# Root removes what members queued in that group-writable spool: nothing else changes.
assert builtins.all
(
unit:
let
c = service allFixture unit;
in
c.ProtectSystem == "strict" && c.ProtectHome && c.PrivateTmp
c.ProtectSystem == "strict"
&& c.ProtectHome
&& c.PrivateTmp
&& c.ReadWritePaths == [ "-/var/lib/proxy-suite/autoproxy-requests" ]
)
[
"proxy-suite-autoproxy"
"proxy-suite-autoproxy-learn"
"proxy-suite-autoproxy-sample"
];
# An install from before the spool is made root's before the socks start writes there.
assert hasInfix
"-proxy-suite-autoproxy-migrate \"$AUTOPROXY_DIR\" /var/lib/proxy-suite/autoproxy-requests"
(socksStart allFixture);
assert (wrapperEnv allFixture).AUTOPROXY_SPOOL_DIR == "/var/lib/proxy-suite/autoproxy-requests";
assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 2770 root proxy-suite -" (
allFixture.config.systemd.tmpfiles.rules
);
@@ -172,6 +192,9 @@ in
null
];
assert (service routingOnlyFixture "proxy-suite-autoproxy").StateDirectoryMode == "0751";
assert builtins.elem "d /var/lib/proxy-suite/autoproxy-requests 0700 root root -" (
routingOnlyFixture.config.systemd.tmpfiles.rules
);
assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 0700 root root -" (
routingOnlyFixture.config.systemd.tmpfiles.rules
);
@@ -216,10 +239,18 @@ in
null
null
];
assert (service fixture "proxy-suite-autoproxy").StateDirectoryMode == "0771";
assert (service fixture "proxy-suite-autoproxy").StateDirectoryMode == "0751";
assert derived.userControlExtraGroupsFor "autoProxy" == [ "proxy-admins" ];
# The state dir read through its own unit's ACLs; the spool written through
# proxy-suite-acls', there before any autoProxy unit has run.
assert pkgs.lib.hasSuffix "-proxy-suite-autoproxy-acl"
(service fixture "proxy-suite-autoproxy").ExecStartPre;
assert builtins.elem "d /var/lib/proxy-suite/autoproxy-requests 3770 root root -" (
fixture.config.systemd.tmpfiles.rules
);
assert hasInfix
"setfacl -R -P -n -m g:proxy-admins:rwX,d:g:proxy-admins:rwX -- /var/lib/proxy-suite/autoproxy-requests"
acls;
# Secrets to proxy-admins alone, still 600 for the primary group.
assert hasInfix "chmod 600 \"$SHARE_TMP\"" start;
assert hasInfix "setfacl -m g:proxy-admins:r -- \"$SHARE_TMP\"" start;
+31 -2
View File
@@ -42,7 +42,7 @@ let
generated.readDerivation
fixture.config.systemd.services."proxy-suite-warp-tunnel".serviceConfig.ExecStart;
convertCall =
fixture: "warp_outbound.py --tag warp --routing-mark ${markOf fixture} < \"$profile\"";
fixture: "warp_outbound.py --tag \"$TUNNEL_TAG\" --routing-mark ${markOf fixture} < \"$profile\"";
singBoxHop = ''"server":"127.0.0.1","server_port":18538,"tag":"warp","type":"socks"'';
xrayHop = ''"protocol":"socks","settings":{"address":"127.0.0.1","port":18538},"tag":"warp"'';
@@ -276,6 +276,33 @@ in
assert hasInfix (convertCall singBox) singBoxTunnel;
true
)
# The tag reaches the scripts as a variable, never spliced into shell or jq text.
(
assert
hasInfix "TUNNEL_TAG=warp\n" singBoxTunnel
&& hasInfix "export TUNNEL_TAG" singBoxTunnel
&& hasInfix ''jq -n --arg tag "$TUNNEL_TAG"'' singBoxTunnel
&& hasInfix "final: $tag" singBoxTunnel
&& !(hasInfix ''"warp"'' singBoxTunnel);
true
)
# The root conversion step is sandboxed; the runtime directory stays writable for the
# watchdog's hints.
(
let
sc = singBox.config.systemd.services."proxy-suite-warp-tunnel".serviceConfig;
in
assert
sc.NoNewPrivileges
&& sc.PrivateTmp
&& sc.ProtectSystem == "strict"
&& sc.ReadWritePaths == [ "/run" ]
&& sc.ProtectKernelTunables
&& sc.ProtectControlGroups
&& sc.RestrictSUIDSGID
&& !(sc ? ProtectHome);
true
)
(
assert !(hasInfix "PrivateKey" singBoxTunnel);
true
@@ -331,7 +358,9 @@ in
assert
hasInfix "--reuid=proxy-suite-daemon" singBoxTunnel
&& hasInfix "--ambient-caps=-all,+net_admin --bounding-set" singBoxTunnel
&& hasInfix ''{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: 18539}'' singBoxTunnel
&& hasInfix ''{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: 18539,'' singBoxTunnel
# It reaches the uplink past the kill switch: a login drawn per start, never in argv.
&& hasInfix ''users: [{username: "probe", password: $ENV.DIRECT_AUTH}]'' singBoxTunnel
&& hasInfix ''{type: "direct", tag: "direct", routing_mark: ${markOf singBox}}'' singBoxTunnel;
true
)
@@ -13,7 +13,7 @@ check_runtime() {
--arg user "" \
--arg password "" \
--argjson route_enabled true \
--argjson route_rules '[]' \
--slurpfile route_rules <(echo '[]') \
--arg route_final "proxy" \
--arg dns_final "remote" \
--argjson clear_dns_rules false \
@@ -44,7 +44,7 @@
"172.19.0.1/30"
checkConstants.globalTunIPv6Address
];
assert tunInbound.sniffing.destOverride == [ "fakedns" ];
assert tunInbound.sniffing.destOverride == [ "fakedns+others" ];
assert tunInbound.sniffing.metadataOnly == false;
assert xrayTunConfig.routing.domainStrategy == "IPIfNonMatch";
assert tunHasFinalRuleTag;
@@ -99,11 +99,13 @@
assert pkgs.lib.hasInfix
"rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}"
xrayTunUpScript;
# Both families, but IPv6 only where the kernel has it (ipv6.disable=1 refuses every -6).
assert pkgs.lib.hasInfix "if [ -e /proc/net/if_inet6 ]; then families+=(-6); fi" xrayTunUpScript;
assert pkgs.lib.hasInfix
"-6 rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101"
''"$family" rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101''
xrayTunUpScript;
assert pkgs.lib.hasInfix
"-6 rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}"
''"$family" rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}''
xrayTunUpScript;
assert pkgs.lib.hasInfix
''"$family" rule add pref ${toString checkConstants.xrayTunMarkBypassRulePriority} fwmark 2 lookup main''
@@ -25,7 +25,7 @@
"172.20.0.1/30"
checkConstants.perAppTunIPv6Address
];
assert perAppTunInbound.sniffing.destOverride == [ "fakedns" ];
assert perAppTunInbound.sniffing.destOverride == [ "fakedns+others" ];
assert perAppTunInbound.sniffing.metadataOnly == false;
assert xrayPerAppTunConfig.routing.domainStrategy == "IPIfNonMatch";
assert (builtins.head xrayPerAppTunConfig.dns.servers).address == "fakedns";
+21 -3
View File
@@ -116,8 +116,16 @@ in
in
assert gc.Type == "notify" && sc.Type == "notify";
assert gc.Restart == "on-failure" && sc.Restart == "on-failure";
assert lib.hasSuffix "stop_fw" gc.ExecStopPost;
assert lib.hasSuffix "stop_fw" (builtins.head gc.ExecStopPost);
assert builtins.length sc.ExecStopPost == 2;
# Root in a directory the zapret scope writes to: a symlink there must not reach
# /proc/sys, /sys or devices. Hence also the conntrack sysctl outside it ("+").
assert gc.ProtectKernelTunables && gc.PrivateDevices && sc.ProtectKernelTunables;
# And put back as it was on stop, not forced to 0.
assert
lib.hasPrefix "-+" gc.ExecStartPost
&& lib.hasSuffix "-proxy-suite-zapret2-liberal" gc.ExecStartPost;
assert lib.hasSuffix "-proxy-suite-zapret2-liberal" (lib.last gc.ExecStopPost);
true
)
@@ -286,6 +294,13 @@ in
end
assert(key("a.b.foo.co.uk", "3") == "b.foo.co.uk")
assert(key("1.2.3.4", "2", true) == "standard")
-- What detect.lua must never learn: a suffix takes every site under it.
for _, host in ipairs({ "com", "co.uk", "CO.UK.", "localhost" }) do
assert(proxy_suite_is_public_suffix(host), host)
end
for _, host in ipairs({ "example.com", "foo.co.uk", "github.io" }) do
assert(not proxy_suite_is_public_suffix(host), host)
end
assert(key("www.google.com", nil) == "standard")
'
# What nfqws2's learner and z2k's detector miss: flaky sites, stalled transfers,
@@ -293,7 +308,8 @@ in
# proxy routes by: works, unfixable, blocked by address.
mkdir -p detect
touch detect/verdicts.tsv
DETECT=$(grep -oE '/nix/store/[^ ]+-detect\.lua' "${z2kRuntime}/config") WORK="$PWD/detect" \
PSL=$(grep -oE '/nix/store/[^ ]+-proxy-suite-zapret2-public-suffix-hostkey\.lua' "${z2kRuntime}/config") \
DETECT=$(grep -oE '/nix/store/[^ ]+-detect\.lua' "${z2kRuntime}/config") WORK="$PWD/detect" \
PROXY_SUITE_ZAPRET2_VERDICTS="$PWD/detect/verdicts.tsv" lua ${./zapret2/detect-test.lua}
# nfqws2 finds the verdicts file by its environment; the last profile watches
# connections for addresses blocked outright.
@@ -427,7 +443,9 @@ in
grep -qF -- '[[ $last =~ ^[0-9]+$ ]] || last=0' ${cutoffProbe}
if grep -qF -- '$((now - $(cat ts' ${cutoffProbe}; then exit 1; fi
# The group's probe request comes through requests/, not the directory root works in.
grep -qF -- 'if [ -e requests/force ]; then' ${cutoffProbe}
grep -qF -- 'if [ -e requests/force ] || [ -L requests/force ]; then' ${cutoffProbe}
# Whatever a member left under the name goes, a directory too: set -e stopped every run.
grep -qF -- 'rm -rf -- requests/force' ${cutoffProbe}
# Cut-off networks without a name become the proxy's rule-set; named ones stay with zapret2.
rules=$(grep -oE '/nix/store/[^ ]+-proxy-suite-zapret2 asn.txt' ${cutoffProbe} | cut -d' ' -f1)
+12
View File
@@ -51,6 +51,8 @@ local hrec = { nstrategy = 1, ctstrategy = 50 }
function automate_host_record() return hrec end
function z2k_fail_tls_alert() return "z2k" end
-- detect.lua's public suffixes, loaded before it as nfqws2 does.
dofile(os.getenv("PSL"))
dofile(os.getenv("DETECT"))
local auto = work .. "/auto.txt"
@@ -233,4 +235,14 @@ end
assert(verdicts()["149.154.167.99 ip"] == "blocked" and not verdicts()["192.168.1.1 ip"], "blocked by address")
syn("149.154.167.99", true)
assert(verdicts()["149.154.167.99 ip"] == "reachable", "an answer clears it")
-- A wildcard domain whose every fresh name resets: past its share of the list, the site
-- itself is learned, which covers the rest, rather than one more name of it.
local f2 = io.open(auto, "a")
for i = 1, 64 do f2:write("r" .. i .. ".wild.example\n") end
f2:close()
for _ = 1, 3 do
hello(flow("r65.wild.example"))
fire("psln_")
end
assert(learned()["wild.example"] and not learned()["r65.wild.example"], "a flooding site learned whole")
print("detect.lua ok")
+4
View File
@@ -115,6 +115,10 @@ import ./options-doc/render-options-markdown.nix {
name = "tui";
summary = "The `proxy-tui` terminal UI.";
}
{
name = "tools";
summary = "Heavy helpers `proxy-ctl` can do without: lnav and curl-impersonate.";
}
];
defaultConfigText = lib.generators.toPretty { allowPrettyValues = true; } (
visibleConfig eval.options.services.proxy-suite eval.config.services.proxy-suite