fix: multiple fixes + cleanup and formatting

This commit is contained in:
FUFSoB committed 2026-09-17 22:51:31 +05:00
1 parent 321e9ca468
commit c62000821a
59 files changed
+1357 -920

No files matched your search

+1 -53
View File
@@ -1,6 +1,6 @@
# proxy-suite-flake
Declarative proxy stack for NixOS, on either side of the connection: as a client that routes this host's traffic through outbounds, as a server that accepts clients on its own inbounds, or both at once. Configure it in Nix, rebuild, and it runs as systemd services. It also runs on other Linux distributions (through system-manager or home-manager) and on Android (through Nix-on-Droid): see [Other hosts](#other-hosts).
Declarative proxy stack for NixOS, on either side of the connection: as a client that routes this host's traffic through outbounds, as a server that accepts clients on its own inbounds, or both at once. Configure it in Nix, rebuild, and it runs as systemd services. It also runs on other Linux distributions (through system-manager or home-manager) and on Android (through Nix-on-Droid).
> [!IMPORTANT]
> This project is for study and research purposes only: learning how proxies, tunnels and traffic routing work. It comes with no warranty, and the authors are not responsible for how it is used.
@@ -115,58 +115,6 @@ services.proxy-suite = {
};
```
### Other hosts
The same options work outside NixOS. Pick the module for the host; everything the host cannot do fails evaluation with a message naming the option.
| | NixOS | system-manager | home-manager | Nix-on-Droid |
|---|:-:|:-:|:-:|:-:|
| Runs as | root, systemd | root, systemd | user, `systemd --user` | user, `proxy-suitectl` |
| Local SOCKS/HTTP proxy, subscriptions, selection, route modes | ✓ | ✓ | ✓ | ✓ |
| Per-app proxychains | ✓ | ✓ | ✓ | ✓ |
| Server inbounds, share links, stats | ✓ | ✓ | ports ≥ 1024 | ports ≥ 1024 |
| tg-ws-proxy, SSH proxy, WARP as a sing-box outbound, Tor | ✓ | ✓ | ✓ | ✓ |
| AmneziaWG `asOutbound = "userspace"` | ✓ | ✓ | ✓ | ✓ |
| Global TUN/TProxy, per-app TUN/TProxy/zapret, zapret, AmneziaWG interfaces and inbounds | ✓ | ✓ | ✗ | ✗ |
| `userControl`, polkit | ✓ | ✓ | not needed | not needed |
| GUI | ✓ | ✓ | ✓ | ✗ (`proxy-ctl`, `proxy-tui`) |
Rootless hosts get the local proxy only: nothing captures the rest of the host's traffic, so point applications at `127.0.0.1:1080` (or run them through `proxy-ctl apps run`).
#### system-manager (other distributions, as root)
```nix
# with github:numtide/system-manager
modules = [ inputs.proxy-suite.systemManagerModules.default ];
```
- Units, service users and the polkit rules (`/etc/polkit-1/rules.d/50-proxy-suite.rules`) are installed like on NixOS; the GUI's user unit goes to `/etc/systemd/user`. The service users come from `users.users`, so system-manager needs its user management.
- The host's firewall is left alone: open the inbound ports yourself, and let AmneziaWG inbound interfaces (`awgi-*`) through the input chain and strict reverse-path filtering. TUN, TProxy, zapret and AmneziaWG inbounds load their own nftables tables, which needs `nf_tables`, `nfnetlink_queue`, `nft_tproxy` and `tun` in the host kernel.
- AmneziaWG runs on its userspace implementation (`amneziaWg.kernelModulePackage` must stay `null`). DNS pushed by a VPN profile goes through `resolvectl` under systemd-resolved, `openresolv` otherwise.
#### home-manager (any Linux, no root)
```nix
# homeConfigurations.<name> = home-manager.lib.homeManagerConfiguration { ... }
modules = [ inputs.proxy-suite.homeManagerModules.default ];
```
- Units run in the user's systemd manager: `systemctl --user status proxy-suite-socks`. They stop at logout unless lingering is on: `loginctl enable-linger $USER`.
- State lives in `$XDG_STATE_HOME/proxy-suite`, runtime files in `$XDG_CACHE_HOME/proxy-suite/run`.
#### Nix-on-Droid (Android, no root)
```nix
# nixOnDroidConfigurations.default = nix-on-droid.lib.nixOnDroidConfiguration { ... }
modules = [ inputs.proxy-suite.nixOnDroidModules.default ];
```
- Android has no systemd, so `nix-on-droid switch` hands the units to `proxy-suitectl`, a small supervisor that understands the parts of systemd units proxy-suite uses (restarts, dependencies, timers, path watches). `proxy-ctl` talks to it for you; directly, `proxy-suitectl status`, `proxy-suitectl restart proxy-suite-socks` and `proxy-suitectl journal -u 'proxy-suite-*' -f` work much like `systemctl` and `journalctl`.
- Android gives the app no boot hook. The services start on `nix-on-droid switch`, and, with `services.proxy-suite.nixOnDroid.startWithSession` (on by default), whenever a Nix-on-Droid shell opens; `proxy-suitectl boot` starts them by hand.
- Android stops background apps: acquire Nix-on-Droid's wake lock from its notification and exempt the app from battery optimisation, or the services die with the terminal.
- Inbounds are reachable from the local network on ports from 1024 up; zapret is not available (on Android it needs a VPN app).
- An AmneziaWG `userspace` outbound resolves an `Endpoint` hostname through the system resolver; give it as an IP address where that resolver is itself blocked.
---
## Options
+36 -11
View File
@@ -27,7 +27,17 @@ let
map (other: "${serviceName other}.service") (
builtins.filter (other: other != name) globalProfileNames
);
inherit (import ./wg-tunnel.nix { inherit lib pkgs cfg derived; }) mkTunnel;
inherit
(import ./wg-tunnel.nix {
inherit
lib
pkgs
cfg
derived
;
})
mkTunnel
;
sourceCount =
profile:
builtins.length (
@@ -84,9 +94,15 @@ let
bypassRule =
family: action:
"${pkgs.iproute2}/bin/ip ${family} rule ${action} pref ${toString proxyBypassRulePriority} fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main";
clearBypassRules = lib.concatMapStrings (family: ''
while ${bypassRule family "del"} 2>/dev/null; do :; done
'') [ "-4" "-6" ];
clearBypassRules =
lib.concatMapStrings
(family: ''
while ${bypassRule family "del"} 2>/dev/null; do :; done
'')
[
"-4"
"-6"
];
# Some lines drop a share of fresh flows for good, handshakes included. A new source port
# is a new flow, and moving the interface to one keeps its routes, so traffic never leaks
@@ -118,7 +134,9 @@ let
pingVia =
profile:
"${pkgs.iputils}/bin/ping -n -c 1"
+ lib.optionalString (profile.asOutbound == "interface") " -I ${lib.escapeShellArg profile.interfaceName}";
+ lib.optionalString (
profile.asOutbound == "interface"
) " -I ${lib.escapeShellArg profile.interfaceName}";
# An outbound interface keeps the host's routes and resolver, and marks its packets so TUN and
# TProxy let them past.
@@ -126,7 +144,9 @@ let
${pkgs.python3}/bin/python3 ${configTool} \
--manifest ${lib.escapeShellArg (toString (manifestFor profile))} \
--output ${output}${
lib.optionalString (profile.asOutbound == "interface") " --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}"
lib.optionalString (
profile.asOutbound == "interface"
) " --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}"
}
'';
@@ -436,7 +456,8 @@ let
interfaceNames = map (name: profiles.${name}.interfaceName) profileNames;
autostartProfiles = builtins.filter (name: profiles.${name}.autostart) globalProfileNames;
globalAutostartCount = builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
globalAutostartCount =
builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
in
{
services.proxy-suite.internal.packages = [
@@ -445,9 +466,11 @@ in
]
++ lib.optional (builtins.any (ob: ob.kind == "userspace") tunnelOutbounds) awgCfg.wireproxyPackage;
services.proxy-suite.internal.kernelModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [
awgCfg.kernelModulePackage
];
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.
services.proxy-suite.internal.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: ''
@@ -461,7 +484,9 @@ in
(lib.mapAttrs' (
name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile)
) interfaceProfiles)
(lib.listToAttrs (map (ob: lib.nameValuePair (serviceName ob.name) (mkTunnelService ob)) tunnelOutbounds))
(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 -4
View File
@@ -13,10 +13,12 @@
pkgs.writeShellScript "proxy-suite-autoproxy" ''
set -euo pipefail
# $1 - probe-exits.json (index -> tag -> path), $2 - state.json
export PATH=${pkgs.lib.makeBinPath [
pkgs.coreutils
pkgs.jq
]}
export PATH=${
pkgs.lib.makeBinPath [
pkgs.coreutils
pkgs.jq
]
}
jq -c '.[]' "$1" | while IFS= read -r exit; do
tag=$(jq -r '.tag' <<<"$exit")
+25 -19
View File
@@ -69,7 +69,9 @@ let
curl -sS --noproxy '*' --max-time 1 "''${clash_auth[@]}" "http://$clash_api/connections" 2>/dev/null ||
echo '{}'
done | jq -s -r --argjson min ${toString (300 * 1024)} \
--argjson below ${toString (apCfg.slowBelowKiBps * 1024)} -f ${jqFile ./autoproxy-slow-sample.jq} || true
--argjson below ${
toString (apCfg.slowBelowKiBps * 1024)
} -f ${jqFile ./autoproxy-slow-sample.jq} || true
)
[ -z "$lines" ] || printf '%s\n' "$lines" >> "$state_dir/samples"
'';
@@ -492,25 +494,29 @@ in
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";
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 = {
Type = "oneshot";
ExecStart = "${sampler}";
}
// stateDirConfig;
};
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 = {
Type = "oneshot";
ExecStart = "${sampler}";
}
// stateDirConfig;
};
services.proxy-suite.internal.timers.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
description = "proxy-suite autoProxy transfer sampling";
wantedBy = [ "timers.target" ];
timerConfig = {
OnActiveSec = "1m";
OnUnitActiveSec = "1m";
AccuracySec = "5s";
};
};
services.proxy-suite.internal.timers.proxy-suite-autoproxy-sample =
lib.mkIf (apCfg.slowBelowKiBps > 0)
{
description = "proxy-suite autoProxy transfer sampling";
wantedBy = [ "timers.target" ];
timerConfig = {
OnActiveSec = "1m";
OnUnitActiveSec = "1m";
AccuracySec = "5s";
};
};
services.proxy-suite.internal.timers.proxy-suite-autoproxy = {
description = "proxy-suite autoProxy probe schedule";
@@ -114,8 +114,7 @@ let
};
clashApiBlock = lib.optionalAttrs clashApiEnabled {
experimental.clash_api.external_controller =
"127.0.0.1:${toString singBoxCfg.clashApiPort}";
experimental.clash_api.external_controller = "127.0.0.1:${toString singBoxCfg.clashApiPort}";
};
mkConfig =
@@ -144,100 +143,104 @@ let
let
fakeIp = fakeIpCache != null && proxyCfg.dns.fakeIp.enable;
in
lib.recursiveUpdate (
{
log.level = "warn";
dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
inherit useOutboundRoutingMark fakeIp;
onionFakeIpInbounds =
lib.optional enableTun "tun-in"
++ lib.optionals enableTProxy ([ "tproxy-in" ] ++ lib.optional proxyCfg.ipv6 "tproxy-in6");
};
inbounds =
lib.optional enableXrayDnsBridge {
type = "direct";
tag = "xray-dns-in";
listen = "127.0.0.1";
listen_port = xrayDnsBridgePort;
}
++ lib.optional enableMixed {
type = "mixed";
tag = "mixed-in";
listen = proxyCfg.listener.address;
listen_port = proxyCfg.listener.port;
}
++ lib.optionals enableTProxy (
[
{
type = "tproxy";
tag = "tproxy-in";
listen = "127.0.0.1";
listen_port = globalTproxy.port;
}
]
++ lib.optional proxyCfg.ipv6 {
type = "tproxy";
tag = "tproxy-in6";
listen = "::1";
listen_port = globalTproxy.port;
}
)
++ lib.optional enableTun (
{
type = "tun";
tag = "tun-in";
interface_name = tunInterface;
address = [ tunAddress ] ++ lib.optional (proxyCfg.ipv6 && tunIPv6Address != null) tunIPv6Address;
mtu = tunMtu;
auto_route = tunAutoRoute;
auto_redirect = tunAutoRedirect;
strict_route = tunStrictRoute;
stack = "mixed";
}
// lib.optionalAttrs tunAutoRoute {
iproute2_table_index = tunAutoRouteTableIndex;
iproute2_rule_index = tunAutoRouteRuleIndex;
}
);
outbounds = [
(
{
type = "direct";
tag = "direct";
}
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
)
lib.recursiveUpdate
(
{
type = "block";
tag = "block";
}
];
log.level = "warn";
route = {
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
final = if (proxyCfg.routing.default == "proxy") then "proxy" else "direct";
}
// lib.optionalAttrs (enableTun && tunAutoRoute) {
auto_detect_interface = true;
};
}
// lib.optionalAttrs enableClashApi clashApiBlock)
# Fake addresses handed out survive a restart, so apps still holding one keep working. The
# start script creates the directory; nothing else is stored, since TUN configs have no
# Clash API to switch a selector with.
(lib.optionalAttrs fakeIp {
experimental.cache_file = {
enabled = true;
path = "${constants.fakeIpCacheDir}/${fakeIpCache}.db";
store_fakeip = true;
};
});
dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
inherit useOutboundRoutingMark fakeIp;
onionFakeIpInbounds =
lib.optional enableTun "tun-in"
++ lib.optionals enableTProxy ([ "tproxy-in" ] ++ lib.optional proxyCfg.ipv6 "tproxy-in6");
};
inbounds =
lib.optional enableXrayDnsBridge {
type = "direct";
tag = "xray-dns-in";
listen = "127.0.0.1";
listen_port = xrayDnsBridgePort;
}
++ lib.optional enableMixed {
type = "mixed";
tag = "mixed-in";
listen = proxyCfg.listener.address;
listen_port = proxyCfg.listener.port;
}
++ lib.optionals enableTProxy (
[
{
type = "tproxy";
tag = "tproxy-in";
listen = "127.0.0.1";
listen_port = globalTproxy.port;
}
]
++ lib.optional proxyCfg.ipv6 {
type = "tproxy";
tag = "tproxy-in6";
listen = "::1";
listen_port = globalTproxy.port;
}
)
++ lib.optional enableTun (
{
type = "tun";
tag = "tun-in";
interface_name = tunInterface;
address = [ tunAddress ] ++ lib.optional (proxyCfg.ipv6 && tunIPv6Address != null) tunIPv6Address;
mtu = tunMtu;
auto_route = tunAutoRoute;
auto_redirect = tunAutoRedirect;
strict_route = tunStrictRoute;
stack = "mixed";
}
// lib.optionalAttrs tunAutoRoute {
iproute2_table_index = tunAutoRouteTableIndex;
iproute2_rule_index = tunAutoRouteRuleIndex;
}
);
outbounds = [
(
{
type = "direct";
tag = "direct";
}
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
)
{
type = "block";
tag = "block";
}
];
route = {
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
final = if (proxyCfg.routing.default == "proxy") then "proxy" else "direct";
}
// lib.optionalAttrs (enableTun && tunAutoRoute) {
auto_detect_interface = true;
};
}
// lib.optionalAttrs enableClashApi clashApiBlock
)
# Fake addresses handed out survive a restart, so apps still holding one keep working. The
# start script creates the directory; nothing else is stored, since TUN configs have no
# Clash API to switch a selector with.
(
lib.optionalAttrs fakeIp {
experimental.cache_file = {
enabled = true;
path = "${constants.fakeIpCacheDir}/${fakeIpCache}.db";
store_fakeip = true;
};
}
);
in
{
# The local proxy, ready for TProxy. A rootless host can neither take transparent
+18 -11
View File
@@ -221,17 +221,24 @@ let
};
sniffing = standardSniffing;
}
++ lib.zipListsWith (tag: listen: {
inherit tag listen;
protocol = "tunnel";
port = globalTproxy.port;
settings = {
allowedNetwork = "tcp,udp";
followRedirect = true;
};
streamSettings.sockopt.tproxy = "tproxy";
sniffing = standardSniffing;
}) (lib.optionals enableTProxy tproxyInboundTags) [ "127.0.0.1" "::1" ]
++
lib.zipListsWith
(tag: listen: {
inherit tag listen;
protocol = "tunnel";
port = globalTproxy.port;
settings = {
allowedNetwork = "tcp,udp";
followRedirect = true;
};
streamSettings.sockopt.tproxy = "tproxy";
sniffing = standardSniffing;
})
(lib.optionals enableTProxy tproxyInboundTags)
[
"127.0.0.1"
"::1"
]
++ lib.optional enableTun {
tag = "tun-in";
protocol = "tun";
+6 -18
View File
@@ -93,24 +93,12 @@ let
routeModeRules =
if derived.pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
tproxyFile = pkgs.writeText "proxy-suite-core" (
builtins.toJSON selectedTemplates.tproxy
);
tunFile = pkgs.writeText "proxy-suite-core" (
builtins.toJSON selectedTemplates.tun
);
perAppTunFile = pkgs.writeText "proxy-suite-core" (
builtins.toJSON selectedTemplates.perAppTun
);
routeModeRulesFile = pkgs.writeText "proxy-suite-core" (
builtins.toJSON routeModeRules
);
proxyInboundsFile = pkgs.writeText "proxy-suite-inbounds" (
builtins.toJSON proxyInboundsTemplate
);
proxyInboundsSpecFile = pkgs.writeText "proxy-suite-inbounds" (
builtins.toJSON proxyInboundsSpec
);
tproxyFile = pkgs.writeText "proxy-suite-core" (builtins.toJSON selectedTemplates.tproxy);
tunFile = pkgs.writeText "proxy-suite-core" (builtins.toJSON selectedTemplates.tun);
perAppTunFile = pkgs.writeText "proxy-suite-core" (builtins.toJSON selectedTemplates.perAppTun);
routeModeRulesFile = pkgs.writeText "proxy-suite-core" (builtins.toJSON routeModeRules);
proxyInboundsFile = pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON proxyInboundsTemplate);
proxyInboundsSpecFile = pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON proxyInboundsSpec);
in
{
inherit
+3 -3
View File
@@ -98,8 +98,7 @@ let
# .onion names from clients go to the local proxy, whose rule hands them to Tor, whatever
# the listener's via. AmneziaWG listeners never pass XRay's routing.
proxyInboundsRouteOnion =
torRouteOnion
&& lib.any (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds;
torRouteOnion && lib.any (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds;
# Whether any listener or inbounds.routing.proxy exception relays through the local SOCKS
# listener.
@@ -187,7 +186,8 @@ let
l: l.type != null && l.transport.type == "xhttp" && l.tls.enable && l.tls.alpn == [ "h3" ];
# What an onion service can carry: TCP to a listener with a known protocol.
proxyInboundOnionCapable =
ib: ib.listener.type != null && ib.listener.type != "amneziawg" && !proxyInboundIsH3Only ib.listener;
ib:
ib.listener.type != null && ib.listener.type != "amneziawg" && !proxyInboundIsH3Only ib.listener;
torOnionEnabled = torCfg.enable && torCfg.onionService.enable && proxyInboundsEnabled;
torOnionInbounds =
if !torOnionEnabled then
+4 -2
View File
@@ -15,7 +15,7 @@ let
tgWsProxyCfg = cfg.tgWsProxy;
tgWsProxyBypassEnabled = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
tgWsProxyBypassMarkLine = lib.optionalString tgWsProxyBypassEnabled ''
meta mark ${toString tgWsProxyCfg.fwmark} return
meta mark ${toString tgWsProxyCfg.fwmark} return
'';
# Shared across all three nftables rule files that do IP routing.
@@ -54,7 +54,9 @@ let
perAppTproxyLocalSubnetLines = mkLocalSubnetLines perAppTproxy.localSubnets;
# Without ipv6, IPv6 packets are left alone, as if the table were still `ip`.
tproxyProtocols = "${lib.optionalString (!proxyCfg.ipv6) "meta nfproto ipv4 "}meta l4proto { tcp, udp }";
tproxyProtocols = "${
lib.optionalString (!proxyCfg.ipv6) "meta nfproto ipv4 "
}meta l4proto { tcp, udp }";
# Both listeners share the port; `tproxy ip`/`tproxy ip6` only match their own family.
mkTproxyLines = prefix: suffix: ''
${prefix}meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:${toString globalTproxy.port}${suffix}
@@ -77,7 +77,10 @@ in
and AmneziaWG tags work too. A pin still reaches them, and so does a selector switched by
hand.
'';
example = [ "ru-vps" "warp" ];
example = [
"ru-vps"
"warp"
];
};
urlTest = {
@@ -37,9 +37,11 @@ in
};
direct = {
domains = list "Domain suffixes sent direct. zapret hostlists join them when zapret.directSync.enable is on." [
"internal.example"
];
domains =
list "Domain suffixes sent direct. zapret hostlists join them when zapret.directSync.enable is on."
[
"internal.example"
];
ips = list "IP CIDRs sent direct." [ "10.10.0.0/16" ];
geosites = list "Geosite names sent direct." [ "category-ru" ];
geoips = list "Geoip names sent direct." [ "ru" ];
+7 -1
View File
@@ -1,7 +1,13 @@
{ lib, ... }:
let
p = path: [ "services" "proxy-suite" ] ++ lib.splitString "." path;
p =
path:
[
"services"
"proxy-suite"
]
++ lib.splitString "." path;
rm = path: replacement: lib.mkRemovedOptionModule (p path) replacement;
# Top-level zapret options that moved under the engine namespace; the value is
# the leaf name they carry there.
+7 -7
View File
@@ -62,7 +62,9 @@ let
zapretCustomUserIps =
if syncZapretDirectUserIps then
lib.unique (
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.ips) zapretCfg.zapret-discord-youtube.hostlistRules
lib.concatMap (
rule: lib.optionals rule.enableDirectSync rule.ips
) zapretCfg.zapret-discord-youtube.hostlistRules
)
else
[ ];
@@ -104,18 +106,16 @@ let
))
(
lib.unique (
map stripExactPrefix (
zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains
)
map stripExactPrefix (zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains)
)
)
else
[ ];
zapretDirectIps =
if syncZapretDirectAnyIps then
subtractItems (
lib.unique (zapretDefaultIps ++ zapretUserIps ++ zapretCustomUserIps ++ zapretCustomDefaultIps)
) zapretExcludedIps
subtractItems (lib.unique (
zapretDefaultIps ++ zapretUserIps ++ zapretCustomUserIps ++ zapretCustomDefaultIps
)) zapretExcludedIps
else
[ ];
in
+130 -103
View File
@@ -167,12 +167,20 @@ let
(mkAssertion (cfg.userControl.scopes == [ ] || cfg.userControl.enable)
"proxy-suite: userControl.scopes is set but userControl.enable is false, so the group gets nothing"
)
(requireEnabled (cfg.warp.enable && cfg.warp.asOutbound != null) proxyEnabled
"proxy-suite: warp.asOutbound requires proxy.enable = true"
)
(requireEnabled (
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'')
cfg.warp.enable && cfg.warp.asOutbound != null
) proxyEnabled "proxy-suite: warp.asOutbound requires proxy.enable = true")
(requireEnabled
(
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")
@@ -203,16 +211,19 @@ let
(!(pureXrayEnabled && (proxyCfg.dns.local.type == "tls" || proxyCfg.dns.remote.type == "tls")))
"proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.backend = \"xray\"; use udp/tcp DNS for XRay"
)
(mkAssertion (
!pureXrayEnabled
|| (
proxyCfg.dns.strategy == null
&& proxyCfg.dns.clientSubnet == null
&& !proxyCfg.dns.fakeIp.enable
&& proxyCfg.dns.singBox.servers == [ ]
&& proxyCfg.dns.singBox.rules == [ ]
(mkAssertion
(
!pureXrayEnabled
|| (
proxyCfg.dns.strategy == null
&& proxyCfg.dns.clientSubnet == null
&& !proxyCfg.dns.fakeIp.enable
&& proxyCfg.dns.singBox.servers == [ ]
&& proxyCfg.dns.singBox.rules == [ ]
)
)
) "proxy-suite: proxy.dns.strategy, clientSubnet, fakeIp and singBox require proxy.backend = \"sing-box\" or \"hybrid\"")
"proxy-suite: proxy.dns.strategy, clientSubnet, fakeIp and singBox require proxy.backend = \"sing-box\" or \"hybrid\""
)
(requireEnabled globalTun.enable proxyEnabled
"proxy-suite: proxy.tun.enable requires proxy.enable = true"
)
@@ -300,43 +311,40 @@ let
] "proxy-suite: tgWsProxy requires exactly one of secret or secretFile")
];
outboundAssertions = lib.concatMap (ob: [
(exactlyOneOf proxyEnabled
[
outboundAssertions =
lib.concatMap (ob: [
(exactlyOneOf proxyEnabled [
ob.urlFile
ob.url
ob.singBoxJson
ob.xrayJson
]
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, or xrayJson"
)
(mkAssertion (
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
) "proxy-suite: outbound '${ob.tag}': xrayJson requires proxy.backend = xray or hybrid")
(mkAssertion (
!xrayEnabled || hybridEnabled || ob.singBoxJson == null
) "proxy-suite: outbound '${ob.tag}': singBoxJson requires proxy.backend = sing-box or hybrid")
(mkAssertion (
!(ob.backend == "xray") || xrayEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.backend = xray or hybrid")
(mkAssertion (!(ob.backend == "sing-box") || singBoxEnabled)
"proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.backend = sing-box or hybrid"
)
(mkAssertion (
ob.detour != ob.tag
) "proxy-suite: outbound '${ob.tag}': detour cannot name the outbound itself")
])
proxyCfg.outbounds
++ map (
e:
mkAssertion (
!builtins.elem e.detour [
"proxy"
"direct"
"block"
]
) "proxy-suite: '${e.tag}': detour must name a real outbound, not proxy, direct or block"
) (builtins.filter (e: e.detour != null) (proxyCfg.outbounds ++ proxyCfg.subscriptions));
] "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, or xrayJson")
(mkAssertion (
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
) "proxy-suite: outbound '${ob.tag}': xrayJson requires proxy.backend = xray or hybrid")
(mkAssertion (
!xrayEnabled || hybridEnabled || ob.singBoxJson == null
) "proxy-suite: outbound '${ob.tag}': singBoxJson requires proxy.backend = sing-box or hybrid")
(mkAssertion (
!(ob.backend == "xray") || xrayEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.backend = xray or hybrid")
(mkAssertion (!(ob.backend == "sing-box") || singBoxEnabled)
"proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.backend = sing-box or hybrid"
)
(mkAssertion (
ob.detour != ob.tag
) "proxy-suite: outbound '${ob.tag}': detour cannot name the outbound itself")
]) proxyCfg.outbounds
++ map (
e:
mkAssertion (
!builtins.elem e.detour [
"proxy"
"direct"
"block"
]
) "proxy-suite: '${e.tag}': detour must name a real outbound, not proxy, direct or block"
) (builtins.filter (e: e.detour != null) (proxyCfg.outbounds ++ proxyCfg.subscriptions));
proxyInboundsCfg = derived.proxyInboundsCfg;
proxyInboundsEnabled = derived.proxyInboundsEnabled;
@@ -489,24 +497,30 @@ let
(mkAssertion (
!proxyInboundsEnabled || l.xrayJson == null || (l.xrayJson.port or l.port) == l.port
) "${prefix}: xrayJson.port and port differ; the firewall and the port checks go by port")
(mkAssertion (
!proxyInboundsEnabled
|| !proxyInboundsCfg.shareLinks
|| !l.reality.enable
|| builtins.elem l.type [
"vless"
"trojan"
]
) "${prefix}: share links carry reality only for vless and trojan; set inbounds.shareLinks = false to serve it anyway")
(mkAssertion (
!proxyInboundsEnabled
|| !proxyInboundsCfg.shareLinks
|| !l.tls.enable
|| !builtins.elem l.type [
"shadowsocks"
"socks"
]
) "${prefix}: share links cannot carry tls for ${toString l.type}; set inbounds.shareLinks = false to serve it anyway")
(mkAssertion
(
!proxyInboundsEnabled
|| !proxyInboundsCfg.shareLinks
|| !l.reality.enable
|| builtins.elem l.type [
"vless"
"trojan"
]
)
"${prefix}: share links carry reality only for vless and trojan; set inbounds.shareLinks = false to serve it anyway"
)
(mkAssertion
(
!proxyInboundsEnabled
|| !proxyInboundsCfg.shareLinks
|| !l.tls.enable
|| !builtins.elem l.type [
"shadowsocks"
"socks"
]
)
"${prefix}: share links cannot carry tls for ${toString l.type}; set inbounds.shareLinks = false to serve it anyway"
)
(exactlyOneOf (proxyInboundsEnabled && l.reality.enable) [
l.reality.privateKey
l.reality.privateKeyFile
@@ -577,19 +591,16 @@ let
(uniqueValues awgListenersEnabled awgInterfaces
"proxy-suite: AmneziaWG inbounds listeners and amneziaWg.profiles must each use a distinct interfaceName"
)
(mkAssertion (!awgListenersEnabled || !lib.any (name: builtins.elem name otherInterfaces) awgInterfaces)
(mkAssertion
(!awgListenersEnabled || !lib.any (name: builtins.elem name otherInterfaces) awgInterfaces)
"proxy-suite: an AmneziaWG inbounds listener's interfaceName is taken by proxy.tun or perAppRouting.tun"
)
(mkAssertion
(
!awgListenersEnabled
|| lib.all (
ib:
lib.all (other: ib.tag == other.tag || !ipv4Overlap ib.subnet other.subnet) awgSubnets
) awgSubnets
)
"proxy-suite: AmneziaWG inbounds listeners must each use a subnet of their own"
)
(mkAssertion (
!awgListenersEnabled
|| lib.all (
ib: lib.all (other: ib.tag == other.tag || !ipv4Overlap ib.subnet other.subnet) awgSubnets
) awgSubnets
) "proxy-suite: AmneziaWG inbounds listeners must each use a subnet of their own")
(mkAssertion
(
!awgListenersEnabled
@@ -644,18 +655,18 @@ let
];
in
lib.optionals (proxyInboundsEnabled && l.type == "amneziawg") [
(mkAssertion (lib.all (user: user.name != "") l.users)
"${prefix}: AmneziaWG users each need a name, which their keys and address are kept under"
(mkAssertion (lib.all (user: user.name != "")
l.users
) "${prefix}: AmneziaWG users each need a name, which their keys and address are kept under")
(mkAssertion (builtins.stringLength awg.interfaceName <= 15)
"${prefix}: amneziaWg.interfaceName '${awg.interfaceName}' is longer than the kernel's 15 characters"
)
(mkAssertion (
builtins.stringLength awg.interfaceName <= 15
) "${prefix}: amneziaWg.interfaceName '${awg.interfaceName}' is longer than the kernel's 15 characters")
(mkAssertion (
!l.tls.enable && !l.reality.enable && l.flow == null && l.transport.type == "raw"
) "${prefix}: AmneziaWG takes no tls, reality, flow or transport")
(mkAssertion (subnet != null && subnet.size >= 4)
"${prefix}: amneziaWg.subnet '${awg.subnet}' must be an IPv4 CIDR of /30 or wider"
)
(mkAssertion (
subnet != null && subnet.size >= 4
) "${prefix}: amneziaWg.subnet '${awg.subnet}' must be an IPv4 CIDR of /30 or wider")
(mkAssertion (subnet == null || lib.all inSubnet addresses)
"${prefix}: each user address must be a host address inside amneziaWg.subnet, other than its first (this host's)"
)
@@ -931,7 +942,8 @@ let
];
torCfg = cfg.tor;
torOnionListeners = if torCfg.onionService.listeners == null then [ ] else torCfg.onionService.listeners;
torOnionListeners =
if torCfg.onionService.listeners == null then [ ] else torCfg.onionService.listeners;
torOnionUnfit = map (ib: ib.tag) (
builtins.filter (ib: !derived.proxyInboundOnionCapable ib) derived.torOnionInbounds
);
@@ -940,14 +952,26 @@ let
) derived.torOnionInbounds;
torSnowflake = lib.any (line: lib.hasPrefix "snowflake " line) torCfg.bridges.lines;
torAssertions = [
(mkAssertion (!torCfg.enable || torCfg.asOutbound || torCfg.onionService.enable)
"proxy-suite: tor.enable = true needs tor.asOutbound or tor.onionService.enable"
)
(requireEnabled (torCfg.enable && torCfg.asOutbound) proxyEnabled
"proxy-suite: tor.asOutbound requires proxy.enable = true"
)
(requireEnabled (torCfg.enable && torCfg.upstream == "proxy") proxyEnabled
''proxy-suite: tor.upstream = "proxy" requires proxy.enable = true''
(mkAssertion (
!torCfg.enable || torCfg.asOutbound || torCfg.onionService.enable
) "proxy-suite: tor.enable = true needs tor.asOutbound or tor.onionService.enable")
(requireEnabled (
torCfg.enable && torCfg.asOutbound
) proxyEnabled "proxy-suite: tor.asOutbound requires proxy.enable = true")
(requireEnabled (
torCfg.enable && torCfg.upstream == "proxy"
) proxyEnabled ''proxy-suite: tor.upstream = "proxy" requires proxy.enable = true'')
# Tor as the one outbound would be what the local proxy dials Tor's own relays through.
(mkAssertion
(
!(
derived.torOutboundEnabled
&& torCfg.upstream == "proxy"
&& lib.subtractLists [ derived.torOutboundTag ] effectiveOutboundTags == [ ]
&& !derived.hasSubscriptions
)
)
''proxy-suite: tor.upstream = "proxy" needs an outbound besides "tor" to reach Tor through; with tor the only one, Tor would dial its relays through itself''
)
(mkAssertion (!(torCfg.enable && torCfg.upstream == "proxy" && torSnowflake))
''proxy-suite: tor.bridges.lines has a snowflake bridge, which cannot follow tor.upstream = "proxy"; use obfs4, webtunnel or meek_lite bridges, or upstream = "direct"''
@@ -955,17 +979,20 @@ let
(mkAssertion (!(derived.torOutboundEnabled && builtins.elem derived.torOutboundTag outboundTags))
"proxy-suite: the outbound tag \"tor\" belongs to tor.asOutbound; rename the proxy.outbounds entry"
)
(requireEnabled (torCfg.enable && torCfg.onionService.enable) cfg.inbounds.enable
"proxy-suite: tor.onionService.enable requires inbounds.enable = true"
)
(mkAssertion (
!derived.torOnionEnabled
|| builtins.all (tag: builtins.hasAttr tag cfg.inbounds.listeners) torOnionListeners
) "proxy-suite: tor.onionService.listeners names listeners not in inbounds.listeners: ${
lib.concatStringsSep ", " (
builtins.filter (tag: !builtins.hasAttr tag cfg.inbounds.listeners) torOnionListeners
(requireEnabled (
torCfg.enable && torCfg.onionService.enable
) cfg.inbounds.enable "proxy-suite: tor.onionService.enable requires inbounds.enable = true")
(mkAssertion
(
!derived.torOnionEnabled
|| builtins.all (tag: builtins.hasAttr tag cfg.inbounds.listeners) torOnionListeners
)
}")
"proxy-suite: tor.onionService.listeners names listeners not in inbounds.listeners: ${
lib.concatStringsSep ", " (
builtins.filter (tag: !builtins.hasAttr tag cfg.inbounds.listeners) torOnionListeners
)
}"
)
(mkAssertion (!derived.torOnionEnabled || derived.torOnionInbounds != [ ])
"proxy-suite: tor.onionService has no listener to serve: amneziawg, h3-only xhttp and raw JSON listeners cannot go over an onion"
)
+16 -4
View File
@@ -264,10 +264,22 @@ rec {
fwmark,
table,
}:
lib.concatMapStrings (family: ''
${mkIpRuleDeleteByFwmark { inherit ip family fwmark table; }}
${mkIpLocalDefaultRouteDelete { inherit ip family table; }}
'') [ "-4" "-6" ];
lib.concatMapStrings
(family: ''
${mkIpRuleDeleteByFwmark {
inherit
ip
family
fwmark
table
;
}}
${mkIpLocalDefaultRouteDelete { inherit ip family table; }}
'')
[
"-4"
"-6"
];
mkTproxyRoutingUp =
{
@@ -140,9 +140,7 @@ let
set -euo pipefail
${subscriptionCacheHelpersBlock}
KEEP="|${
lib.concatMapStrings (sub: "${sub.tag}|") proxyCfg.subscriptions
}"
KEEP="|${lib.concatMapStrings (sub: "${sub.tag}|") proxyCfg.subscriptions}"
while IFS=$'\t' read -r TAG _; do
[ -n "$TAG" ] || continue
KEEP="$KEEP$TAG|"
@@ -44,7 +44,11 @@ let
${builders.cidrNetworkFunction}
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
${builders.mkNftDeleteTable {
inherit nft;
family = "inet";
table = "proxy_suite_per_app_tun";
}}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-4";
@@ -57,8 +61,16 @@ let
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable {
inherit ip;
family = "-4";
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable {
inherit ip;
family = "-6";
table = perAppRoutingTun.routeTable;
}}
${nft} -f ${perAppTunChainFile}
${perAppTunWaitForInterface}
tun_addr="''${tun_cidr%%/*}"
@@ -89,7 +101,11 @@ let
set +e
# Best-effort cleanup for graceful stops and for unclean previous exits.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
${builders.mkNftDeleteTable {
inherit nft;
family = "inet";
table = "proxy_suite_per_app_tun";
}}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-4";
@@ -102,16 +118,31 @@ let
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpLinkDelete { inherit ip; interface = perAppRoutingTun.interface; }}
${builders.mkIpRouteFlushTable {
inherit ip;
family = "-4";
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable {
inherit ip;
family = "-6";
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpLinkDelete {
inherit ip;
interface = perAppRoutingTun.interface;
}}
${builders.flushResolvedCaches}
'';
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app" ''
set -euo pipefail
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tproxy"; }}
${builders.mkNftDeleteTable {
inherit nft;
family = "inet";
table = "proxy_suite_per_app_tproxy";
}}
${builders.mkTproxyRoutingDown {
inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
@@ -130,7 +161,11 @@ let
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app" ''
set +e
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tproxy"; }}
${builders.mkNftDeleteTable {
inherit nft;
family = "inet";
table = "proxy_suite_per_app_tproxy";
}}
${builders.mkTproxyRoutingDown {
inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
@@ -41,7 +41,7 @@ let
serverAddressBlock =
if proxyInboundsCfg.serverAddress != null then
''SERVER_ADDRESS=${lib.escapeShellArg proxyInboundsCfg.serverAddress}''
"SERVER_ADDRESS=${lib.escapeShellArg proxyInboundsCfg.serverAddress}"
else if proxyInboundsCfg.shareLinks then
''
${builders.mkDefaultUplinkIPv4Source {
@@ -95,9 +95,7 @@ let
''
# via outbound: ${ob.tag} (static xray json)
OB_JSON=$(cat ${
pkgs.writeText "proxy-suite-inbounds" (
builtins.toJSON (ob.xrayJson // { inherit (ob) tag; })
)
pkgs.writeText "proxy-suite-inbounds" (builtins.toJSON (ob.xrayJson // { inherit (ob) tag; }))
})
${dialerBlock}
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
+56 -19
View File
@@ -25,17 +25,23 @@ let
globalTunIPv6RoutePrefix
;
deleteXrayTunRules = lib.concatMapStrings (
family:
lib.concatMapStrings (priority: builders.mkIpRuleDeleteByPriority { inherit ip family priority; }) [
xrayTunMarkBypassRulePriority
xrayTunServiceUserRulePriority
xrayTunPerAppTunRulePriority
xrayTunDnsRulePriority
xrayTunMainRulePriority
tunAutoRouteRulePriority
]
) [ "-4" "-6" ];
deleteXrayTunRules =
lib.concatMapStrings
(
family:
lib.concatMapStrings (priority: builders.mkIpRuleDeleteByPriority { inherit ip family priority; }) [
xrayTunMarkBypassRulePriority
xrayTunServiceUserRulePriority
xrayTunPerAppTunRulePriority
xrayTunDnsRulePriority
xrayTunMainRulePriority
tunAutoRouteRulePriority
]
)
[
"-4"
"-6"
];
# Replies to connections from outside (sshd, a game server, anything listening) take
# proxyMark, so the fwmark rule sends them back out the way they came instead of into
@@ -119,7 +125,11 @@ in
# Start from a clean policy-routing state. `ip rule add` permits duplicate
# rules on some iproute2 versions, and a stale rule can keep packets routed
# into a dead local table after a failed restart.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "singbox"; }}
${builders.mkNftDeleteTable {
inherit nft;
family = "inet";
table = "singbox";
}}
${builders.mkTproxyRoutingDown {
inherit ip;
fwmark = globalTproxy.fwmark;
@@ -138,7 +148,11 @@ in
tproxyDownScript = pkgs.writeShellScript "proxy-suite-routing" ''
set +e
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "singbox"; }}
${builders.mkNftDeleteTable {
inherit nft;
family = "inet";
table = "singbox";
}}
${builders.mkTproxyRoutingDown {
inherit ip;
fwmark = globalTproxy.fwmark;
@@ -152,14 +166,37 @@ in
# SingBox normally removes these on graceful shutdown, but stale
# auto_route/auto_redirect state leaves the host routing through a dead TUN
# interface after `proxy-ctl proxy tun off` or an unclean service stop.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkNftDeleteTable {
inherit nft;
family = "inet";
table = "sing-box";
}}
${builders.mkIpRuleDeleteByTable {
inherit ip;
family = "-4";
table = tunAutoRouteTableIndex;
}}
${builders.mkIpRuleDeleteByTable {
inherit ip;
family = "-6";
table = tunAutoRouteTableIndex;
}}
${deleteXrayTunRules}
${deleteXrayTunReplyTable}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }}
${builders.mkIpRouteFlushTable {
inherit ip;
family = "-4";
table = tunAutoRouteTableIndex;
}}
${builders.mkIpRouteFlushTable {
inherit ip;
family = "-6";
table = tunAutoRouteTableIndex;
}}
${builders.mkIpLinkDelete {
inherit ip;
interface = globalTun.interface;
}}
${builders.flushResolvedCaches}
'';
}
@@ -25,13 +25,17 @@ lib.optionalString hybridEnabled ''
local batch
batch=$(${jq} -c \
--argjson base "$XRAY_SIDECAR_NEXT_PORT" \
--argjson mark ${if xraySidecarRoutingMark == null then "null" else 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
${lib.optionalString (xraySidecarRoutingMark != null) "| .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}]}},
@@ -163,7 +163,9 @@ let
_proxy_suite_parse_xray_url() {
${parse "--backend xray" (
lib.optionalString (xraySidecarRoutingMark != null) " --routing-mark ${toString xraySidecarRoutingMark}"
lib.optionalString (
xraySidecarRoutingMark != null
) " --routing-mark ${toString xraySidecarRoutingMark}"
)}
}
''
@@ -238,7 +240,11 @@ let
singBoxRawOutboundJson =
ob: tag: routingMark:
ob.singBoxJson // { inherit tag; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; };
ob.singBoxJson
// {
inherit tag;
}
// lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; };
mkHybridOutboundBlock =
ob: routingMark: tag:
@@ -435,7 +441,10 @@ let
# Declared detours, resolved once every outbound - subscription entries included - exists.
detourMap =
entries: lib.listToAttrs (map (e: lib.nameValuePair e.tag e.detour) (lib.filter (e: e.detour != null) entries));
entries:
lib.listToAttrs (
map (e: lib.nameValuePair e.tag e.detour) (lib.filter (e: e.detour != null) entries)
);
detours = {
outbounds = detourMap proxyCfg.outbounds;
subscriptions = detourMap proxyCfg.subscriptions;
@@ -645,9 +654,7 @@ let
# Real exits for autoProxy, taken after the wrapper may have renamed one to
# "proxy".
exitTagsBlock = ''
EXIT_TAGS_JSON=$(${jq} -c '[.[] | select(.type != "selector" and .type != "urltest"${
lib.optionalString torOutboundEnabled " and (.tag | ltrimstr(\"proxy-suite-ob-\")) != \"tor\""
}) | .tag]' <<< "$OUTBOUNDS_JSON")
EXIT_TAGS_JSON=$(${jq} -c '[.[] | select(.type != "selector" and .type != "urltest"${lib.optionalString torOutboundEnabled " and (.tag | ltrimstr(\"proxy-suite-ob-\")) != \"tor\""}) | .tag]' <<< "$OUTBOUNDS_JSON")
'';
in
mkUrlOutboundHelpersBlock routingMark
@@ -25,11 +25,7 @@ let
subscriptionCacheDir = "${stateDir}/subscriptions/${backend}";
mkSubscriptionUrlSource =
sub:
if sub.urlFile != null then
sub.urlFile
else
pkgs.writeText "proxy-suite-core" sub.url;
sub: if sub.urlFile != null then sub.urlFile else pkgs.writeText "proxy-suite-core" sub.url;
# Defined in every script that touches a cache: the start scripts and the
# update unit.
@@ -145,14 +141,10 @@ let
}
'';
mkSubscriptionBlock =
sub: _routingMark:
''
# subscription: ${sub.tag}
_proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${
lib.escapeShellArg (mkSubscriptionUrlSource sub)
}
'';
mkSubscriptionBlock = sub: _routingMark: ''
# subscription: ${sub.tag}
_proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}
'';
runtimeSubscriptionsBlock = ''
# subscriptions added at runtime
@@ -162,17 +154,13 @@ let
done < <(_proxy_suite_runtime_subscriptions)
'';
mkSubscriptionFetchBlock =
sub:
''
if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${
lib.escapeShellArg (mkSubscriptionUrlSource sub)
}; then
echo "Updated subscription: ${sub.tag}"
else
FAILED=1
fi
'';
mkSubscriptionFetchBlock = sub: ''
if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${lib.escapeShellArg (mkSubscriptionUrlSource sub)}; then
echo "Updated subscription: ${sub.tag}"
else
FAILED=1
fi
'';
runtimeSubscriptionsFetchBlock = ''
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
+1 -1
View File
@@ -34,7 +34,7 @@ let
)
${lib.optionalString (s.server.port != 22) "args+=(-p ${toString s.server.port})"}
${lib.optionalString (s.identityFile != null) ''args+=(-i "$CREDENTIALS_DIRECTORY/identity")''}
${lib.optionalString (knownHosts != null) ''args+=(-o UserKnownHostsFile=${knownHosts})''}
${lib.optionalString (knownHosts != null) "args+=(-o UserKnownHostsFile=${knownHosts})"}
${extraArgs}
exec ${pkgs.openssh}/bin/ssh "''${args[@]}" ${lib.escapeShellArg destination}
'';
+22 -22
View File
@@ -80,12 +80,7 @@ let
"ControlSocketsGroupWritable 1"
]
++ lib.optional t.clientOnly "ClientOnly 1"
++ (
if t.asOutbound then
[ "SocksPort 127.0.0.1:${toString t.socksPort}" ]
else
[ "SocksPort 0" ]
)
++ (if t.asOutbound then [ "SocksPort 127.0.0.1:${toString t.socksPort}" ] else [ "SocksPort 0" ])
++ lib.optionals bridgesEnabled [
"UseBridges 1"
"ClientTransportPlugin obfs4,webtunnel,meek_lite exec ${t.lyrebirdPackage}/bin/lyrebird"
@@ -104,6 +99,22 @@ let
-g ${lib.escapeShellArg cfg.userControl.group} "$dir"
'';
# Before ExecStart, which is when proxy-suite-inbounds may start reading the hostname: a
# stale one must be gone by then.
onionKeyScript = pkgs.writeShellScript "proxy-suite-tor-onion-key" ''
set -euo pipefail
umask 0077
# Tor wants the service directory private to it.
${pkgs.coreutils}/bin/install -d -m 0700 "$STATE_DIRECTORY/onion"
if ! ${pkgs.diffutils}/bin/cmp -s "$CREDENTIALS_DIRECTORY/onion-secret-key" "$STATE_DIRECTORY/onion/hs_ed25519_secret_key"; then
# Another key: the old address and its public key must not be served with it.
${pkgs.coreutils}/bin/rm -f "$STATE_DIRECTORY/onion/hs_ed25519_public_key" "$STATE_DIRECTORY/onion/hostname"
${pkgs.coreutils}/bin/install -m 0600 "$CREDENTIALS_DIRECTORY/onion-secret-key" \
"$STATE_DIRECTORY/onion/hs_ed25519_secret_key"
fi
'';
onionKeyEnabled = derived.torOnionEnabled && t.onionService.secretKeyFile != null;
startScript = pkgs.writeShellScript "proxy-suite-tor" ''
set -euo pipefail
umask 0077
@@ -133,17 +144,6 @@ let
cat ${pkgs.writeText "proxy-suite-torrc-extra" t.extraConfig}
} > "$torrc"
${lib.optionalString (derived.torOnionEnabled && t.onionService.secretKeyFile != null) ''
# Tor wants the service directory private to it.
${pkgs.coreutils}/bin/install -d -m 0700 "$STATE_DIRECTORY/onion"
if ! ${pkgs.diffutils}/bin/cmp -s "$CREDENTIALS_DIRECTORY/onion-secret-key" "$STATE_DIRECTORY/onion/hs_ed25519_secret_key"; then
# Another key: the old address and its public key must not be served with it.
${pkgs.coreutils}/bin/rm -f "$STATE_DIRECTORY/onion/hs_ed25519_public_key" "$STATE_DIRECTORY/onion/hostname"
${pkgs.coreutils}/bin/install -m 0600 "$CREDENTIALS_DIRECTORY/onion-secret-key" \
"$STATE_DIRECTORY/onion/hs_ed25519_secret_key"
fi
''}
exec ${t.package}/bin/tor -f "$torrc"
'';
in
@@ -171,15 +171,15 @@ in
LoadCredential =
lib.optional withProxyAuth "proxy-password:${passwordSource}"
++ lib.optional (t.bridges.file != null) "bridges:${t.bridges.file}"
++ lib.optional (
derived.torOnionEnabled && t.onionService.secretKeyFile != null
) "onion-secret-key:${t.onionService.secretKeyFile}";
++ lib.optional onionKeyEnabled "onion-secret-key:${t.onionService.secretKeyFile}";
Restart = "always";
RestartSec = 5;
LimitNOFILE = 65536;
}
// lib.optionalAttrs controlGroup {
ExecStartPre = "+${controlDirScript}";
// lib.optionalAttrs (controlGroup || onionKeyEnabled) {
ExecStartPre =
lib.optional controlGroup "+${controlDirScript}"
++ lib.optional onionKeyEnabled "${onionKeyScript}";
};
};
}
+14 -2
View File
@@ -85,7 +85,17 @@ let
}
'';
inherit (import ./wg-tunnel.nix { inherit lib pkgs cfg derived; }) mkTunnel;
inherit
(import ./wg-tunnel.nix {
inherit
lib
pkgs
cfg
derived
;
})
mkTunnel
;
viaAmneziaWg = builtins.elem w.asOutbound [
"userspace"
"interface"
@@ -135,7 +145,9 @@ in
StateDirectoryMode = "0700";
WorkingDirectory = "${derived.constants.stateDir}/warp";
UMask = "0077";
LoadCredential = lib.optional (cfg.proxy.enable && withProxyAuth) "proxy-password:${passwordSource}";
LoadCredential = lib.optional (
cfg.proxy.enable && withProxyAuth
) "proxy-password:${passwordSource}";
ExecStart = registerScript;
};
};
+8 -26
View File
@@ -50,45 +50,27 @@ let
discord = [ "discord-voice" ];
};
expandDefaultDomains =
groups:
lib.unique (
lib.concatMap (group: domainGroups.${group}) groups
);
expandDefaultDomains = groups: lib.unique (lib.concatMap (group: domainGroups.${group}) groups);
expandDefaultIps =
groups:
lib.unique (
lib.concatMap (group: ipGroups.${group}) groups
);
expandDefaultIps = groups: lib.unique (lib.concatMap (group: ipGroups.${group}) groups);
inferPresets =
groups:
lib.unique (map (group: groupPresets.${group}) groups);
inferPresets = groups: lib.unique (map (group: groupPresets.${group}) groups);
effectiveRuleDomains =
rule:
lib.unique (expandDefaultDomains rule.defaultDomains ++ rule.domains);
effectiveRuleDomains = rule: lib.unique (expandDefaultDomains rule.defaultDomains ++ rule.domains);
effectiveRuleIps =
rule:
lib.unique (expandDefaultIps rule.defaultIps ++ rule.ips);
effectiveRuleIps = rule: lib.unique (expandDefaultIps rule.defaultIps ++ rule.ips);
effectiveRulePresets =
rule:
if rule.preset != null then [ rule.preset ] else inferPresets rule.defaultDomains;
rule: if rule.preset != null then [ rule.preset ] else inferPresets rule.defaultDomains;
effectiveRuleIpsetFamilies =
rule:
lib.optional (effectiveRuleIps rule != [ ]) "all";
effectiveRuleIpsetFamilies = rule: lib.optional (effectiveRuleIps rule != [ ]) "all";
effectiveRuleProtocolFamilies =
rule:
lib.optionals (rule.configName != null) (
lib.unique (
lib.concatMap (
group:
if builtins.hasAttr group protocolGroups then protocolGroups.${group} else [ ]
group: if builtins.hasAttr group protocolGroups then protocolGroups.${group} else [ ]
) rule.defaultDomains
)
);
+7 -3
View File
@@ -63,9 +63,13 @@ let
profiles = [
# Its first UDP strategy's fake has no blob, which zapret2 rejects on every
# packet; nfqws1's default for unknown UDP was 64 zero bytes.
(replaceStrings [ "--lua-desync=fake:repeats=6:strategy=1" ] [
"--lua-desync=fake:blob=0x${lib.fixedWidthString 128 "0" ""}:repeats=6:strategy=1"
] (args "NFQWS_ARGS_UDP"))
(replaceStrings
[ "--lua-desync=fake:repeats=6:strategy=1" ]
[
"--lua-desync=fake:blob=0x${lib.fixedWidthString 128 "0" ""}:repeats=6:strategy=1"
]
(args "NFQWS_ARGS_UDP")
)
"${args "NFQWS_ARGS_QUIC"} <HOSTLIST_NOAUTO> ${lists}"
"${withSniPick (args "NFQWS_ARGS")} <HOSTLIST> ${lists}"
];
+14 -7
View File
@@ -207,8 +207,11 @@ in
awgOnly.config.environment.systemPackages;
assert builtins.elem awgOnly.config.services.proxy-suite.amneziaWg.userspacePackage
awgOnly.config.environment.systemPackages;
assert pkgs.lib.versionAtLeast awgOnly.config.services.proxy-suite.amneziaWg.toolsPackage.version "3.1";
assert pkgs.lib.versionAtLeast awgOnly.config.services.proxy-suite.amneziaWg.userspacePackage.version "3.1";
assert pkgs.lib.versionAtLeast awgOnly.config.services.proxy-suite.amneziaWg.toolsPackage.version
"3.1";
assert pkgs.lib.versionAtLeast
awgOnly.config.services.proxy-suite.amneziaWg.userspacePackage.version
"3.1";
assert pkgs.lib.hasInfix "cmd_awg" ctl.script;
assert
ctl.awgProfiles == [
@@ -218,11 +221,15 @@ in
true
)
(
assert pkgs.lib.versionAtLeast defaultPackages.config.services.proxy-suite.amneziaWg.toolsPackage.version "3.1";
assert
pkgs.lib.versionAtLeast defaultPackages.config.services.proxy-suite.amneziaWg.userspacePackage.version "3.1";
assert
pkgs.lib.versionAtLeast defaultPackages.config.services.proxy-suite.amneziaWg.kernelModulePackage.version "3.1";
assert pkgs.lib.versionAtLeast
defaultPackages.config.services.proxy-suite.amneziaWg.toolsPackage.version
"3.1";
assert pkgs.lib.versionAtLeast
defaultPackages.config.services.proxy-suite.amneziaWg.userspacePackage.version
"3.1";
assert pkgs.lib.versionAtLeast
defaultPackages.config.services.proxy-suite.amneziaWg.kernelModulePackage.version
"3.1";
true
)
(
+64 -44
View File
@@ -11,7 +11,9 @@
let
generated = import ./read-generated.nix;
startScript =
fixture: generated.readDerivation fixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart;
fixture:
generated.readDerivation
fixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart;
chained = evalProxySuite [
baseModule
@@ -70,9 +72,13 @@ in
assertions = [
# Detours are resolved at start, once subscription and runtime entries exist.
(
assert pkgs.lib.hasInfix ''{"outbounds":{"exit":"primary"},"subscriptions":{"sub":"primary"}}'' (startScript chained);
assert pkgs.lib.hasInfix ''{"outbounds":{"exit":"primary"},"subscriptions":{"sub":"primary"}}'' (
startScript chained
);
assert pkgs.lib.hasInfix "proxy-suite-outbound-detours" (startScript chained);
assert pkgs.lib.hasInfix ''/var/lib/proxy-suite/outbounds.d/$RUNTIME_OB_TAG.detour'' (startScript chained);
assert pkgs.lib.hasInfix "/var/lib/proxy-suite/outbounds.d/$RUNTIME_OB_TAG.detour" (
startScript chained
);
true
)
@@ -85,51 +91,52 @@ in
]);
in
assert pkgs.lib.hasInfix ''--argjson ex '["primary"]' '' script;
assert pkgs.lib.hasInfix ''excluded: ($tags - $selectable)'' script;
assert pkgs.lib.hasInfix "excluded: ($tags - $selectable)" script;
true
)
# An inbound pinned to a chained outbound gets the whole chain.
(
let
script = generated.readDerivation
(evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
script =
generated.readDerivation
(evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
outbounds = [
{
tag = "hop";
url = "http://hop.example.com:8080";
}
{
tag = "exit";
url = "http://exit.example.com:8080";
detour = "hop";
}
];
};
inbounds = {
enable = true;
serverAddress = "203.0.113.1";
listeners.main = {
type = "socks";
port = 1081;
via = "exit";
users = [
proxy = {
enable = true;
outbounds = [
{
name = "a";
password = "b";
tag = "hop";
url = "http://hop.example.com:8080";
}
{
tag = "exit";
url = "http://exit.example.com:8080";
detour = "hop";
}
];
};
inbounds = {
enable = true;
serverAddress = "203.0.113.1";
listeners.main = {
type = "socks";
port = 1081;
via = "exit";
users = [
{
name = "a";
password = "b";
}
];
};
};
};
};
}
]).config.systemd.services."proxy-suite-inbounds".serviceConfig.ExecStart;
}
]).config.systemd.services."proxy-suite-inbounds".serviceConfig.ExecStart;
in
assert pkgs.lib.hasInfix "# via outbound: hop" script;
assert pkgs.lib.hasInfix "--arg hop hop '.streamSettings.sockopt.dialerProxy = $hop'" script;
@@ -138,12 +145,20 @@ in
# User rules first, fake IP last and only for what comes through the TUN.
(
assert builtins.head tunDns.rules == { domain_suffix = [ "corp.example" ]; server = "corp"; };
assert pkgs.lib.last tunDns.rules == {
inbound = [ "tun-in" ];
query_type = [ "A" "AAAA" ];
server = "fakeip";
};
assert
builtins.head tunDns.rules == {
domain_suffix = [ "corp.example" ];
server = "corp";
};
assert
pkgs.lib.last tunDns.rules == {
inbound = [ "tun-in" ];
query_type = [
"A"
"AAAA"
];
server = "fakeip";
};
assert builtins.any (s: s.tag == "fakeip") tunDns.servers;
assert builtins.any (s: s.tag == "corp") tunDns.servers;
assert tunDns.strategy == "ipv4_only";
@@ -151,7 +166,8 @@ in
)
# Fake addresses survive a restart, one cache per TUN config.
(
assert (mkTunConfig dnsFixture).experimental.cache_file.path == "/var/lib/proxy-suite/fakeip/tun.db";
assert
(mkTunConfig dnsFixture).experimental.cache_file.path == "/var/lib/proxy-suite/fakeip/tun.db";
assert (mkTunConfig dnsFixture).experimental.cache_file.store_fakeip;
true
)
@@ -209,7 +225,11 @@ in
(
assert !(builtins.any (s: s.tag == "fakeip") tproxyDns.servers);
assert !((mkTProxyConfig dnsFixture).experimental ? cache_file);
assert builtins.head tproxyDns.rules == { domain_suffix = [ "corp.example" ]; server = "corp"; };
assert
builtins.head tproxyDns.rules == {
domain_suffix = [ "corp.example" ];
server = "corp";
};
true
)
]
+26 -8
View File
@@ -74,20 +74,29 @@ in
# IPv6 goes through the same port on ::1; without it IPv6 is left alone.
(
let
tproxyTags = config: map (inbound: inbound.tag) (builtins.filter (inbound: inbound.type == "tproxy") config.inbounds);
tproxyTags =
config:
map (inbound: inbound.tag) (builtins.filter (inbound: inbound.type == "tproxy") config.inbounds);
in
assert pkgs.lib.hasInfix "delete table inet singbox" tproxyManualStartScript;
assert pkgs.lib.hasInfix "-6 route replace local default dev lo table 100" tproxyManualStartScript;
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" tproxyManualNftRules;
assert pkgs.lib.hasInfix "meta l4proto { tcp, udp } tproxy ip6 to [::1]:1085 meta mark set 1" tproxyManualNftRules;
assert tproxyTags tproxyManualConfig == [ "tproxy-in" "tproxy-in6" ];
assert pkgs.lib.hasInfix "meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:1085 meta mark set 1"
tproxyManualNftRules;
assert pkgs.lib.hasInfix "meta l4proto { tcp, udp } tproxy ip6 to [::1]:1085 meta mark set 1"
tproxyManualNftRules;
assert
tproxyTags tproxyManualConfig == [
"tproxy-in"
"tproxy-in6"
];
assert !(pkgs.lib.hasInfix "-6 rule add" 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 ipv4 meta l4proto { tcp, udp } meta mark set 1"
tproxyIPv4OnlyNftRules;
assert tproxyTags tproxyIPv4OnlyConfig == [ "tproxy-in" ];
true
)
@@ -95,10 +104,19 @@ in
# family. Off, they stay IPv4-only and wrapped apps' IPv6 is unreachable.
(
let
tunAddress = config: (builtins.head (builtins.filter (inbound: inbound.type or "" == "tun") config.inbounds)).address;
xrayGateway = config: (builtins.head (builtins.filter (inbound: inbound.protocol or "" == "tun") config.inbounds)).settings.gateway;
tunAddress =
config:
(builtins.head (builtins.filter (inbound: inbound.type or "" == "tun") config.inbounds)).address;
xrayGateway =
config:
(builtins.head (builtins.filter (inbound: inbound.protocol or "" == "tun") config.inbounds))
.settings.gateway;
in
assert tunAddress tunDefaultConfig == [ "172.19.0.1/30" checkConstants.globalTunIPv6Address ];
assert
tunAddress tunDefaultConfig == [
"172.19.0.1/30"
checkConstants.globalTunIPv6Address
];
assert tunAddress ipv4OnlyTunConfig == [ "172.19.0.1/30" ];
assert pkgs.lib.hasInfix "-6 route replace unreachable default table 101" ipv4OnlyPerAppTunUpScript;
assert !(pkgs.lib.hasInfix "-6 addr replace" ipv4OnlyPerAppTunUpScript);
+9 -6
View File
@@ -59,13 +59,15 @@ let
};
}
];
tproxyIPv4OnlyStartScript = generated.readDerivation
tproxyIPv4OnlyFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig.ExecStart;
tproxyIPv4OnlyStartScript =
generated.readDerivation
tproxyIPv4OnlyFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig.ExecStart;
tproxyIPv4OnlyConfig = mkTProxyConfig tproxyIPv4OnlyFixture;
tproxyIPv4OnlyNftRules = mkTProxyNftRules tproxyIPv4OnlyFixture;
ipv4OnlyTunConfig = mkTunConfig tproxyIPv4OnlyFixture;
ipv4OnlyPerAppTunUpScript = generated.readDerivation
tproxyIPv4OnlyFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStartPost;
ipv4OnlyPerAppTunUpScript =
generated.readDerivation
tproxyIPv4OnlyFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStartPost;
# XRay's TUN configures IPv6 itself: with it off, its up script must not touch IPv6 addresses.
xrayIPv4OnlyFixture = evalProxySuite [
@@ -82,8 +84,9 @@ let
)
];
xrayIPv4OnlyTunConfig = mkTunConfig xrayIPv4OnlyFixture;
xrayIPv4OnlyTunUpScript = generated.readDerivation
xrayIPv4OnlyFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStartPost;
xrayIPv4OnlyTunUpScript =
generated.readDerivation
xrayIPv4OnlyFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStartPost;
tproxyAutostartFixture = evalProxySuite [
baseModule
+4 -2
View File
@@ -67,11 +67,13 @@ in
in
assert guiFixture.config.security.polkit.enable;
# nixpkgs 26.11+: no setuid pkexec unless asked for, and without it pkexec refuses to run.
assert guiFixture.config.security.wrappers ? pkexec && guiFixture.config.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;
assert
builtins.match ".*AUTH_ADMIN_KEEP.*" tuiOffFixture.config.security.polkit.extraConfig == null;
true
)
(
+2 -1
View File
@@ -92,7 +92,8 @@ in
assert pkgs.lib.hasInfix "--backend xray" hybridStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript;
assert pkgs.lib.hasInfix "hybrid XRay json sidecar" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix ''{type: "socks", tag: $tag, server: "127.0.0.1"'' hybridXrayRawStartScript;
assert pkgs.lib.hasInfix ''{type: "socks", tag: $tag, server: "127.0.0.1"''
hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "udp: true" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "{routing_mark: 2}" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "sing_box_preserved_rules" hybridBackendJqFilter;
+2 -1
View File
@@ -108,7 +108,8 @@ in
assert pkgs.lib.hasInfix ''chgrp proxy-suite-daemon "$backend_config"'' localProxyAuthStartScript;
assert pkgs.lib.hasInfix ''chmod 640 "$backend_config"'' localProxyAuthStartScript;
# The backend itself runs unprivileged.
assert pkgs.lib.hasInfix "setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon" localProxyAuthStartScript;
assert pkgs.lib.hasInfix "setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon"
localProxyAuthStartScript;
true
)
+1 -2
View File
@@ -100,8 +100,7 @@ in
(
assert pkgs.lib.hasInfix "Usage: proxy-ctl <group>" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "local proxy backend" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "restart active services"
perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "restart active services" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "apps run <profile> -- <cmd>" perAppRoutingProxychainsScript;
assert pkgs.lib.hasInfix "apps" perAppRoutingProxychainsScript;
true
+18 -10
View File
@@ -31,12 +31,13 @@ let
perAppRoutingTproxyUserStartScript = generated.readDerivation (
(mkPerAppUserRules perAppRoutingTproxyFixture).perAppTproxyUserRuleStart
);
perAppRoutingTproxyNftRules = generated.readDerivation
(import ../../modules/proxy-suite/nftables.nix {
inherit (pkgs) lib;
inherit pkgs;
cfg = perAppRoutingTproxyFixture.config.services.proxy-suite;
}).perAppTproxyRulesFile;
perAppRoutingTproxyNftRules =
generated.readDerivation
(import ../../modules/proxy-suite/nftables.nix {
inherit (pkgs) lib;
inherit pkgs;
cfg = perAppRoutingTproxyFixture.config.services.proxy-suite;
}).perAppTproxyRulesFile;
in
{
assertions = [
@@ -67,7 +68,8 @@ in
# -- 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" perAppRoutingTproxyUserStartScript;
assert pkgs.lib.hasInfix "add rule inet proxy_suite_per_app_tproxy output"
perAppRoutingTproxyUserStartScript;
assert pkgs.lib.hasInfix "meta mark set" perAppRoutingTproxyUserStartScript;
assert pkgs.lib.hasInfix "ct mark set" perAppRoutingTproxyUserStartScript;
true
@@ -78,7 +80,11 @@ in
(
let
inherit (pkgs.lib) hasInfix splitString;
guardedBeforeMark = chain: hasInfix "ct direction reply return" (builtins.head (splitString "ct mark 17 meta mark set 17" chain));
guardedBeforeMark =
chain:
hasInfix "ct direction reply return" (
builtins.head (splitString "ct mark 17 meta mark set 17" chain)
);
chains = splitString "chain output" perAppRoutingTproxyNftRules;
in
assert guardedBeforeMark (builtins.elemAt chains 0);
@@ -90,8 +96,10 @@ in
# -- perAppRouting: app TProxy startup installs nftables and loopback policy route --
(
assert pkgs.lib.hasInfix "delete table inet proxy_suite_per_app_tproxy" perAppRoutingTproxyStartScript;
assert pkgs.lib.hasInfix "-6 route replace local default dev lo table 102" perAppRoutingTproxyStartScript;
assert pkgs.lib.hasInfix "delete table inet proxy_suite_per_app_tproxy"
perAppRoutingTproxyStartScript;
assert pkgs.lib.hasInfix "-6 route replace local default dev lo table 102"
perAppRoutingTproxyStartScript;
assert pkgs.lib.hasInfix "-6 rule add fwmark 17 table 102" perAppRoutingTproxyStartScript;
assert pkgs.lib.hasInfix "-6 rule del fwmark 17 table 102" perAppRoutingTproxyStopScript;
assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStartScript;
+17 -10
View File
@@ -38,12 +38,13 @@ let
perAppRoutingTunUserStartScript = generated.readDerivation (
(mkPerAppUserRules perAppRoutingTunFixture).perAppTunUserRuleStart
);
perAppRoutingTunNftRules = generated.readDerivation
(import ../../modules/proxy-suite/nftables.nix {
inherit (pkgs) lib;
inherit pkgs;
cfg = perAppRoutingTunFixture.config.services.proxy-suite;
}).perAppTunChainFile;
perAppRoutingTunNftRules =
generated.readDerivation
(import ../../modules/proxy-suite/nftables.nix {
inherit (pkgs) lib;
inherit pkgs;
cfg = perAppRoutingTunFixture.config.services.proxy-suite;
}).perAppTunChainFile;
perAppRoutingTunWithTproxyFixture = evalProxySuite [
baseModule
@@ -98,7 +99,11 @@ in
);
in
assert inbound.interface_name == "psperapptun0";
assert inbound.address == [ "172.20.0.1/30" "fd66:20::1/64" ];
assert
inbound.address == [
"172.20.0.1/30"
"fd66:20::1/64"
];
assert inbound.auto_route == false;
assert inbound.auto_redirect == false;
assert inbound.strict_route == false;
@@ -147,7 +152,8 @@ in
assert perAppRoutingTunServiceConfig.ExecStartPre == perAppRoutingTunServiceConfig.ExecStopPost;
# With proxy.ipv6, wrapped apps' IPv6 goes through the app TUN too.
assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev psperapptun0'' perAppRoutingTunUpScript;
assert pkgs.lib.hasInfix "-6 route replace default dev psperapptun0 table 101" perAppRoutingTunUpScript;
assert pkgs.lib.hasInfix "-6 route replace default dev psperapptun0 table 101"
perAppRoutingTunUpScript;
assert !(pkgs.lib.hasInfix "unreachable" perAppRoutingTunUpScript);
assert pkgs.lib.hasInfix "-6 rule add fwmark 16 table 101" perAppRoutingTunUpScript;
assert pkgs.lib.hasInfix "-6 route flush table 101" perAppRoutingTunCleanupScript;
@@ -160,8 +166,9 @@ in
# -- perAppRouting: wrapped apps' replies to incoming connections skip the mark (and the
# user rule appended after it), so they leave directly --
(
assert pkgs.lib.hasInfix "ct direction reply return"
(builtins.head (pkgs.lib.splitString "ct mark 16 meta mark set 16" perAppRoutingTunNftRules));
assert pkgs.lib.hasInfix "ct direction reply return" (
builtins.head (pkgs.lib.splitString "ct mark 16 meta mark set 16" perAppRoutingTunNftRules)
);
true
)
+3 -4
View File
@@ -190,12 +190,11 @@ in
perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "proxy-suite-per-app-zapret";
assert
perAppRoutingZapretWithoutGlobalFixture.config.systemd.services
? "proxy-suite-per-app-zapret-user@";
? "proxy-suite-per-app-zapret-user@";
assert
perAppRoutingZapretWithoutGlobalFixture.config.systemd.user.services
? "proxy-suite-per-app-zapret-anchor";
assert
!(perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "proxy-suite-zapret");
? "proxy-suite-per-app-zapret-anchor";
assert !(perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "proxy-suite-zapret");
assert builtins.length perAppRoutingZapretWithoutGlobalProfiles == 2;
assert builtins.any (
profile: profile.name == "zapret" && profile.route == "zapret"
+258 -90
View File
@@ -27,7 +27,12 @@ let
inbounds:
evalProxySuite [
baseModule
{ services.proxy-suite.inbounds = { enable = true; } // inbounds; }
{
services.proxy-suite.inbounds = {
enable = true;
}
// inbounds;
}
];
relayFixture = mkInbounds { listeners.vless-in = realityListener; };
@@ -278,7 +283,9 @@ let
if lib.any (a: lib.hasInfix fragment a.message) failed then
true
else
throw "proxy-inbounds check: expected an assertion matching '${fragment}', got: ${builtins.toJSON (map (a: a.message) failed)}";
throw "proxy-inbounds check: expected an assertion matching '${fragment}', got: ${
builtins.toJSON (map (a: a.message) failed)
}";
mkRejectsListener =
listener:
@@ -453,23 +460,20 @@ let
};
} "targets a sing-box-only outbound")
(mkRejects (baseProxy // { inbounds.enable = true; })
"requires at least one entry in inbounds.listeners"
)
(mkRejects (
baseProxy // { inbounds.enable = true; }
) "requires at least one entry in inbounds.listeners")
# recursiveUpdate, not //: this one nests into proxy, which baseProxy sets.
(mkRejects
(lib.recursiveUpdate baseProxy {
proxy.listener.port = 1080;
inbounds = {
enable = true;
listeners.clash = realityListener // {
port = 1080;
};
(mkRejects (lib.recursiveUpdate baseProxy {
proxy.listener.port = 1080;
inbounds = {
enable = true;
listeners.clash = realityListener // {
port = 1080;
};
})
"collides with proxy.listener.port"
)
};
}) "collides with proxy.listener.port")
# AmneziaWG listeners.
(mkRejectsListener (awgListener // { tls.enable = true; }) "AmneziaWG takes no tls")
@@ -511,24 +515,37 @@ let
assertions = [
# Listeners are rendered at start time.
(assert relayConfig.inbounds == [ ]; true)
(
assert relayConfig.inbounds == [ ];
true
)
# AsIs when relayed through sing-box; IPOnDemand when XRay dials (see the template).
(assert relayConfig.routing.domainStrategy == "AsIs"; true)
(assert exitConfig.routing.domainStrategy == "IPOnDemand"; true)
(assert hasOutbound relayConfig "proxy"; true)
(assert (ruleByTag relayConfig "inbound-final").outboundTag == "proxy"; true)
(
assert
(builtins.head (builtins.filter (ob: ob.tag == "proxy") relayConfig.outbounds)).protocol
== "socks";
assert relayConfig.routing.domainStrategy == "AsIs";
true
)
(
assert exitConfig.routing.domainStrategy == "IPOnDemand";
true
)
(
assert hasOutbound relayConfig "proxy";
true
)
(
assert (ruleByTag relayConfig "inbound-final").outboundTag == "proxy";
true
)
(
assert
(builtins.head (builtins.filter (ob: ob.tag == "proxy") relayConfig.outbounds))
.settings.servers
(builtins.head (builtins.filter (ob: ob.tag == "proxy") relayConfig.outbounds)).protocol == "socks";
true
)
(
assert
(builtins.head (builtins.filter (ob: ob.tag == "proxy") relayConfig.outbounds)).settings.servers
== [
{
address = "127.0.0.1";
@@ -539,15 +556,36 @@ let
)
# A pure exit node needs no proxy outbound at all.
(assert !hasOutbound exitConfig "proxy"; true)
(assert (ruleByTag exitConfig "inbound-final").outboundTag == "direct"; true)
(
assert !hasOutbound exitConfig "proxy";
true
)
(
assert (ruleByTag exitConfig "inbound-final").outboundTag == "direct";
true
)
# Safety rules come first.
(assert builtins.head (ruleTags relayConfig) == "inbound-block-private"; true)
(assert (ruleByTag relayConfig "inbound-block-private").outboundTag == "block"; true)
(assert (ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ]; true)
(assert (ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ]; true)
(assert !builtins.elem "inbound-block-private" (ruleTags unguardedConfig); true)
(
assert builtins.head (ruleTags relayConfig) == "inbound-block-private";
true
)
(
assert (ruleByTag relayConfig "inbound-block-private").outboundTag == "block";
true
)
(
assert (ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ];
true
)
(
assert (ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ];
true
)
(
assert !builtins.elem "inbound-block-private" (ruleTags unguardedConfig);
true
)
# serverAddress is exempt after blockPrivate, before the country blocks.
(
assert
@@ -559,8 +597,7 @@ let
true
)
(
assert
(ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ];
assert (ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ];
true
)
# Names that resolve private are refused where XRay dials them itself.
@@ -579,29 +616,68 @@ let
assert (ruleByTag namedConfig "inbound-server-address-direct").port == "443";
true
)
(assert (ruleByTag blockedConfig "inbound-proxy-domain").inboundTag == [ "open" ]; true)
(assert (ruleByTag blockedConfig "inbound-server-address-direct").inboundTag == [ "open" ]; true)
# No address to exempt when it is detected at runtime instead.
(assert !builtins.elem "inbound-server-address-direct" (ruleTags relayConfig); true)
(
assert
(ruleByTag ipNamedConfig "inbound-server-address-direct").ip == [ "82.146.44.102" ];
assert (ruleByTag blockedConfig "inbound-proxy-domain").inboundTag == [ "open" ];
true
)
(
assert (ruleByTag blockedConfig "inbound-server-address-direct").inboundTag == [ "open" ];
true
)
# No address to exempt when it is detected at runtime instead.
(
assert !builtins.elem "inbound-server-address-direct" (ruleTags relayConfig);
true
)
(
assert (ruleByTag ipNamedConfig "inbound-server-address-direct").ip == [ "82.146.44.102" ];
true
)
(
assert !builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig);
true
)
(assert !builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig); true)
# A per-listener via becomes its own rule; listeners on the default do not.
(assert builtins.elem "inbound-via-local-exit" (ruleTags mixedConfig); true)
(assert !builtins.elem "inbound-via-relayed" (ruleTags mixedConfig); true)
(assert (ruleByTag mixedConfig "inbound-via-local-exit").inboundTag == [ "local-exit" ]; true)
(assert (ruleByTag mixedConfig "inbound-via-local-exit").outboundTag == "direct"; true)
(
assert builtins.elem "inbound-via-local-exit" (ruleTags mixedConfig);
true
)
(
assert !builtins.elem "inbound-via-relayed" (ruleTags mixedConfig);
true
)
(
assert (ruleByTag mixedConfig "inbound-via-local-exit").inboundTag == [ "local-exit" ];
true
)
(
assert (ruleByTag mixedConfig "inbound-via-local-exit").outboundTag == "direct";
true
)
# The pinned listener gets its own rule; the default one rides the final rule.
(assert (ruleByTag pinnedConfig "inbound-via-through-de").outboundTag == "de-vps"; true)
(assert (ruleByTag pinnedConfig "inbound-final").outboundTag == "nl-vps"; true)
(
assert (ruleByTag pinnedConfig "inbound-via-through-de").outboundTag == "de-vps";
true
)
(
assert (ruleByTag pinnedConfig "inbound-final").outboundTag == "nl-vps";
true
)
# Pinned outbounds are injected at start and need no local proxy.
(assert !hasOutbound pinnedConfig "proxy"; true)
(assert outboundTags pinnedConfig == [ "direct" "block" ]; true)
(
assert !hasOutbound pinnedConfig "proxy";
true
)
(
assert
outboundTags pinnedConfig == [
"direct"
"block"
];
true
)
# Only referenced outbounds are rendered, so the sing-box-only one is fine.
(
assert
@@ -614,23 +690,46 @@ let
)
# The final rule always comes last.
(assert lib.last (ruleTags relayConfig) == "inbound-final"; true)
(assert lib.last (ruleTags mixedConfig) == "inbound-final"; true)
# Without zapret running there is nothing to route around it.
(assert !builtins.elem "inbound-zapret-direct-domain" (ruleTags relayConfig); true)
# The spec carries secret paths, never their contents.
(assert builtins.length relaySpec.listeners == 1; true)
(assert (builtins.head relaySpec.listeners).tag == "vless-in"; true)
(assert (builtins.head relaySpec.listeners).listen == "::"; true)
(
assert
(builtins.head (builtins.head relaySpec.listeners).users).uuidFile == "/run/secrets/uuid";
assert lib.last (ruleTags relayConfig) == "inbound-final";
true
)
(
assert lib.last (ruleTags mixedConfig) == "inbound-final";
true
)
# Without zapret running there is nothing to route around it.
(
assert !builtins.elem "inbound-zapret-direct-domain" (ruleTags relayConfig);
true
)
# The spec carries secret paths, never their contents.
(
assert builtins.length relaySpec.listeners == 1;
true
)
(
assert (builtins.head relaySpec.listeners).tag == "vless-in";
true
)
(
assert (builtins.head relaySpec.listeners).listen == "::";
true
)
(
assert (builtins.head (builtins.head relaySpec.listeners).users).uuidFile == "/run/secrets/uuid";
true
)
(
assert (builtins.head relaySpec.listeners).reality.privateKeyFile == "/run/secrets/reality-key";
true
)
(
assert relaySpec.shareLinks;
true
)
(assert (builtins.head relaySpec.listeners).reality.privateKeyFile == "/run/secrets/reality-key"; true)
(assert relaySpec.shareLinks; true)
# Firewall: TCP for every listener, UDP only where the protocol uses it.
(
@@ -649,15 +748,33 @@ let
];
true
)
(assert wsListener.port == 10002 && wsListener.sharePort == 443; true)
(assert noFirewallFixture.config.networking.firewall.allowedTCPPorts == [ ]; true)
(
assert wsListener.port == 10002 && wsListener.sharePort == 443;
true
)
(
assert noFirewallFixture.config.networking.firewall.allowedTCPPorts == [ ];
true
)
# The unit exists, and only waits on the client stack when it relays.
(assert (service relayFixture).wantedBy == [ "multi-user.target" ]; true)
(assert builtins.elem "proxy-suite-socks.service" (service relayFixture).after; true)
(assert !builtins.elem "proxy-suite-socks.service" (service exitFixture).after; true)
(
assert (service relayFixture).wantedBy == [ "multi-user.target" ];
true
)
(
assert builtins.elem "proxy-suite-socks.service" (service relayFixture).after;
true
)
(
assert !builtins.elem "proxy-suite-socks.service" (service exitFixture).after;
true
)
# Not `requires`: direct-routed listeners keep serving if the client is down.
(assert (service relayFixture).requires == [ ]; true)
(
assert (service relayFixture).requires == [ ];
true
)
# A stop collects what XRay counted since the last timer run.
(
assert
@@ -676,20 +793,44 @@ let
)
# AmneziaWG: the spec carries each listener's loopback inbound, in listener order.
(assert (awgSpecListener "home").amneziaWg.internalPort == 18700; true)
(assert (awgSpecListener "roam").amneziaWg.internalPort == 18701; true)
(assert (awgSpecListener "home").amneziaWg.internalListen == "::"; true)
(assert (awgSpecListener "roam").amneziaWg.internalListen == "127.0.0.1"; true)
(assert (awgSpecListener "home").amneziaWg.fwmark == 2; true)
(assert (awgSpecListener "home").amneziaWg.interfaceName == "awgi-home"; true)
(
assert (awgSpecListener "home").amneziaWg.internalPort == 18700;
true
)
(
assert (awgSpecListener "roam").amneziaWg.internalPort == 18701;
true
)
(
assert (awgSpecListener "home").amneziaWg.internalListen == "::";
true
)
(
assert (awgSpecListener "roam").amneziaWg.internalListen == "127.0.0.1";
true
)
(
assert (awgSpecListener "home").amneziaWg.fwmark == 2;
true
)
(
assert (awgSpecListener "home").amneziaWg.interfaceName == "awgi-home";
true
)
(
assert
(awgSpecListener "roam").amneziaWg.stateFile == "/var/lib/proxy-suite/awg-inbounds/roam/state.json";
true
)
(assert !((awgSpecListener "vless-in") ? amneziaWg); true)
(
assert !((awgSpecListener "vless-in") ? amneziaWg);
true
)
# UDP only, and the interfaces past the host firewall.
(assert awgFixture.config.networking.firewall.allowedTCPPorts == [ 443 ]; true)
(
assert awgFixture.config.networking.firewall.allowedTCPPorts == [ 443 ];
true
)
(
assert
lib.sort lib.lessThan awgFixture.config.networking.firewall.allowedUDPPorts == [
@@ -704,22 +845,37 @@ let
true
)
(
assert
lib.hasInfix ''iifname "awgi-home" accept'' awgFixture.config.networking.firewall.extraReversePathFilterRules;
assert lib.hasInfix ''iifname "awgi-home" accept''
awgFixture.config.networking.firewall.extraReversePathFilterRules;
true
)
# The interfaces come up before XRay renders their links.
(assert builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).after; true)
(assert builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).wants; true)
(assert !(relayFixture.config.systemd.services ? "proxy-suite-inbounds-awg"); true)
(
assert builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).after;
true
)
(
assert builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).wants;
true
)
(
assert !(relayFixture.config.systemd.services ? "proxy-suite-inbounds-awg");
true
)
(
assert lib.hasInfix "rule add pref 8990 fwmark 20 table 103" (awgStartScript awgFixture);
assert lib.hasInfix "awg_inbound.py prepare" (awgStartScript awgFixture);
true
)
# IPv6 routing only where a listener has IPv6.
(assert lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgFixture); true)
(assert !lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgProxyFixture); true)
(
assert lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgFixture);
true
)
(
assert !lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgProxyFixture);
true
)
# Transparent sockets only where there is something to divert.
(
assert lib.hasInfix "net_admin" (readInboundsStart awgFixture);
@@ -727,9 +883,18 @@ let
true
)
# Forwarding only for "lan" listeners.
(assert awgFixture.config.boot.kernel.sysctl."net.ipv4.ip_forward" == 1; true)
(assert awgFixture.config.boot.kernel.sysctl."net.ipv6.conf.all.forwarding" == 1; true)
(assert !(awgProxyFixture.config.services.proxy-suite.internal.sysctl ? "net.ipv4.ip_forward"); true)
(
assert awgFixture.config.boot.kernel.sysctl."net.ipv4.ip_forward" == 1;
true
)
(
assert awgFixture.config.boot.kernel.sysctl."net.ipv6.conf.all.forwarding" == 1;
true
)
(
assert !(awgProxyFixture.config.services.proxy-suite.internal.sysctl ? "net.ipv4.ip_forward");
true
)
# "lan" clients reach private networks and each other natively, "proxy" clients nothing but via.
(
let
@@ -749,7 +914,10 @@ let
assert !lib.hasInfix "10.67.0.0/24 oifname" rules;
true
)
(assert !lib.hasInfix "masquerade" (awgRules awgProxyFixture); true)
(
assert !lib.hasInfix "masquerade" (awgRules awgProxyFixture);
true
)
]
++ failing;
+90 -85
View File
@@ -456,29 +456,32 @@
# proxy_ctl.py's function-level tests: the probe verdict table and exit walk,
# autoProxy learn/queue, inbound stats and subscriptions, apps run.
proxy-ctl-unit =
pkgs.runCommand "proxy-suite-proxy-ctl-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } ''
export SING_BOX=${pkgs.sing-box}/bin/sing-box
export PYTHONDONTWRITEBYTECODE=1
python ${../../pkgs/proxy-ctl}/test_proxy_ctl.py
touch "$out"
'';
pkgs.runCommand "proxy-suite-proxy-ctl-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; }
''
export SING_BOX=${pkgs.sing-box}/bin/sing-box
export PYTHONDONTWRITEBYTECODE=1
python ${../../pkgs/proxy-ctl}/test_proxy_ctl.py
touch "$out"
'';
# proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped.
proxy-suite-supervisor-unit =
pkgs.runCommand "proxy-suite-supervisor-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } ''
export PYTHONDONTWRITEBYTECODE=1 HOME="$TMPDIR"
python ${../../pkgs/proxy-ctl}/test_proxy_supervisor.py
touch "$out"
'';
pkgs.runCommand "proxy-suite-supervisor-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; }
''
export PYTHONDONTWRITEBYTECODE=1 HOME="$TMPDIR"
python ${../../pkgs/proxy-ctl}/test_proxy_supervisor.py
touch "$out"
'';
# proxy_export: the running config made portable, and sing-box still accepts it.
proxy-export-unit =
pkgs.runCommand "proxy-suite-proxy-export-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } ''
export SING_BOX=${pkgs.sing-box}/bin/sing-box
export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl}
python ${../../pkgs/proxy-ctl}/test_proxy_export.py
touch "$out"
'';
pkgs.runCommand "proxy-suite-proxy-export-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; }
''
export SING_BOX=${pkgs.sing-box}/bin/sing-box
export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl}
python ${../../pkgs/proxy-ctl}/test_proxy_export.py
touch "$out"
'';
# proxy-tui driven headless: keys turn into the right proxy-ctl argv.
proxy-tui-unit =
@@ -492,11 +495,12 @@
# proxy_model: the status strip, tab loads and the tray menu tree, without a UI toolkit.
proxy-model-unit =
pkgs.runCommand "proxy-suite-proxy-model-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } ''
export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl}
python ${../../pkgs/proxy-ctl}/test_proxy_model.py
touch "$out"
'';
pkgs.runCommand "proxy-suite-proxy-model-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; }
''
export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl}
python ${../../pkgs/proxy-ctl}/test_proxy_model.py
touch "$out"
'';
# proxy_gui and proxy_sni import against GTK4/libadwaita, the D-Bus interfaces parse,
# and the tray menu serializes to dbusmenu's layout type. No display needed.
@@ -520,8 +524,7 @@
# autoProxy slowness routing: sampler and judge.
autoproxy-slowness =
pkgs.runCommand "proxy-suite-autoproxy-slowness-check"
{ nativeBuildInputs = [ pkgs.jq ]; }
pkgs.runCommand "proxy-suite-autoproxy-slowness-check" { nativeBuildInputs = [ pkgs.jq ]; }
''
sample=${../../modules/proxy-suite/autoproxy-slow-sample.jq}
judge=${../../modules/proxy-suite/autoproxy-slow-judge.jq}
@@ -582,73 +585,75 @@
# autoProxy probe order: one exit per network first, bad exits last; and the
# strikes that make an exit bad.
autoproxy-rounds =
pkgs.runCommand "proxy-suite-autoproxy-rounds-check" { nativeBuildInputs = [ pkgs.jq ]; } ''
echo '[{"tag":"direct"},{"tag":"a"},{"tag":"b"},{"tag":"a2"},{"tag":"b2"},{"tag":"c"}]' > index.json
echo '{"exits":{"a":{"asn":"AS1","bad":true},"b":{"asn":"AS2"},"a2":{"asn":"AS1"},
"b2":{"asn":"AS2"},"c":{"asn":"AS3","bad":false}}}' > state.json
r="$(jq -c --slurpfile s state.json -f ${../../modules/proxy-suite/autoproxy-rounds.jq} index.json)"
printf '%s\n' "$r"
# A refused a takes neither AS1's first place (a2 does) nor any place before b2.
jq -e '. == {r1: "b,a2,c", r2: "b2,a", ordered: ["b", "a2", "b2", "c", "a"]}' <<<"$r" > /dev/null
pkgs.runCommand "proxy-suite-autoproxy-rounds-check" { nativeBuildInputs = [ pkgs.jq ]; }
''
echo '[{"tag":"direct"},{"tag":"a"},{"tag":"b"},{"tag":"a2"},{"tag":"b2"},{"tag":"c"}]' > index.json
echo '{"exits":{"a":{"asn":"AS1","bad":true},"b":{"asn":"AS2"},"a2":{"asn":"AS1"},
"b2":{"asn":"AS2"},"c":{"asn":"AS3","bad":false}}}' > state.json
r="$(jq -c --slurpfile s state.json -f ${../../modules/proxy-suite/autoproxy-rounds.jq} index.json)"
printf '%s\n' "$r"
# A refused a takes neither AS1's first place (a2 does) nor any place before b2.
jq -e '. == {r1: "b,a2,c", r2: "b2,a", ordered: ["b", "a2", "b2", "c", "a"]}' <<<"$r" > /dev/null
k() {
jq -c --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$4" --argjson ttl 100 \
-f ${../../modules/proxy-suite/autoproxy-strike.jq} <<<"$5"
}
s='{"exits":{"a":{"asn":"AS1"},"b":{}}}'
# One destination is not enough, however often it strikes.
s="$(k '["a"]' sekai.test refused 1000 "$s")"
s="$(k '["a","b"]' sekai.test refused 1010 "$s")"
jq -e '.exits.a.bad == false and .exits.a.asn == "AS1" and .exits.b.bad == false' <<<"$s" > /dev/null
# A second one is.
s="$(k '["a"]' pximg.net slow 1020 "$s")"
jq -e '.exits.a | .bad and .badBy == ["sekai.test refused", "pximg.net slow"]' <<<"$s" > /dev/null
jq -e '.exits.b.bad == false' <<<"$s" > /dev/null
# A TTL later the older strike has expired.
s="$(k '[]' "" "" 1115 "$s")"
jq -e '.exits.a | (.bad | not) and .badBy == ["pximg.net slow"]' <<<"$s" > /dev/null
# A block page may be a passing challenge: one is not enough either.
s="$(k '["b"]' colorfulpalette.org wall:aws-waf 1120 "$s")"
jq -e '.exits.b | (.bad | not) and .badBy == ["colorfulpalette.org wall:aws-waf"]' <<<"$s" > /dev/null
s="$(k '["b"]' fandom.com wall:cloudflare 1130 "$s")"
jq -e '.exits.b | .bad and .badBy == ["colorfulpalette.org wall:aws-waf", "fandom.com wall:cloudflare"]' <<<"$s" > /dev/null
touch "$out"
'';
k() {
jq -c --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$4" --argjson ttl 100 \
-f ${../../modules/proxy-suite/autoproxy-strike.jq} <<<"$5"
}
s='{"exits":{"a":{"asn":"AS1"},"b":{}}}'
# One destination is not enough, however often it strikes.
s="$(k '["a"]' sekai.test refused 1000 "$s")"
s="$(k '["a","b"]' sekai.test refused 1010 "$s")"
jq -e '.exits.a.bad == false and .exits.a.asn == "AS1" and .exits.b.bad == false' <<<"$s" > /dev/null
# A second one is.
s="$(k '["a"]' pximg.net slow 1020 "$s")"
jq -e '.exits.a | .bad and .badBy == ["sekai.test refused", "pximg.net slow"]' <<<"$s" > /dev/null
jq -e '.exits.b.bad == false' <<<"$s" > /dev/null
# A TTL later the older strike has expired.
s="$(k '[]' "" "" 1115 "$s")"
jq -e '.exits.a | (.bad | not) and .badBy == ["pximg.net slow"]' <<<"$s" > /dev/null
# A block page may be a passing challenge: one is not enough either.
s="$(k '["b"]' colorfulpalette.org wall:aws-waf 1120 "$s")"
jq -e '.exits.b | (.bad | not) and .badBy == ["colorfulpalette.org wall:aws-waf"]' <<<"$s" > /dev/null
s="$(k '["b"]' fandom.com wall:cloudflare 1130 "$s")"
jq -e '.exits.b | .bad and .badBy == ["colorfulpalette.org wall:aws-waf", "fandom.com wall:cloudflare"]' <<<"$s" > /dev/null
touch "$out"
'';
# `proxy-ctl proxy auto forget|clear`, as the runner applies them.
autoproxy-edit =
pkgs.runCommand "proxy-suite-autoproxy-edit-check" { nativeBuildInputs = [ pkgs.jq ]; } ''
edit() { jq -c --arg op "$1" --arg d "$2" -f ${../../modules/proxy-suite/autoproxy-edit.jq} <<<"$3"; }
s='{
"domains": {"last.fm": {"exit": "a", "host": "www.last.fm"}, "pximg.net": {"exit": "b", "host": "i.pximg.net"}},
"hosts": {"www.last.fm": {"domain": "last.fm"}, "cdn.last.fm": {"domain": "last.fm"}, "i.pximg.net": {"domain": "pximg.net"}},
"backlog": {"api.last.fm": {"domain": "last.fm", "hits": 3}, "x.test": {"domain": "x.test", "hits": 1}},
"slowWant": {"last.fm": 1}, "slowSkip": {"pximg.net": 1},
"exits": {
"a": {"asn": "AS1", "strikes": {"last.fm": {"why": "refused", "at": 1}, "sekai.test": {"why": "slow", "at": 2}}, "bad": true,
"badBy": ["last.fm refused", "sekai.test slow"]},
"b": {"asn": "AS2"}
},
"egress": "203.0.113.1", "lastRun": 5
}'
pkgs.runCommand "proxy-suite-autoproxy-edit-check" { nativeBuildInputs = [ pkgs.jq ]; }
''
edit() { jq -c --arg op "$1" --arg d "$2" -f ${../../modules/proxy-suite/autoproxy-edit.jq} <<<"$3"; }
s='{
"domains": {"last.fm": {"exit": "a", "host": "www.last.fm"}, "pximg.net": {"exit": "b", "host": "i.pximg.net"}},
"hosts": {"www.last.fm": {"domain": "last.fm"}, "cdn.last.fm": {"domain": "last.fm"}, "i.pximg.net": {"domain": "pximg.net"}},
"backlog": {"api.last.fm": {"domain": "last.fm", "hits": 3}, "x.test": {"domain": "x.test", "hits": 1}},
"slowWant": {"last.fm": 1}, "slowSkip": {"pximg.net": 1},
"exits": {
"a": {"asn": "AS1", "strikes": {"last.fm": {"why": "refused", "at": 1}, "sekai.test": {"why": "slow", "at": 2}}, "bad": true,
"badBy": ["last.fm refused", "sekai.test slow"]},
"b": {"asn": "AS2"}
},
"egress": "203.0.113.1", "lastRun": 5
}'
# Forget: every trace of the one domain, and a strike it made no longer counts.
f="$(edit forget last.fm "$s")"
jq -e '(.domains | keys) == ["pximg.net"]' <<<"$f" > /dev/null
jq -e '(.hosts | keys) == ["i.pximg.net"] and (.backlog | keys) == ["x.test"]' <<<"$f" > /dev/null
jq -e '.slowWant == {} and .slowSkip == {"pximg.net": 1}' <<<"$f" > /dev/null
jq -e '.exits.a | .asn == "AS1" and (.bad | not) and .badBy == ["sekai.test slow"]' <<<"$f" > /dev/null
jq -e '.exits.b == {"asn": "AS2"}' <<<"$f" > /dev/null
# A domain it never knew changes nothing.
jq -e --argjson s "$s" '. == $s' <<<"$(edit forget nope.test "$s")" > /dev/null
# Forget: every trace of the one domain, and a strike it made no longer counts.
f="$(edit forget last.fm "$s")"
jq -e '(.domains | keys) == ["pximg.net"]' <<<"$f" > /dev/null
jq -e '(.hosts | keys) == ["i.pximg.net"] and (.backlog | keys) == ["x.test"]' <<<"$f" > /dev/null
jq -e '.slowWant == {} and .slowSkip == {"pximg.net": 1}' <<<"$f" > /dev/null
jq -e '.exits.a | .asn == "AS1" and (.bad | not) and .badBy == ["sekai.test slow"]' <<<"$f" > /dev/null
jq -e '.exits.b == {"asn": "AS2"}' <<<"$f" > /dev/null
# A domain it never knew changes nothing.
jq -e --argjson s "$s" '. == $s' <<<"$(edit forget nope.test "$s")" > /dev/null
# Clear: every route and verdict; the exits, backlog and egress stay.
c="$(edit clear "" "$s")"
jq -e '.domains == {} and .hosts == {} and (has("slowWant") | not) and (has("slowSkip") | not)' <<<"$c" > /dev/null
jq -e '.exits.a | .asn == "AS1" and .strikes == {} and (.bad | not) and .badBy == []' <<<"$c" > /dev/null
jq -e '(.backlog | keys) == ["api.last.fm", "x.test"] and .egress == "203.0.113.1" and .lastRun == 5' <<<"$c" > /dev/null
touch "$out"
'';
# Clear: every route and verdict; the exits, backlog and egress stay.
c="$(edit clear "" "$s")"
jq -e '.domains == {} and .hosts == {} and (has("slowWant") | not) and (has("slowSkip") | not)' <<<"$c" > /dev/null
jq -e '.exits.a | .asn == "AS1" and .strikes == {} and (.bad | not) and .badBy == []' <<<"$c" > /dev/null
jq -e '(.backlog | keys) == ["api.last.fm", "x.test"] and .egress == "203.0.113.1" and .lastRun == 5' <<<"$c" > /dev/null
touch "$out"
'';
# 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
+4 -2
View File
@@ -177,11 +177,13 @@ in
true
)
(
assert !(ipServer.config.systemd.services ? proxy-suite-tor) && (ipSpec.onionListeners or [ ]) == [ ];
assert
!(ipServer.config.systemd.services ? proxy-suite-tor) && (ipSpec.onionListeners or [ ]) == [ ];
true
)
(
assert builtins.elem "proxy-suite-tor.service" onionServer.config.systemd.services.proxy-suite-inbounds.after;
assert builtins.elem "proxy-suite-tor.service"
onionServer.config.systemd.services.proxy-suite-inbounds.after;
true
)
(
+10 -6
View File
@@ -19,9 +19,7 @@ let
# JSON. The context is dropped so the check may mention it.
expectedOutboundFile =
value:
builtins.unsafeDiscardStringContext "${
pkgs.writeText "proxy-suite-core" (builtins.toJSON value)
}";
builtins.unsafeDiscardStringContext "${pkgs.writeText "proxy-suite-core" (builtins.toJSON value)}";
# SingBox dials SSH natively: no unit, no local SOCKS listener.
sshNativeSingBox = evalProxySuite [
@@ -367,7 +365,9 @@ let
(
assert pkgs.lib.hasInfix expectedNativeSingBoxOutbound sshNativeSingBoxStart;
# The daemon cannot read the key where it lives: it gets a group-readable copy.
assert pkgs.lib.hasInfix "install -m 0640 -g proxy-suite-daemon /run/secrets/ssh-key \"$SSH_IDENTITY\"" sshNativeSingBoxStart;
assert pkgs.lib.hasInfix
"install -m 0640 -g proxy-suite-daemon /run/secrets/ssh-key \"$SSH_IDENTITY\""
sshNativeSingBoxStart;
assert pkgs.lib.hasInfix "'.private_key_path = $key'" sshNativeSingBoxStart;
true
)
@@ -392,7 +392,10 @@ let
)
# The keys must not be baked into the store-resident outbound JSON.
(
assert !(pkgs.lib.hasInfix "host_key" (builtins.toJSON sshHostKeyFile.config.services.proxy-suite.sshProxy.hostKey));
assert
!(pkgs.lib.hasInfix "host_key" (
builtins.toJSON sshHostKeyFile.config.services.proxy-suite.sshProxy.hostKey
));
true
)
@@ -443,7 +446,8 @@ let
true
)
(
assert pkgs.lib.hasInfix ''UserKnownHostsFile="$CREDENTIALS_DIRECTORY/known_hosts"'' standaloneStartScript;
assert pkgs.lib.hasInfix ''UserKnownHostsFile="$CREDENTIALS_DIRECTORY/known_hosts"''
standaloneStartScript;
true
)
# Secrets reach the unprivileged user as credentials.
+17 -22
View File
@@ -77,19 +77,16 @@ in
# absent a pin - at start, keeping every tag for rules that name one.
(
assert pkgs.lib.hasInfix ''PROXY_TAG="$PINNED_OUTBOUND"'' subscriptionFirstSelectionStartScript;
assert
pkgs.lib.hasInfix ''[{type:"selector",tag:"proxy",outbounds:[$t],default:$t}] + .''
subscriptionFirstSelectionStartScript;
assert pkgs.lib.hasInfix ''[{type:"selector",tag:"proxy",outbounds:[$t],default:$t}] + .''
subscriptionFirstSelectionStartScript;
true
)
# The pin is read from state, and one that names nothing is dropped.
(
assert
pkgs.lib.hasInfix "/var/lib/proxy-suite/pinned-outbound" subscriptionOnlyStartScript;
assert
pkgs.lib.hasInfix "pinned outbound '$PINNED_OUTBOUND' is not available"
subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix "/var/lib/proxy-suite/pinned-outbound" subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix "pinned outbound '$PINNED_OUTBOUND' is not available"
subscriptionOnlyStartScript;
true
)
@@ -134,10 +131,8 @@ in
# Declared and runtime subscriptions both go through the same two entry
# points, with the tag passed raw.
(
assert pkgs.lib.hasInfix "_proxy_suite_load_subscription community "
subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_fetch_subscription community "
subscriptionOnlyUpdateScript;
assert pkgs.lib.hasInfix "_proxy_suite_load_subscription community " subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_fetch_subscription community " subscriptionOnlyUpdateScript;
assert pkgs.lib.hasInfix ''_proxy_suite_load_subscription "$RUNTIME_SUB_TAG"''
subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix ''_proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG"''
@@ -147,8 +142,10 @@ in
# The fetcher's output must land in the cache, not after a stray newline.
(
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"'' subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"'' subscriptionOnlyUpdateScript;
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"''
subscriptionOnlyStartScript;
assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"''
subscriptionOnlyUpdateScript;
true
)
@@ -190,14 +187,12 @@ in
# Runtime spool dirs are root-only unless userControl grants outbounds (see user-control.nix).
(
assert
builtins.any (
rule: builtins.match "d /var/lib/proxy-suite/outbounds\\.d 0700 root root -" rule != null
) minimal.config.systemd.tmpfiles.rules;
assert
builtins.any (
rule: builtins.match "d /var/lib/proxy-suite/subscriptions\\.d 0700 root root -" rule != null
) minimal.config.systemd.tmpfiles.rules;
assert builtins.any (
rule: builtins.match "d /var/lib/proxy-suite/outbounds\\.d 0700 root root -" rule != null
) minimal.config.systemd.tmpfiles.rules;
assert builtins.any (
rule: builtins.match "d /var/lib/proxy-suite/subscriptions\\.d 0700 root root -" rule != null
) minimal.config.systemd.tmpfiles.rules;
true
)
+8 -10
View File
@@ -5,19 +5,17 @@
}:
let
proxyWithSubscriptions =
subscriptions:
{
system.stateVersion = "26.05";
services.proxy-suite = {
proxyWithSubscriptions = subscriptions: {
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
proxy = {
enable = true;
backend = "sing-box";
inherit subscriptions;
};
backend = "sing-box";
inherit subscriptions;
};
};
};
subscriptionUrlFileFixture = evalProxySuite [
(proxyWithSubscriptions [
+2 -1
View File
@@ -86,7 +86,8 @@ in
assert tgWithGlobalTunServiceConfig.User == "proxy-suite-daemon";
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" tgWithGlobalTunBypassUp;
assert pkgs.lib.hasInfix "\"system.slice/proxy-suite-tg-ws-proxy.service\" meta mark set 4"
tgWithGlobalTunBypassUp;
assert pkgs.lib.hasInfix "delete table inet proxy_suite_tg_ws_proxy" tgWithGlobalTunBypassDown;
assert pkgs.lib.hasInfix "rule add pref 8999 fwmark 4 lookup main" tgWithGlobalTunBypassUp;
assert pkgs.lib.hasInfix "rule del pref 8999 fwmark 4 lookup main" tgWithGlobalTunBypassDown;
+4 -1
View File
@@ -75,7 +75,10 @@ let
inherit (pkgs) lib;
inherit pkgs cfg;
packages = import ../../../pkgs/default.nix { inherit pkgs; };
derived = import ../../../modules/proxy-suite/derived.nix { inherit (pkgs) lib; inherit cfg; };
derived = import ../../../modules/proxy-suite/derived.nix {
inherit (pkgs) lib;
inherit cfg;
};
};
tgWithGlobalTunBypassUp = generated.readDerivation tgWithGlobalTunModule.bypassUpScript;
tgWithGlobalTunBypassDown = generated.readDerivation tgWithGlobalTunModule.bypassDownScript;
+153 -119
View File
@@ -54,9 +54,12 @@ let
builtins.filter (a: !a.assertion && lib.hasPrefix "proxy-suite" a.message) fixture.config.assertions
);
services = fixture: fixture.config.systemd.services;
socksStartOf = fixture: generated.readDerivation (services fixture).proxy-suite-socks.serviceConfig.ExecStart;
torStartOf = fixture: generated.readDerivation (services fixture).proxy-suite-tor.serviceConfig.ExecStart;
dnsOut = config: (lib.head (builtins.filter (o: o.tag == "dns-out") config.outbounds)).settings.rules;
socksStartOf =
fixture: generated.readDerivation (services fixture).proxy-suite-socks.serviceConfig.ExecStart;
torStartOf =
fixture: generated.readDerivation (services fixture).proxy-suite-tor.serviceConfig.ExecStart;
dnsOut =
config: (lib.head (builtins.filter (o: o.tag == "dns-out") config.outbounds)).settings.rules;
singBox = mkFixture "sing-box" { };
singBoxStart = socksStartOf singBox;
@@ -64,10 +67,12 @@ let
singBoxTun = mkTunConfig singBox;
singBoxModes = (mkRouting singBox).singBoxRouteModeRules;
singBoxTorUnit = (services singBox).proxy-suite-tor;
singBoxTProxy = mkTProxyConfig (mkFixture "sing-box" {
proxy.tun.enable = false;
proxy.tproxy.enable = true;
});
singBoxTProxy = mkTProxyConfig (
mkFixture "sing-box" {
proxy.tun.enable = false;
proxy.tproxy.enable = true;
}
);
xray = mkFixture "xray" { proxy.tproxy.enable = true; };
xrayStart = socksStartOf xray;
@@ -85,7 +90,9 @@ let
bridges = mkFixture "sing-box" {
tor = {
bridges.lines = [ "obfs4 192.0.2.1:443 0123456789ABCDEF0123456789ABCDEF01234567 cert=x iat-mode=0" ];
bridges.lines = [
"obfs4 192.0.2.1:443 0123456789ABCDEF0123456789ABCDEF01234567 cert=x iat-mode=0"
];
bridges.file = "/run/secrets/tor-bridges";
};
};
@@ -143,7 +150,9 @@ let
exitNode = mkFixture "sing-box" exitInbounds;
exitNodeConfig = mkInboundsConfig exitNode;
exitNodeRules = exitNodeConfig.routing.rules;
exitNodeNoOnion = mkInboundsConfig (mkFixture "sing-box" (exitInbounds // { tor.routeOnion = false; }));
exitNodeNoOnion = mkInboundsConfig (
mkFixture "sing-box" (exitInbounds // { tor.routeOnion = false; })
);
# inbounds.routing.blockPrivate's resolve guard must come after the .onion rule: resolving
# a .onion name fails, and the connection with it. autoProxy's probe pins sit first.
@@ -166,25 +175,23 @@ let
]
)
);
guardRuntime =
pkgs.runCommand "proxy-suite-tor-guard-check" { nativeBuildInputs = [ pkgs.jq ]; }
''
echo '{"inbounds":[],"outbounds":[],"dns":{"rules":[]},"route":{"rules":[]}}' |
jq --argjson obs '[]' --argjson auth_enabled false --arg user "" --arg password "" \
--argjson route_enabled true --argjson route_rules "$(cat ${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"}]' \
-f ${guardFilter} > rules.json
jq -e '
.route.rules as $r
| ($r | map(.domain_suffix? == ["onion"]) | index(true)) as $onion
| ($r | map(.action? == "resolve") | index(true)) as $guard
| ($r | map(.domain_suffix? == ["ru"]) | index(true)) as $ru
| $onion != null and $guard > $onion and $guard < $ru
' rules.json
touch $out
'';
guardRuntime = pkgs.runCommand "proxy-suite-tor-guard-check" { nativeBuildInputs = [ pkgs.jq ]; } ''
echo '{"inbounds":[],"outbounds":[],"dns":{"rules":[]},"route":{"rules":[]}}' |
jq --argjson obs '[]' --argjson auth_enabled false --arg user "" --arg password "" \
--argjson route_enabled true --argjson route_rules "$(cat ${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"}]' \
-f ${guardFilter} > rules.json
jq -e '
.route.rules as $r
| ($r | map(.domain_suffix? == ["onion"]) | index(true)) as $onion
| ($r | map(.action? == "resolve") | index(true)) as $guard
| ($r | map(.domain_suffix? == ["ru"]) | index(true)) as $ru
| $onion != null and $guard > $onion and $guard < $ru
' rules.json
touch $out
'';
onionStart = torStartOf onion;
onionSpec = mkInboundsSpec onion;
@@ -192,93 +199,111 @@ let
invalidAssertions = mkFailingAssertions mkBadProxySuiteFixture (
map (case: { enable = true; } // case) [
# Enabled but used for nothing.
{ tor.enable = true; }
# An outbound without a backend.
{
tor = {
enable = true;
asOutbound = true;
};
}
# "tor" is taken.
{
tor = {
enable = true;
asOutbound = true;
};
proxy = {
enable = true;
outbounds = [
{
tag = "tor";
url = "http://proxy.example.com:8080";
}
];
};
}
# Snowflake ignores Socks5Proxy.
{
tor = {
enable = true;
asOutbound = true;
upstream = "proxy";
bridges.lines = [ "snowflake 192.0.2.3:80 2B280B23E1107BB62ABFC40DDCC8824814F80A72" ];
};
proxy.enable = true;
}
# The SOCKS port on the proxy's own.
{
tor = {
enable = true;
asOutbound = true;
socksPort = 1080;
};
proxy = {
enable = true;
listener.port = 1080;
};
}
# An onion service without inbounds, and one naming a listener that is not there.
{
tor = {
enable = true;
onionService.enable = true;
};
}
{
tor = {
enable = true;
onionService = {
# Enabled but used for nothing.
{ tor.enable = true; }
# An outbound without a backend.
{
tor = {
enable = true;
listeners = [ "missing" ];
asOutbound = true;
};
};
inbounds = {
enable = true;
routing.via = "direct";
listeners.plain = listener;
};
}
# Two listeners on one onion port.
{
tor = {
enable = true;
onionService.enable = true;
};
inbounds = {
enable = true;
routing.via = "direct";
listeners.a = listener // {
sharePort = 443;
}
# "tor" is taken.
{
tor = {
enable = true;
asOutbound = true;
};
listeners.b = listener // {
port = 10444;
sharePort = 443;
proxy = {
enable = true;
outbounds = [
{
tag = "tor";
url = "http://proxy.example.com:8080";
}
];
};
};
}
]);
}
# Snowflake ignores Socks5Proxy.
{
tor = {
enable = true;
asOutbound = true;
upstream = "proxy";
bridges.lines = [ "snowflake 192.0.2.3:80 2B280B23E1107BB62ABFC40DDCC8824814F80A72" ];
};
proxy = {
enable = true;
outbounds = [
{
tag = "vps";
url = "http://vps.example.com:8080";
}
];
};
}
# Upstream through the proxy with Tor its only outbound: Tor through itself.
{
tor = {
enable = true;
asOutbound = true;
upstream = "proxy";
};
proxy.enable = true;
}
# The SOCKS port on the proxy's own.
{
tor = {
enable = true;
asOutbound = true;
socksPort = 1080;
};
proxy = {
enable = true;
listener.port = 1080;
};
}
# An onion service without inbounds, and one naming a listener that is not there.
{
tor = {
enable = true;
onionService.enable = true;
};
}
{
tor = {
enable = true;
onionService = {
enable = true;
listeners = [ "missing" ];
};
};
inbounds = {
enable = true;
routing.via = "direct";
listeners.plain = listener;
};
}
# Two listeners on one onion port.
{
tor = {
enable = true;
onionService.enable = true;
};
inbounds = {
enable = true;
routing.via = "direct";
listeners.a = listener // {
sharePort = 443;
};
listeners.b = listener // {
port = 10444;
sharePort = 443;
};
};
}
]
);
in
{
runtime = guardRuntime;
@@ -297,7 +322,8 @@ in
assert lib.any (o: o.tag == "proxy") exitNodeConfig.outbounds;
assert builtins.elem "proxy-suite-socks.service" (services exitNode).proxy-suite-inbounds.wants;
assert !(lib.any (r: r.ruleTag or "" == "inbound-tor-onion") exitNodeNoOnion.routing.rules);
assert !(lib.any (r: r.ruleTag or "" == "inbound-tor-onion") (mkInboundsConfig onion).routing.rules);
assert
!(lib.any (r: r.ruleTag or "" == "inbound-tor-onion") (mkInboundsConfig onion).routing.rules);
true
)
(
@@ -315,12 +341,13 @@ in
# Every backend dials Tor's SOCKS listener as the "tor" outbound.
(
assert hasInfix ''{"server":"127.0.0.1","server_port":18530,"tag":"tor","type":"socks"}'' singBoxStart;
assert hasInfix ''{"server":"127.0.0.1","server_port":18530,"tag":"tor","type":"socks"}''
singBoxStart;
true
)
(
assert
hasInfix ''{"protocol":"socks","settings":{"address":"127.0.0.1","port":18530},"tag":"tor"}'' xrayStart;
assert hasInfix ''{"protocol":"socks","settings":{"address":"127.0.0.1","port":18530},"tag":"tor"}''
xrayStart;
true
)
(
@@ -443,9 +470,12 @@ in
# userControl's group can use the control socket: that is `proxy-ctl tor status|newnym`.
(
assert
hasInfix "proxy-suite-tor-control-dir" (toString (services controlled).proxy-suite-tor.serviceConfig.ExecStartPre)
hasInfix "proxy-suite-tor-control-dir" (
toString (services controlled).proxy-suite-tor.serviceConfig.ExecStartPre
)
&& !(singBoxTorUnit.serviceConfig ? ExecStartPre)
&& (mkProxyCtlDerived singBox).wrapperEnv.TOR_CONTROL_SOCKET == "/run/proxy-suite-tor/control/socket";
&&
(mkProxyCtlDerived singBox).wrapperEnv.TOR_CONTROL_SOCKET == "/run/proxy-suite-tor/control/socket";
true
)
(
@@ -455,7 +485,8 @@ in
&& hasInfix "ClientTransportPlugin snowflake exec" bridgesStart
&& hasInfix "Bridge obfs4 192.0.2.1:443 " bridgesStart
&& hasInfix ''"$CREDENTIALS_DIRECTORY/bridges"'' bridgesStart
&& builtins.elem "bridges:/run/secrets/tor-bridges" (services bridges).proxy-suite-tor.serviceConfig.LoadCredential;
&& builtins.elem "bridges:/run/secrets/tor-bridges" (services bridges)
.proxy-suite-tor.serviceConfig.LoadCredential;
true
)
# Through the local proxy, with its password read at start, never written to the store.
@@ -475,7 +506,10 @@ in
&& hasInfix "HiddenServicePort 10443 127.0.0.1:10443" onionStart
&& hasInfix "HiddenServicePort 443 127.0.0.1:10444" onionStart
&& hasInfix "SocksPort 0" onionStart
&& hasInfix "hs_ed25519_secret_key" onionStart;
&& !(hasInfix "hs_ed25519_secret_key" onionStart)
&& hasInfix "proxy-suite-tor-onion-key" (
toString (services onion).proxy-suite-tor.serviceConfig.ExecStartPre
);
true
)
(
+2 -1
View File
@@ -157,7 +157,8 @@ in
true
)
(
assert hasInfix singBoxHop hybridStart && hasInfix "_proxy_suite_add_sing_box_ob \"$OB_JSON\"" hybridStart;
assert
hasInfix singBoxHop hybridStart && hasInfix "_proxy_suite_add_sing_box_ob \"$OB_JSON\"" hybridStart;
true
)
# Only the tunnel reads the profile, at start; the private key never reaches the store.
@@ -41,7 +41,13 @@
) xrayTproxyConfig.inbounds;
# Apps' DNS through TProxy is answered by XRay, as sing-box's hijack-dns.
assert builtins.any (
rule: (rule.ruleTag or "") == "dns-hijack" && rule.inboundTag == [ "tproxy-in" "tproxy-in6" ]
rule:
(rule.ruleTag or "") == "dns-hijack"
&&
rule.inboundTag == [
"tproxy-in"
"tproxy-in6"
]
) xrayTproxyConfig.routing.rules;
assert builtins.any (outbound: outbound.tag == "dns-out") xrayTproxyConfig.outbounds;
assert specificRule.outboundTag == "proxy-suite-ob-primary";
+24 -14
View File
@@ -30,7 +30,11 @@
rule: (rule ? ruleTag) && rule.ruleTag == "dns-hijack"
) xrayTunConfig.routing.rules;
tunDnsUpstreamRules = builtins.filter (
rule: builtins.elem (rule.ruleTag or "") [ "dns-upstream-direct" "dns-upstream-remote" ]
rule:
builtins.elem (rule.ruleTag or "") [
"dns-upstream-direct"
"dns-upstream-remote"
]
) xrayTunConfig.routing.rules;
in
assert tunInbound.protocol == "tun";
@@ -47,7 +51,11 @@
assert tunHasDirectGeositeRule;
assert tunHasDnsHijackRule;
# Servers route by their own tags: local direct, remote through the proxy.
assert map (rule: rule.inboundTag) tunDnsUpstreamRules == [ [ "local" ] [ "remote" ] ];
assert
map (rule: rule.inboundTag) tunDnsUpstreamRules == [
[ "local" ]
[ "remote" ]
];
assert xrayTunConfig.dns.queryStrategy == "UseIP";
assert (builtins.head xrayTunConfig.dns.servers).address == "fakedns";
assert (builtins.head xrayTunConfig.dns.servers).tag == "fakedns";
@@ -110,18 +118,20 @@
# No uplink src: it would go stale when the uplink address changes.
assert !(pkgs.lib.hasInfix "uplink_addr" xrayTunUpScript);
# Every rule the up script adds is flushed first, v4 and v6.
assert builtins.all (
priority:
pkgs.lib.hasInfix "-4 rule del pref ${toString priority}" xrayTunUpScript
&& pkgs.lib.hasInfix "-6 rule del pref ${toString priority}" xrayTunUpScript
) [
checkConstants.xrayTunMarkBypassRulePriority
checkConstants.xrayTunServiceUserRulePriority
checkConstants.xrayTunPerAppTunRulePriority
checkConstants.xrayTunDnsRulePriority
checkConstants.xrayTunMainRulePriority
checkConstants.tunAutoRouteRulePriority
];
assert builtins.all
(
priority:
pkgs.lib.hasInfix "-4 rule del pref ${toString priority}" xrayTunUpScript
&& pkgs.lib.hasInfix "-6 rule del pref ${toString priority}" xrayTunUpScript
)
[
checkConstants.xrayTunMarkBypassRulePriority
checkConstants.xrayTunServiceUserRulePriority
checkConstants.xrayTunPerAppTunRulePriority
checkConstants.xrayTunDnsRulePriority
checkConstants.xrayTunMainRulePriority
checkConstants.tunAutoRouteRulePriority
];
true
)
];
+6 -3
View File
@@ -43,7 +43,8 @@ let
tunedRuntime = runtimeDir zapret2Tuned globalService;
noAutoRuntime = runtimeDir zapret2NoAuto globalService;
z2kRuntime = runtimeDir zapret2Z2k globalService;
cutoffProbe = zapret2Global.config.systemd.services.proxy-suite-zapret2-cutoff.serviceConfig.ExecStart;
cutoffProbe =
zapret2Global.config.systemd.services.proxy-suite-zapret2-cutoff.serviceConfig.ExecStart;
socksStart = fixture: fixture.config.systemd.services.proxy-suite-socks.serviceConfig.ExecStart;
proxyCtlEnv = fixture: (mkProxyCtlDerived fixture).wrapperEnv;
@@ -67,7 +68,8 @@ in
== "proxy-suite";
assert envValue zapret2PerApp perAppService "HOSTLIST_BASE=" == "/var/lib/proxy-suite/zapret2";
assert
envValue zapret2PerApp perAppService "Z2K_STATE_DIR_OVERRIDE=" == "/var/lib/proxy-suite/zapret2/circular";
envValue zapret2PerApp perAppService "Z2K_STATE_DIR_OVERRIDE="
== "/var/lib/proxy-suite/zapret2/circular";
true
)
@@ -85,7 +87,8 @@ in
assert !(zapretDiscordYoutubeGlobal.config.systemd.services ? proxy-suite-zapret2-cutoff);
assert (proxyCtlEnv zapret2Global).ZAPRET_CUTOFF_ENABLED == "1";
assert
envValue zapret2Global globalService "Z2K_TCP16_ASN=" == "/var/lib/proxy-suite/zapret2/cutoff/asn.txt";
envValue zapret2Global globalService "Z2K_TCP16_ASN="
== "/var/lib/proxy-suite/zapret2/cutoff/asn.txt";
true
)
+7 -1
View File
@@ -46,7 +46,13 @@ let
proxyInboundsFile
proxyInboundsSpecFile
;
inherit (nftr) perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile ip nft;
inherit (nftr)
perAppTunChainFile
perAppTproxyRulesFile
perAppZapretRulesFile
ip
nft
;
};
in
pkgs.runCommand "proxy-suite-README.md" { nativeBuildInputs = [ pkgs.python3 ]; } ''
+11 -2
View File
@@ -377,7 +377,12 @@ def cmd_tor(verb="status", *args):
usage("tor [status|on|off|newnym]")
_toggle(unit, "tor", verb, *args)
if verb == "status" and svc_active(unit):
print(f"bootstrap {_tor_bootstrap()}")
# Extra detail: the unit's state stands without it, for a user outside the group
# or a Tor that has not opened its socket yet. The reason is on stderr.
try:
print(f"bootstrap {_tor_bootstrap()}")
except SystemExit:
print("bootstrap unknown")
def _emit(text, qr):
@@ -1279,7 +1284,8 @@ def cmd_pin(tag="", *_):
# Dismissed.
if status or not tag:
return
if os.path.exists(_outbound_disabled_marker(tag)):
# The inventory too: the marker sits in a dir only root and the group can look into.
if os.path.exists(_outbound_disabled_marker(tag)) or tag in _outbound_disabled():
die(f"Outbound '{tag}' is disabled; enable it first: proxy-ctl proxy outbounds enable {tag}")
status, escaped = _run(["systemd-escape", "--", tag], capture=True)
if status:
@@ -1481,6 +1487,9 @@ def _runtime_entry_rm(kind, tag="", *_):
usage(f"proxy {_runtime_noun(kind)} rm <tag>")
path = _runtime_path(kind, tag)
if not os.path.exists(path):
# The dir may be root-only: an entry that is there looks absent from outside it.
if _runtime_hidden(kind):
die(f"Cannot see the entry for '{tag}' in {_runtime_dir(kind)} - {ask_group()}")
die(f"No runtime {kind} named '{tag}'. Ones declared in the NixOS configuration are removed there.")
try:
os.unlink(path)
+2 -1
View File
@@ -307,7 +307,8 @@ def inbound_rows(_):
# A listener behind the onion service has a second row, for its .onion link.
return [
{
"key": "/".join(ctl._s(x.get(k) or "") for k in ("tag", "user", "variant")),
# The TUI titles its menu with the key: no trailing "/" for the plain link.
"key": "/".join(ctl._s(x.get(k)) for k in ("tag", "user", "variant") if x.get(k)),
**{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port", "variant")},
**({"type": f"{ctl._s(x.get('type') or '')} (onion)"} if x.get("variant") == "onion" else {}),
}
+18
View File
@@ -540,6 +540,19 @@ class RuntimeEntryTest(EnvTest):
self.assertNotEqual(run(ctl.cmd_outbounds, "enable", "primary")[0], 0)
self.assertNotEqual(run(ctl.cmd_outbounds, "enable", "../primary")[0], 0)
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
def test_rm_says_so_when_the_dir_is_out_of_reach(self):
"""outbounds.d is root-only without the group: the entry is there, it just cannot be seen."""
ok(ctl.cmd_outbounds, "add", "de", "vless://u@de.test:443")
os.chmod(self.path("outbounds.d"), 0o000)
try:
status, _, err = run(ctl.cmd_outbounds, "rm", "de")
finally:
os.chmod(self.path("outbounds.d"), 0o700)
self.assertNotEqual(status, 0)
self.assertIn("Cannot see the entry for 'de'", err)
self.assertNotIn("No runtime outbound", err)
def test_rm_takes_the_marker_along(self):
ok(ctl.cmd_outbounds, "add", "de", "vless://u@de.test:443")
ok(ctl.cmd_outbounds, "disable", "de")
@@ -955,6 +968,11 @@ class TorTest(EnvTest):
self.assertNotEqual(status, 0)
self.assertIn("not running", err)
self.assertNotEqual(run(ctl.cmd_tor, "bogus")[0], 0)
# Status still reports the unit.
status, out, err = run(ctl.cmd_tor)
self.assertEqual(status, 0)
self.assertIn("bootstrap unknown", out)
self.assertIn("not running", err)
class BadExitTest(EnvTest):
+1 -1
View File
@@ -114,7 +114,7 @@ class ModelTest(unittest.TestCase):
]
with mock.patch.object(ctl, "_inbound_links", lambda: links):
plain, onion = model.inbound_rows({})
self.assertNotEqual(plain["key"], onion["key"])
self.assertEqual((plain["key"], onion["key"]), ("ws/alice", "ws/alice/onion"))
self.assertEqual((plain["type"], onion["type"]), ("vless", "vless (onion)"))
self.assertEqual(model._link(plain, "--qr"), ["inbounds", "link", "ws", "alice", "--qr"])
self.assertEqual(model._link(onion, "--qr"), ["inbounds", "link", "ws", "alice", "--onion", "--qr"])
+9 -9
View File
@@ -10,15 +10,15 @@
sing-box.overrideAttrs (old: {
postConfigure = (old.postConfigure or "") + ''
tun=vendor/github.com/sagernet/sing-tun
chmod -R u+w "$tun"
cp ${./patches/sing-tun-netlink-groups-probe.go} "$tun/monitor_linux_groups_probe.go"
substituteInPlace "$tun/monitor_linux.go" --replace-fail \
'func NewNetworkUpdateMonitor(logger logger.Logger) (NetworkUpdateMonitor, error) {' \
'func NewNetworkUpdateMonitor(logger logger.Logger) (NetworkUpdateMonitor, error) {
if netlinkGroupsBanned() {
return nil, ErrNetlinkBanned
}'
tun=vendor/github.com/sagernet/sing-tun
chmod -R u+w "$tun"
cp ${./patches/sing-tun-netlink-groups-probe.go} "$tun/monitor_linux_groups_probe.go"
substituteInPlace "$tun/monitor_linux.go" --replace-fail \
'func NewNetworkUpdateMonitor(logger logger.Logger) (NetworkUpdateMonitor, error) {' \
'func NewNetworkUpdateMonitor(logger logger.Logger) (NetworkUpdateMonitor, error) {
if netlinkGroupsBanned() {
return nil, ErrNetlinkBanned
}'
'';
passthru = (old.passthru or { }) // {
rootlessNetlink = true;
+6 -1
View File
@@ -70,7 +70,12 @@ def generate_obfuscation(declared: dict[str, Any], stored: dict[str, Any]) -> di
pick("jmin", lambda v: jmin_low <= v <= jmin_high, lambda: rng.randint(jmin_low, jmin_high))
jmin = values["jmin"] if type(values["jmin"]) is int else 0
pick("jmax", lambda v: jmin + 8 <= v <= max(jmin + 8, 250), lambda: rng.randint(jmin + 8, max(jmin + 8, 250)))
pick("s1", lambda v: 15 <= v <= 150, lambda: rng.randint(15, 150))
s2_declared = values.get("s2") if type(values.get("s2")) is int else None
pick(
"s1",
lambda v: 15 <= v <= 150 and (s2_declared is None or v + HANDSHAKE_SIZE_DIFFERENCE != s2_declared),
lambda: rng.randint(15, 150),
)
s1 = values["s1"] if isinstance(values["s1"], int) else None
pick(
"s2",
+7
View File
@@ -142,6 +142,13 @@ class ObfuscationTests(unittest.TestCase):
self.assertTrue(values["jmin"] < 20)
self.assertNotIn(7, [values[key] for key in ("h2", "h3", "h4")])
def test_generated_s1_avoids_declared_s2(self):
# A stored S1 that no longer fits is replaced too.
for stored in ({}, {"s1": 44}):
for _ in range(200):
values = awg_inbound.generate_obfuscation({"s2": 100}, stored)
self.assertNotEqual(values["s1"] + 56, 100)
class StateTests(Fixture):
def test_prepare_creates_private_state_and_server_config(self):