feat: tproxy lan gateway, killswitch; fix: zapret2 fixes, various other

This commit is contained in:
FUFSoB committed 2026-09-23 01:12:31 +05:00
1 parent 4bcc168b2a
commit ae8f65da2e
54 files changed
+1880 -143

No files matched your search

+35 -6
View File
@@ -11,6 +11,8 @@ let
profiles = awgCfg.profiles;
profileNames = builtins.attrNames profiles;
globalProfileNames = builtins.attrNames derived.awgGlobalProfiles;
inherit (derived.constants) awgGlobalFwmark awgGlobalGroup;
killSwitchUnit = "proxy-suite-killswitch.service";
# Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick.
tunnelOutbounds = derived.awgTunnelOutbounds;
interfaceProfiles = lib.filterAttrs (
@@ -135,17 +137,31 @@ let
) " -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.
# TProxy let them past. A global one under the kill switch marks them with a mark it knows.
prepareCommand = profile: output: ''
${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}"
if profile.asOutbound == "interface" then
" --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}"
else
lib.optionalString (derived.killSwitchEnabled && profile.asOutbound == null) " --fwmark ${toString awgGlobalFwmark} --resolve-endpoints"
}
'';
# Under the kill switch, glibc would hand the Endpoint lookup to nscd or systemd-resolved,
# whose own queries the kill switch rejects. With both out of the way it asks resolved's
# upstreams itself, under the unit's group, and awg-quick gets the Endpoint as an address.
ownLookups = pkgs.writeShellScript "proxy-suite-awg" ''
mount=${pkgs.util-linux}/bin/mount
# Best effort: at worst the lookup goes the usual way.
if [ -S /run/nscd/socket ]; then $mount --bind /dev/null /run/nscd/socket || true; fi
if [ -s /run/systemd/resolve/resolv.conf ]; then
$mount --bind /run/systemd/resolve/resolv.conf /etc/resolv.conf || true
fi
exec "$@"
'';
mkService =
name: profile:
let
@@ -153,7 +169,7 @@ let
configPath = runtimeConfig name profile;
prepare = pkgs.writeShellScript "proxy-suite-awg" ''
set -euo pipefail
${prepareCommand profile (lib.escapeShellArg configPath)}
${lib.optionalString (derived.killSwitchEnabled && !outbound) "${pkgs.util-linux}/bin/unshare --mount ${ownLookups} "}${prepareCommand profile (lib.escapeShellArg configPath)}
'';
proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" ''
set -euo pipefail
@@ -247,7 +263,11 @@ let
"proxy-suite-zapret.service"
]
++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
wants = [
"network-online.target"
]
++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"
++ lib.optional derived.killSwitchEnabled killSwitchUnit;
wantedBy = lib.optionals profile.autostart [ "multi-user.target" ];
conflicts = allProfileConflicts name ++ [
"proxy-suite-tun.service"
@@ -291,6 +311,11 @@ let
// lib.optionalAttrs (cfg.proxy.enable && !outbound) {
ExecStopPost = proxyBypassDown;
}
# The Endpoint lookup (ownLookups) gets past the kill switch by this group, so a
# profile that dropped can come back while the kill switch holds.
// lib.optionalAttrs (derived.killSwitchEnabled && !outbound) {
Group = awgGlobalGroup;
}
# A failed handshake leaves no routes behind here, so try again later.
// lib.optionalAttrs outbound {
Restart = "on-failure";
@@ -451,6 +476,10 @@ in
]
++ lib.optional (builtins.any (ob: ob.kind == "userspace") tunnelOutbounds) awgCfg.wireproxyPackage;
services.proxy-suite.internal.groups = lib.optional (
derived.killSwitchEnabled && globalProfileNames != [ ]
) awgGlobalGroup;
services.proxy-suite.internal.kernelModulePackages =
lib.optionals (awgCfg.kernelModulePackage != null)
[
+1
View File
@@ -46,6 +46,7 @@ let
perAppTproxyRulesFile
perAppZapretRulesFile
nftablesRulesFile
killSwitchRulesFile
ip
nft
;
@@ -38,14 +38,24 @@ in
(mkDnsServer "local" proxyCfg.dns.local)
];
inbounds = [ ];
# Counters per user, inbound and outbound for proxy-suite-inbound-stats, and who is
# connected right now, on loopback only.
# connected right now, from where. A socket rather than loopback, which any local
# user could ask: the start script's setgid directory gives it the group that may
# read the stats. The listeners are appended at start.
inbounds = [
{
tag = "api-in";
protocol = "dokodemo-door";
listen = "${derived.constants.inboundStatsApiSocket},0660";
settings = {
address = "127.0.0.1";
network = "unix";
};
}
];
stats = { };
api = {
tag = "api";
listen = "127.0.0.1:${toString derived.constants.inboundStatsApiPort}";
services = [ "StatsService" ];
};
policy = {
@@ -95,6 +105,13 @@ in
# IPIfNonMatch the network-only final rule matches names unresolved.
domainStrategy = if proxyInboundsResolveInSingBox then "AsIs" else "IPOnDemand";
domainMatcher = "hybrid";
rules = inboundRules.xrayInboundRules;
rules = [
{
ruleTag = "inbound-stats-api";
inboundTag = [ "api-in" ];
outboundTag = "api";
}
]
++ inboundRules.xrayInboundRules;
};
}
@@ -219,7 +219,7 @@ let
route = {
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets ++ rules.remoteRuleSets;
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
final = if (proxyCfg.routing.default == "proxy") then "proxy" else "direct";
}
+1
View File
@@ -58,6 +58,7 @@ let
transport
tls
reality
hysteria
xrayJson
jsonFile
;
+11
View File
@@ -138,6 +138,17 @@ in
}
))
(lib.mkIf derived.ruleSetsEnabled (
import ./rulesets.nix {
inherit
lib
pkgs
cfg
derived
;
}
))
(lib.mkIf (derived.proxyInboundsEnabled && derived.proxyInboundsAwg != [ ]) (
import ./amnezia-wg-inbounds.nix {
inherit
+59 -7
View File
@@ -23,6 +23,43 @@ let
perAppRoutingCfg = cfg.perAppRouting;
globalTun = proxyCfg.tun;
globalTproxy = proxyCfg.tproxy;
# Forwarding for what gateway clients send that TProxy does not take (ping, the LAN itself).
tproxyLanSysctl =
lib.optionalAttrs (proxyEnabled && globalTproxy.enable && globalTproxy.lanInterfaces != [ ])
(
{
"net.ipv4.ip_forward" = 1;
}
// lib.optionalAttrs proxyCfg.ipv6 {
"net.ipv6.conf.all.forwarding" = 1;
}
);
# proxy.routing.ruleSets, with the format settled and the file sing-box reads.
ruleSets = lib.mapAttrsToList (
name: rs:
let
format =
if rs.format != null then
rs.format
else if lib.hasSuffix ".srs" (lib.head (lib.splitString "?" rs.url)) then
"binary"
else
"source";
in
rs
// {
inherit name format;
path = "${constants.ruleSetsDir}/${name}.${if format == "binary" then "srs" else "json"}";
# Its domain rules only, for DNS rules: sing-box 1.14 refuses an IP-only rule set there,
# and a legacy address filter would send every other name to that rule's server first.
dnsPath = "${constants.ruleSetsDir}/${name}.dns.json";
}
) proxyCfg.routing.ruleSets;
ruleSetsEnabled = proxyEnabled && ruleSets != [ ];
# Some global tunnel for it to guard.
killSwitchEnabled =
cfg.killSwitch.enable
&& (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalProfiles != { });
perAppRoutingTun = cfg.perAppRouting.tun;
perAppRoutingTproxy = cfg.perAppRouting.tproxy;
zapretCfg = cfg.zapret;
@@ -188,6 +225,7 @@ let
proxyInboundUdpTypes = [
"amneziawg"
"hysteria2"
"shadowsocks"
"socks"
];
@@ -203,13 +241,16 @@ let
]
)
) proxyInbounds;
# h3-only xhttp listeners are UDP-only, leaving the TCP port to a web server.
proxyInboundIsH3Only =
l: l.type != null && l.transport.type == "xhttp" && l.tls.enable && l.tls.alpn == [ "h3" ];
# QUIC listeners are UDP-only: hysteria2, and h3-only xhttp, which leaves the TCP port to a
# web server.
proxyInboundIsUdpOnly =
l:
l.type == "hysteria2"
|| 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.listener.type != null && ib.listener.type != "amneziawg" && !proxyInboundIsUdpOnly ib.listener;
torOnionEnabled = torCfg.enable && torCfg.onionService.enable && proxyInboundsEnabled;
torOnionInbounds =
if !torOnionEnabled then
@@ -221,7 +262,7 @@ let
proxyInboundFirewallPorts = lib.unique (
map (ib: ib.listener.port) (
builtins.filter (
ib: !proxyInboundIsH3Only ib.listener && ib.listener.type != "amneziawg"
ib: !proxyInboundIsUdpOnly ib.listener && ib.listener.type != "amneziawg"
) proxyInboundsPublic
)
);
@@ -232,7 +273,7 @@ let
ib:
ib.listener.type == null
|| builtins.elem ib.listener.type proxyInboundUdpTypes
|| proxyInboundIsH3Only ib.listener
|| proxyInboundIsUdpOnly ib.listener
) proxyInboundsPublic
)
);
@@ -357,14 +398,21 @@ let
# Written by every backend start script; proxy-ctl reads the socks copy.
outboundInventoryFile = "${runtimeDir}/proxy-suite-socks/outbounds.json";
inboundStatsApiPort = 18536;
inboundStatsApiSocket = "${runtimeDir}/proxy-suite-inbounds/api/stats.sock";
# Mark and table sending the AmneziaWG listeners' diverted packets to the local stack,
# clear of proxy.tproxy's and perAppRouting's (asserted).
awgInboundFwmark = 20;
awgInboundRouteTable = 103;
awgInboundRulePriority = 8990;
# A global AmneziaWG profile's own packets carry this mark (awg-quick's default table,
# pinned so the kill switch knows it), and its unit runs with this group, whose lookups
# (an Endpoint's name) get past the kill switch.
awgGlobalFwmark = 51820;
awgGlobalGroup = "proxy-suite-awg";
# sing-box's fake IP caches, one per TUN config; the start script hands it to the backend.
fakeIpCacheDir = "${stateDir}/fakeip";
# Downloaded proxy.routing.ruleSets, one file each, written by the service user.
ruleSetsDir = "${stateDir}/rulesets";
# Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches.
outboundTestPort = 18537;
inboundStatsFile = "${stateDir}/inbound-stats.json";
@@ -436,6 +484,10 @@ in
perAppRoutingCfg
globalTun
globalTproxy
tproxyLanSysctl
killSwitchEnabled
ruleSets
ruleSetsEnabled
perAppRoutingTun
perAppRoutingTproxy
zapretCfg
+11
View File
@@ -49,11 +49,22 @@ in
allowedTCPPorts = forward internal.firewall.allowedTCPPorts;
allowedUDPPorts = forward internal.firewall.allowedUDPPorts;
extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules;
extraInputRules = forward internal.firewall.extraInputRules;
trustedInterfaces = forward internal.firewall.trustedInterfaces;
};
boot.extraModulePackages = forward internal.kernelModulePackages;
boot.kernel.sysctl = lib.mapAttrs (_: lib.mkDefault) cfg.internal.sysctl;
assertions = [
{
assertion =
cfg.internal.firewall.extraInputRules == ""
|| !config.networking.firewall.enable
|| config.networking.nftables.enable;
message = "proxy-suite: proxy.tproxy.lanInterfaces needs the nftables firewall (networking.nftables.enable); the iptables one drops the gateway clients' diverted traffic";
}
];
}
]
))
+2 -1
View File
@@ -14,7 +14,8 @@
# interface). The newest handshake counts as seen, and .awgPeers keeps each user's latest.
reduce ($q.stat // [])[] as $s (.;
($s.name | split(">>>")) as $n
| if ($n | length) == 4 and ($n[0] | IN("user", "inbound", "outbound")) and $n[2] == "traffic" then
| if ($n | length) == 4 and ($n[0] | IN("user", "inbound", "outbound")) and $n[2] == "traffic"
and ([$n[0], $n[1]] | IN(["inbound", "api-in"], ["outbound", "api"]) | not) then
.days[$day][$n[0]][$n[1]][if $n[3] == "uplink" then "up" else "down" end] += (($s.value // 0) | tonumber)
else . end)
| reduce ($online.users // [])[] as $u (.;
+72 -2
View File
@@ -6,7 +6,8 @@
}:
let
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser;
inherit (import ./derived.nix { inherit lib cfg; }) constants awgGlobalProfiles;
inherit (constants) serviceUser;
proxyCfg = cfg.proxy;
globalTproxy = proxyCfg.tproxy;
perAppTun = cfg.perAppRouting.tun;
@@ -67,6 +68,12 @@ let
'';
tproxyLocalSubnetLines = mkLocalSubnetLines globalTproxy.localSubnets;
lanInterfaceSet = "{ ${lib.concatMapStringsSep ", " (i: ''"${i}"'') globalTproxy.lanInterfaces} }";
# Devices using this host as their gateway, past the destinations nobody diverts.
tproxyLanLines = lib.optionalString (globalTproxy.lanInterfaces != [ ]) (
mkTproxyLines "iifname ${lanInterfaceSet} " " meta mark set ${toString globalTproxy.fwmark}"
);
perAppTproxyLocalSubnetLines = mkLocalSubnetLines perAppTproxy.localSubnets;
# Without ipv6, IPv6 packets are left alone, as if the table were still `ip`.
@@ -89,11 +96,12 @@ let
# are served here, not taken by the tproxy socket. A resolver this host
# runs for the LAN is one of them.
fib daddr type local return
${tproxyLocalSubnetLines}
${tproxyLanLines}
# Packets re-entering via loopback after output marking should not
# be skipped just because the host has an RFC1918 source address.
iifname != "lo" ip saddr $RESERVED_IP return
iifname != "lo" ip6 saddr $RESERVED_IP6 return
${tproxyLocalSubnetLines}
${mkTproxyLines "" " meta mark set ${toString globalTproxy.fwmark}"}
}
chain output {
@@ -140,6 +148,67 @@ let
}
'';
# Everything proxy-suite sends itself, or has already taken into the proxy, gets past; the
# rest is what TUN, TProxy or a global AmneziaWG profile would have taken, had it been up.
sshProxyUser = cfg.sshProxy.serviceUser;
killSwitchMarks = [
globalTproxy.fwmark
globalTproxy.proxyMark
]
++ lib.optional perAppTun.enable perAppTun.fwmark
++ lib.optional perAppTproxy.enable perAppTproxy.fwmark
++ lib.optional tgWsProxyBypassEnabled tgWsProxyCfg.fwmark
++ lib.optional (awgGlobalProfiles != { }) constants.awgGlobalFwmark;
awgGlobalInterfaces = lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles;
globalTunEnabled = proxyCfg.enable && proxyCfg.tun.enable;
killSwitchAllowLines = ''
ip daddr $RESERVED_IP accept
ip6 daddr $RESERVED_IP6 accept
${lib.concatMapStrings (cidr: ''
${ipFamily cidr} daddr ${cidr} accept
'') globalTproxy.localSubnets}
ct direction reply accept
'';
killSwitchRulesFile = pkgs.writeText "proxy-suite-routing" ''
${reservedIpBlock}
table inet proxy_suite_killswitch {
chain output {
type filter hook output priority filter; policy accept;
oifname "lo" accept
meta skuid "${serviceUser}" accept
${lib.optionalString globalTunEnabled ''
oifname "${proxyCfg.tun.interface}" accept
# sing-box's auto_redirect hands DNS to the TUN by rewriting it to the TUN's peer,
# while the route still points at the uplink.
ip daddr ${proxyCfg.tun.address} accept
${lib.optionalString proxyCfg.ipv6 "ip6 daddr ${constants.globalTunIPv6Address} accept"}
''}
${lib.optionalString (awgGlobalProfiles != { }) ''
oifname { ${lib.concatMapStringsSep ", " (i: ''"${i}"'') awgGlobalInterfaces} } accept
meta skgid "${constants.awgGlobalGroup}" accept
''}
${lib.optionalString (
cfg.sshProxy.enable && sshProxyUser != null && sshProxyUser != serviceUser
) ''meta skuid "${sshProxyUser}" accept''}
meta mark { ${lib.concatMapStringsSep ", " toString (lib.unique killSwitchMarks)} } accept
# A lookup the proxy did not take would name every site to the LAN resolver.
meta l4proto { tcp, udp } th dport 53 reject with icmpx admin-prohibited
${killSwitchAllowLines}
# DHCP keeps the uplink, NTP the clock that TLS depends on.
udp dport { 67, 68, 123 } accept
reject with icmpx admin-prohibited
}
${lib.optionalString (globalTproxy.lanInterfaces != [ ]) ''
# Gateway clients: what TProxy does not divert is forwarded, to the LAN only.
chain forward {
type filter hook forward priority filter; policy accept;
${killSwitchAllowLines}
iifname ${lanInterfaceSet} reject with icmpx admin-prohibited
}
''}
}
'';
perAppZapretRulesFile = pkgs.writeText "proxy-suite-routing" ''
table inet proxy_suite_per_app_zapret_mark {
chain prerouting {
@@ -192,6 +261,7 @@ in
inherit
reservedIpBlock
nftablesRulesFile
killSwitchRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
+1
View File
@@ -21,6 +21,7 @@
./gui.nix
./tui.nix
./user-control.nix
./kill-switch.nix
./host.nix
];
+2
View File
@@ -68,6 +68,8 @@ in
allowedTCPPorts = internalOption (types.listOf types.port) [ ];
allowedUDPPorts = internalOption (types.listOf types.port) [ ];
extraReversePathFilterRules = internalOption types.lines "";
# nftables firewall only: iptables has no such hook.
extraInputRules = internalOption types.lines "";
trustedInterfaces = internalOption (types.listOf types.str) [ ];
};
# Kernel parameters the services also set when they start.
@@ -0,0 +1,11 @@
{ lib, ... }:
{
options.services.proxy-suite.killSwitch.enable = lib.mkEnableOption ''
a kill switch for the global tunnels (proxy.tun, proxy.tproxy and global AmneziaWG profiles):
once one starts, outgoing traffic that would leave outside it is rejected, also while it
restarts, after it crashes or after its handshake gives up. LAN destinations, DHCP and NTP
stay open; tproxy.lanInterfaces clients keep the LAN but lose the internet. Only
`proxy-ctl killswitch off`, `proxy off`, `proxy tun off`, `proxy tproxy off` or `awg off`
lift it (proxy-suite-killswitch)
'';
}
@@ -28,6 +28,7 @@ in
ips = list "IP CIDRs sent through the proxy." [ "1.1.1.0/24" ];
geosites = list "Geosite names sent through the proxy." [ "netflix" ];
geoips = list "Geoip names sent through the proxy." [ "us" ];
ruleSets = list "Names from ruleSets sent through the proxy." [ "antifilter" ];
};
direct = {
@@ -39,6 +40,7 @@ in
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" ];
ruleSets = list "Names from ruleSets sent direct." [ "ru-services" ];
};
block = {
@@ -46,6 +48,7 @@ in
ips = list "IP CIDRs blocked." [ "203.0.113.0/24" ];
geosites = list "Geosite names blocked." [ "category-ads-all" ];
geoips = list "Geoip names blocked." [ "cn" ];
ruleSets = list "Names from ruleSets blocked." [ "ads" ];
};
rules = mkOption {
@@ -63,5 +66,54 @@ in
}
];
};
ruleSets = mkOption {
type = types.attrsOf (
types.submodule {
options = {
url = mkOption {
type = types.strMatching "https?://.+";
description = "Where the sing-box rule set is downloaded from.";
example = "https://example.com/antifilter.srs";
};
format = mkOption {
type = types.nullOr (
types.enum [
"binary"
"source"
]
);
default = null;
description = ''"binary" (.srs) or "source" (JSON). Null goes by the URL: .srs is binary.'';
};
detour = mkOption {
type = types.enum [
"proxy"
"direct"
];
default = "proxy";
description = "Downloaded through the local proxy, or directly.";
};
};
}
);
default = { };
description = ''
sing-box rule sets kept up to date at runtime, for the ruleSets of proxy, direct, block,
rules and an outbound's routing. They are fetched every ruleSetUpdateInterval and on
`proxy-ctl proxy rulesets update`, and sing-box picks up a new file without a restart;
until the first fetch one matches nothing. Not for backend = "xray".
'';
example = {
antifilter.url = "https://example.com/antifilter.srs";
};
};
ruleSetUpdateInterval = mkOption {
type = types.str;
default = "1d";
description = "How often ruleSets are downloaded again (systemd time span).";
example = "6h";
};
};
}
@@ -41,5 +41,16 @@ in
"fd00::/8"
];
};
lanInterfaces = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Interfaces whose forwarded TCP and UDP is taken through the proxy too: devices on them
that use this host as their gateway. Turns on IP forwarding for the rest (ping, the LAN
itself), which is routed as it is. Needs the nftables firewall on NixOS.
'';
example = [ "br0" ];
};
};
}
+12 -2
View File
@@ -10,6 +10,12 @@ let
geosites = list "Geosite names to match (see geodata)." [ "netflix" ];
geoips = list "Geoip names to match (see geodata; the defaults are country codes only)." [ "us" ];
};
# The client's routing also matches downloaded rule sets, which XRay cannot read.
clientRoutingFields = routingFields // {
ruleSets = list "Names from proxy.routing.ruleSets to match (sing-box and hybrid backends)." [
"antifilter"
];
};
routingRuleType = types.submodule {
options = {
@@ -19,7 +25,7 @@ let
example = "vps-de";
};
}
// routingFields;
// clientRoutingFields;
};
dnsUpstreamType = types.submodule {
@@ -78,10 +84,14 @@ in
dnsUpstreamType
perAppRoutingProfileType
routingFields
clientRoutingFields
routingRuleType
;
}
// import ./types/outbounds.nix { inherit lib routingFields; }
// import ./types/outbounds.nix {
inherit lib;
routingFields = clientRoutingFields;
}
// import ./types/zapret.nix { inherit lib; }
// import ./types/inbounds.nix { inherit lib; }
// import ./types/amnezia-wg.nix { inherit lib; }
@@ -254,6 +254,7 @@ let
"vless"
"vmess"
"trojan"
"hysteria2"
"shadowsocks"
"socks"
"http"
@@ -264,7 +265,8 @@ let
description = ''
Protocol. Set exactly one of type, xrayJson, or jsonFile. "amneziawg" is an AmneziaWG
server on UDP port, with its own interface (see amneziaWg); its traffic is handed to XRay
and leaves like any other listener's.
and leaves like any other listener's. "hysteria2" is QUIC on UDP port: it needs tls (a
certificate) and takes passwords, and no transport, reality or flow.
'';
example = "vless";
};
@@ -345,6 +347,11 @@ let
jsonFile = nullStr "Runtime path to a raw XRay inbound (no share link); tag is overridden and port, if left out, filled in." "/run/secrets/proxy-inbound-vless.json";
hysteria.masquerade = nullStr ''
Site that a hysteria2 listener serves, reverse-proxied, to anything that is not a client
(a browser, a prober). Null answers them with 404.
'' "https://www.example.com";
amneziaWg = mkOption {
type = mkAmneziaWgType name;
default = { };
+2 -1
View File
@@ -125,7 +125,8 @@ in
Some lines let TLS to certain hosting networks handshake and then cut it at 12-34 KB,
which no strategy fixes. z2k's probe checks this line against ~110 known targets when
its network changes and once a day, and for each cut-off network searches a whitelisted
name that nfqws2 then puts into a fake ClientHello: thousands of short TLS connections to
name that nfqws2 then puts into a fake ClientHello (strategySource "z2k" only; ahead of
the nfqws2-keenetic strategies it breaks them): thousands of short TLS connections to
foreign hosting IPs per full run, sent directly and never touched by zapret2. State and
maps live in /var/lib/proxy-suite/zapret2/cutoff; `proxy-ctl zapret cutoff` shows them.
'';
+6 -1
View File
@@ -47,7 +47,8 @@ let
ob:
let
ro = ob.routing;
hasAny = ro.domains != [ ] || ro.ips != [ ] || ro.geosites != [ ] || ro.geoips != [ ];
hasAny =
ro.domains != [ ] || ro.ips != [ ] || ro.geosites != [ ] || ro.geoips != [ ] || ro.ruleSets != [ ];
in
lib.optional hasAny {
outbound = resolveTag ob.tag;
@@ -56,6 +57,7 @@ let
ips
geosites
geoips
ruleSets
;
}
) proxyCfg.outbounds;
@@ -78,10 +80,12 @@ let
onionOutbound
;
inherit (cfg) geodata;
inherit (derived) ruleSets;
};
inherit (singBoxRules)
geositeRuleSets
geoIPRuleSets
remoteRuleSets
singBoxRoutingRules
singBoxRouteModeRules
singBoxDnsRules
@@ -111,6 +115,7 @@ in
zapretDirectRules
geositeRuleSets
geoIPRuleSets
remoteRuleSets
singBoxRoutingRules
singBoxRouteModeRules
singBoxDnsRules
+36 -7
View File
@@ -8,6 +8,7 @@
customRuleCategory,
onionOutbound,
geodata,
ruleSets,
}:
let
@@ -28,6 +29,7 @@ let
(mkIPRule rule.outbound rule.ips)
(mkRulesetRule rule.outbound (map (s: "geosite-${s}") rule.geosites))
(mkRulesetRule rule.outbound (map (s: "geoip-${s}") rule.geoips))
(mkRulesetRule rule.outbound (map remoteTag rule.ruleSets))
];
allGeositeNames = lib.unique (
@@ -51,6 +53,24 @@ let
geositeRuleSets = map (mkRuleSet "geosite" geodata.singBox.geosite) allGeositeNames;
geoIPRuleSets = map (mkRuleSet "geoip" geodata.singBox.geoip) allGeoIPNames;
# Downloaded at runtime; sing-box reloads a local rule set when its file changes.
# DNS rules read each one's domain-only copy (see derived.ruleSets).
remoteTag = name: "ruleset-${name}";
remoteDnsTag = name: "ruleset-${name}-dns";
remoteRuleSets = lib.concatMap (rs: [
{
tag = remoteTag rs.name;
type = "local";
inherit (rs) format path;
}
{
tag = remoteDnsTag rs.name;
type = "local";
format = "source";
path = rs.dnsPath;
}
]) ruleSets;
commonRules = [
{
network = [
@@ -82,6 +102,7 @@ let
(mkIPRule "direct" direct.ips)
(mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites))
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
(mkRulesetRule "direct" (map remoteTag r.direct.ruleSets))
];
tgWsProxyRelayDirectRules =
@@ -105,11 +126,13 @@ let
(mkIPRule "block" r.block.ips)
(mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites))
(mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips))
(mkRulesetRule "block" (map remoteTag r.block.ruleSets))
];
proxyGeoRules = lib.flatten [
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
(mkRulesetRule "proxy" (map remoteTag r.proxy.ruleSets))
];
singBoxRoutingRules =
@@ -125,13 +148,16 @@ let
# the ISP's resolver never sees it and cannot spoof the answer; a direct one is looked up
# locally. In the routing's order; block entries resolve however the final says.
mkDnsRules =
server: domains: geosites:
server: domains: geosites: names:
let
tags = map (s: "geosite-${s}") geosites ++ map remoteDnsTag names;
in
lib.optional (domains != [ ]) {
domain_suffix = domains;
inherit server;
}
++ lib.optional (geosites != [ ]) {
rule_set = map (s: "geosite-${s}") geosites;
++ lib.optional (tags != [ ]) {
rule_set = tags;
inherit server;
};
dnsServerFor = category: if category == "direct" then "local" else "remote";
@@ -139,12 +165,14 @@ let
lib.concatMap (
rule:
lib.optionals (customRuleCategory rule.outbound != "block") (
mkDnsRules (dnsServerFor (customRuleCategory rule.outbound)) rule.domains rule.geosites
mkDnsRules (dnsServerFor (customRuleCategory rule.outbound)) rule.domains rule.geosites (
rule.ruleSets or [ ]
)
)
) customRules
++ mkDnsRules "remote" r.proxy.domains [ ]
++ mkDnsRules "local" direct.domains direct.geosites
++ mkDnsRules "remote" [ ] r.proxy.geosites;
++ mkDnsRules "remote" r.proxy.domains [ ] [ ]
++ mkDnsRules "local" direct.domains direct.geosites r.direct.ruleSets
++ mkDnsRules "remote" [ ] r.proxy.geosites r.proxy.ruleSets;
singBoxRouteModeRules = {
common = commonRules;
@@ -160,6 +188,7 @@ in
inherit
geositeRuleSets
geoIPRuleSets
remoteRuleSets
singBoxRoutingRules
singBoxRouteModeRules
singBoxDnsRules
+137
View File
@@ -0,0 +1,137 @@
# proxy.routing.ruleSets: downloaded by the service user into the state directory, where
# sing-box reads them as local rule sets and reloads each one when its file changes.
{
lib,
pkgs,
cfg,
derived,
}:
let
inherit (derived) ruleSets localProxy;
inherit (derived.constants) ruleSetsDir unprivilegedServiceConfig serviceUser;
inherit (cfg.host) privileged;
singBox = "${cfg.proxy.singBox.package}/bin/sing-box";
curl = "${pkgs.curl}/bin/curl";
inherit (localProxy) auth;
passwordSource =
if auth.passwordFile != null then
auth.passwordFile
else if auth.password != null then
pkgs.writeText "proxy-suite-rulesets" auth.password
else
null;
withProxyAuth = lib.any (rs: rs.detour == "proxy") ruleSets && localProxy.authEnabled;
# What sing-box reads until the first download: a rule set that matches nothing.
emptySource = pkgs.writeText "proxy-suite-rulesets.json" (
builtins.toJSON {
version = 3;
rules = [ ];
}
);
emptyBinary = pkgs.runCommand "proxy-suite-rulesets.srs" { } ''
${singBox} rule-set compile --output "$out" ${emptySource}
'';
fetchScript = pkgs.writeShellScript "proxy-suite-rulesets" ''
set -uo pipefail
proxy=(--proxy socks5h://${localProxy.hostPart}:${toString cfg.proxy.listener.port})
${lib.optionalString withProxyAuth ''
proxy+=(--proxy-user ${lib.escapeShellArg auth.username}:"$(< "$CREDENTIALS_DIRECTORY/proxy-password")")
''}
failed=0
# A download replaces the file only once sing-box has read it back, so a bad one never
# reaches the backend; a failed one keeps what was there. Its domain rules go to the copy
# DNS rules read.
fetch() {
local name=$1 url=$2 path=$3 dns=$4 format=$5 detour=$6 tmp dnsTmp
local args=(--fail --silent --show-error --location --max-time 120 --max-filesize 64M)
[ "$detour" = proxy ] && args+=("''${proxy[@]}")
tmp=$(${pkgs.coreutils}/bin/mktemp "$path.XXXXXX") || { failed=1; return; }
dnsTmp=$(${pkgs.coreutils}/bin/mktemp "$dns.XXXXXX") || { rm -f "$tmp"; failed=1; return; }
if ${curl} "''${args[@]}" --output "$tmp" "$url" && valid "$tmp" "$format" &&
domains "$tmp" "$format" > "$dnsTmp" && valid "$dnsTmp" source; then
chmod 0644 "$tmp" "$dnsTmp"
mv -f "$dnsTmp" "$dns"
mv -f "$tmp" "$path"
echo "rule set $name: updated"
else
rm -f "$tmp" "$dnsTmp"
echo "rule set $name: not updated from $url; keeping the one it has" >&2
failed=1
fi
}
valid() {
if [ "$2" = binary ]; then
${singBox} rule-set decompile --output /dev/null "$1" 2>/dev/null
else
${singBox} rule-set compile --output /dev/null "$1" 2>/dev/null
fi
}
domains() {
if [ "$2" = binary ]; then
${singBox} rule-set decompile --output /dev/stdout "$1"
else
cat "$1"
fi | ${pkgs.jq}/bin/jq '.rules = [(.rules // [])[]
| select((.type // "default") == "default"
and (has("domain") or has("domain_suffix") or has("domain_keyword") or has("domain_regex")))
| del(.ip_cidr, .ip_is_private)]'
}
${lib.concatMapStrings (rs: ''
fetch ${
lib.escapeShellArgs [
rs.name
rs.url
rs.path
rs.dnsPath
rs.format
rs.detour
]
}
'') ruleSets}
exit "$failed"
'';
in
{
services.proxy-suite.internal = {
# sing-box refuses to start on a missing rule set: an empty one stands in until the first
# download, and is only copied where no file is yet.
tmpfiles = [
"d ${ruleSetsDir} 0755 ${if privileged then "${serviceUser} ${serviceUser}" else "- -"} -"
]
++ lib.concatMap (rs: [
"C ${rs.path} - - - - ${if rs.format == "binary" then emptyBinary else emptySource}"
"C ${rs.dnsPath} - - - - ${emptySource}"
]) ruleSets;
services.proxy-suite-rulesets = {
description = "proxy-suite - download routing rule sets";
after = [
"network-online.target"
"proxy-suite-socks.service"
];
wants = [ "network-online.target" ];
serviceConfig = unprivilegedServiceConfig [ ] // {
Type = "oneshot";
ExecStart = fetchScript;
StateDirectory = "proxy-suite/rulesets";
StateDirectoryMode = "0755";
LoadCredential = lib.optional withProxyAuth "proxy-password:${passwordSource}";
};
};
timers.proxy-suite-rulesets = {
description = "Periodic proxy-suite rule set download";
wantedBy = [ "timers.target" ];
timerConfig = {
OnActiveSec = "1m";
OnUnitActiveSec = cfg.proxy.routing.ruleSetUpdateInterval;
};
};
};
}
+72 -17
View File
@@ -68,10 +68,7 @@ let
# the autoProxy prober's range must stay clear of.
reservedLoopbackPorts =
builtins.attrValues constants.xrayDnsBridgePorts
++ [
constants.inboundStatsApiPort
constants.outboundTestPort
]
++ [ constants.outboundTestPort ]
++ lib.optionals derived.warpOutboundEnabled [
derived.warpCfg.tunnelPort
derived.warpCfg.directPort
@@ -116,6 +113,7 @@ let
rootlessAssertions = [
(rootlessForbids (proxyEnabled && globalTun.enable) "proxy.tun")
(rootlessForbids (proxyEnabled && globalTproxy.enable) "proxy.tproxy")
(rootlessForbids cfg.killSwitch.enable "killSwitch")
(rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTun.enable) "perAppRouting.tun")
(rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTproxy.enable) "perAppRouting.tproxy")
(rootlessForbids perAppZapretCfg.enable "perAppRouting.zapret")
@@ -144,6 +142,18 @@ let
"proxy-suite: ${item.name} = ${toString item.port} is a privileged port, which services on a ${hostKind} host cannot bind; pick one from 1024 up"
) rootlessPorts;
unknownRuleSets = lib.unique (
builtins.filter (name: !proxyCfg.routing.ruleSets ? ${name}) (
lib.concatMap (category: proxyCfg.routing.${category}.ruleSets) [
"proxy"
"direct"
"block"
]
++ lib.concatMap (rule: rule.ruleSets) proxyCfg.routing.rules
++ lib.concatMap (ob: ob.routing.ruleSets) proxyCfg.outbounds
)
);
featureAssertions = [
# Declaring no outbound at all is legal: they can be added at runtime with
# `proxy-ctl proxy outbounds add`. Only a warning here; the backend still
@@ -212,6 +222,12 @@ let
(mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ])
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
)
(mkAssertion (!proxyEnabled || unknownRuleSets == [ ])
"proxy-suite: routing refers to rule set(s) proxy.routing.ruleSets does not declare: ${lib.concatStringsSep ", " unknownRuleSets}"
)
(mkAssertion (!(pureXrayEnabled && proxyCfg.routing.ruleSets != { }))
"proxy-suite: proxy.routing.ruleSets are sing-box rule sets, which proxy.backend = \"xray\" cannot read; use \"sing-box\" or \"hybrid\""
)
(mkAssertion (
!(pureXrayEnabled && proxyCfg.selection == "selector")
) "proxy-suite: proxy.selection = \"selector\" requires proxy.backend = \"sing-box\" or \"hybrid\"")
@@ -244,6 +260,36 @@ let
(requireEnabled (proxyCfg.autostart == "tproxy") globalTproxy.enable
''proxy-suite: proxy.autostart = "tproxy" requires proxy.tproxy.enable = true''
)
(requireEnabled (
globalTproxy.lanInterfaces != [ ]
) globalTproxy.enable "proxy-suite: proxy.tproxy.lanInterfaces requires proxy.tproxy.enable = true")
(requireEnabled cfg.killSwitch.enable derived.killSwitchEnabled
"proxy-suite: killSwitch.enable needs a global tunnel to guard: proxy.tun, proxy.tproxy or a global amneziaWg profile"
)
(mkAssertion
(
!derived.killSwitchEnabled
|| derived.awgGlobalProfiles == { }
|| !builtins.elem constants.awgGlobalFwmark (
[
globalTproxy.fwmark
globalTproxy.proxyMark
globalTproxy.routeTable
constants.tunAutoRouteTableIndex
]
++ lib.optionals perAppRoutingTun.enable [
perAppRoutingTun.fwmark
perAppRoutingTun.routeTable
]
++ lib.optionals perAppRoutingTproxy.enable [
perAppRoutingTproxy.fwmark
perAppRoutingTproxy.routeTable
]
++ lib.optional tgWsProxyCfg.enable tgWsProxyCfg.fwmark
)
)
"proxy-suite: global AmneziaWG profiles mark and route with ${toString constants.awgGlobalFwmark}, which a proxy.tproxy, perAppRouting or tgWsProxy mark or table also uses"
)
];
# Each case reads "<used> requires <dependency> = true", with option paths as labels.
@@ -406,12 +452,11 @@ let
(
!proxyInboundsEnabled
|| !lib.any (port: builtins.elem port derived.proxyInboundPorts) (
[ derived.constants.inboundStatsApiPort ]
++ map (listener: listener.internalPort) derived.proxyInboundsAwg
map (listener: listener.internalPort) derived.proxyInboundsAwg
++ builtins.attrValues derived.constants.xrayDnsBridgePorts
)
)
"proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the inbounds' stats API on ${toString derived.constants.inboundStatsApiPort}, the AmneziaWG listeners' loopback inbounds from 18700, or 18533-18535)"
"proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, or 18533-18535)"
)
# The prober opens one loopback listener per exit from probeBasePort; the WARP
# and AmneziaWG tunnels open two each from their own bases. They all bind
@@ -441,11 +486,12 @@ let
];
needsPassword = builtins.elem l.type [
"trojan"
"hysteria2"
"shadowsocks"
"socks"
"http"
];
tlsTerminated = l.tls.enable || l.type == "trojan";
tlsTerminated = l.tls.enable || l.type == "trojan" || l.type == "hysteria2";
multiUserShadowsocks = l.type == "shadowsocks" && builtins.length l.users > 1;
eachUser =
condition: fields: message:
@@ -544,12 +590,24 @@ let
(mkAssertion (
!proxyInboundsEnabled || l.flow == null || (l.type == "vless" && l.transport.type == "raw")
) "${prefix}: flow is only valid on a vless listener with transport.type = \"raw\"")
(mkAssertion
(
!proxyInboundsEnabled
|| l.tls.alpn == null
|| !builtins.elem "h3" l.tls.alpn
|| l.type == "hysteria2"
|| (l.transport.type == "xhttp" && l.tls.enable && !l.reality.enable)
)
"${prefix}: tls.alpn \"h3\" is served only by hysteria2, and by the xhttp transport with tls.enable (not REALITY)"
)
# hysteria2 is its own QUIC transport, under a certificate of its own.
(mkAssertion
(!proxyInboundsEnabled || l.type != "hysteria2" || (!l.reality.enable && l.transport.type == "raw"))
"${prefix}: hysteria2 takes no reality or transport; it needs tls.certificateFile and tls.keyFile"
)
(mkAssertion (
!proxyInboundsEnabled
|| l.tls.alpn == null
|| !builtins.elem "h3" l.tls.alpn
|| (l.transport.type == "xhttp" && l.tls.enable && !l.reality.enable)
) "${prefix}: tls.alpn \"h3\" is served only by the xhttp transport with tls.enable (not REALITY)")
!proxyInboundsEnabled || l.hysteria.masquerade == null || l.type == "hysteria2"
) "${prefix}: hysteria.masquerade is for hysteria2 listeners only")
]
) proxyInbounds;
@@ -891,10 +949,7 @@ let
|| (proxyInboundsEnabled && builtins.elem torCfg.socksPort derived.proxyInboundPorts)
|| builtins.elem torCfg.socksPort (
builtins.attrValues constants.xrayDnsBridgePorts
++ [
constants.inboundStatsApiPort
constants.outboundTestPort
]
++ [ constants.outboundTestPort ]
)
)
)
+2
View File
@@ -14,6 +14,7 @@
perAppTproxyRulesFile,
perAppZapretRulesFile,
nftablesRulesFile,
killSwitchRulesFile,
ip,
nft,
}:
@@ -96,6 +97,7 @@ let
perAppTproxyRulesFile
perAppZapretRulesFile
nftablesRulesFile
killSwitchRulesFile
ip
nft
;
+8 -1
View File
@@ -21,6 +21,8 @@ let
proxyInboundsCfg
proxyInboundsEnabled
amneziaWgProfileNamesFile
ruleSets
pkgs
;
inherit (ctx.scripts)
subscriptionTagsFile
@@ -54,6 +56,11 @@ in
SELECTION = selectionMode;
SUB_TAGS_FILE = toString subscriptionTagsFile;
SUB_CACHE_DIR = subscriptionCacheDir;
RULE_SETS_FILE = toString (
pkgs.writeText "proxy-suite-control" (
builtins.toJSON (map (rs: { inherit (rs) name path; }) ruleSets)
)
);
PER_APP_ROUTING_ENABLED = flag perAppRoutingCfg.enable;
PER_APP_ROUTING_PROXYCHAINS_ENABLED = flag perAppRoutingCfg.proxychains.enable;
PER_APP_ROUTING_TUN_ENABLED = flag perAppRoutingTun.enable;
@@ -69,7 +76,7 @@ in
INBOUNDS_LINKS_FILE = proxyInboundsLinksFile;
INBOUNDS_STATS_FILE = constants.inboundStatsFile;
INBOUNDS_XRAY = proxyInboundsXray;
INBOUNDS_API = "127.0.0.1:${toString constants.inboundStatsApiPort}";
INBOUNDS_API = "unix://${constants.inboundStatsApiSocket}";
INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile;
INBOUNDS_SUB_BASE_URL =
if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl;
+21 -4
View File
@@ -26,6 +26,7 @@ let
pureXrayEnabled
globalTun
globalTproxy
tproxyLanSysctl
perAppRoutingTun
perAppRoutingTproxy
userControlCfg
@@ -98,10 +99,26 @@ lib.mkMerge [
) true;
# Inbound listeners are reached from outside, so their ports have to be open.
firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
firewall = lib.mkMerge [
(lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
})
# Gateway clients' diverted packets reach input with their original destination, and
# carry a mark whose table has no route back. Only those: the LAN is not trusted.
(lib.mkIf (tproxyLanSysctl != { }) (
let
rules = lib.concatMapStrings (interface: ''
iifname "${interface}" meta mark ${toString globalTproxy.fwmark} accept
'') globalTproxy.lanInterfaces;
in
{
extraInputRules = rules;
extraReversePathFilterRules = rules;
}
))
];
sysctl = tproxyLanSysctl;
groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) [
userControlCfg.group
@@ -173,7 +173,7 @@ let
--argjson auth_enabled ${if needsLocalProxyAuth then "true" else "false"} \
--arg user ${if needsLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
--arg password ${if needsLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
'.inbounds = $ibs
'.inbounds += $ibs
| .outbounds = $obs + .outbounds
| if $auth_enabled then
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
@@ -220,6 +220,20 @@ let
}
mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json"
# The stats API's socket takes this setgid directory's group: XRay cannot chown it.
API_DIR=$(dirname ${lib.escapeShellArg constants.inboundStatsApiSocket})
rm -rf "$API_DIR"
${
if !constants.privileged then
''mkdir -m 0700 "$API_DIR"''
else if userControlAllows "stats" then
''
install -d -m 2750 -o ${constants.serviceUser} -g ${lib.escapeShellArg userControlCfg.group} "$API_DIR" ||
install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"''
else
''install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"''
}
${writeLinksBlock}
${writeSubscriptionsBlock}
@@ -231,7 +245,7 @@ let
collectInboundStats = pkgs.writeShellScript "proxy-suite-inbounds" ''
set -euo pipefail
file=${lib.escapeShellArg constants.inboundStatsFile}
api=--server=127.0.0.1:${toString constants.inboundStatsApiPort}
api=--server=unix://${constants.inboundStatsApiSocket}
# A timer run and a stop can overlap: each reads and resets part, and both rewrite the file.
exec 9> "$file.lock"
${pkgs.util-linux}/bin/flock 9
@@ -8,9 +8,11 @@ let
ip
nft
nftablesRulesFile
killSwitchRulesFile
constants
globalTun
globalTproxy
tproxyLanSysctl
perAppRoutingTun
proxyCfg
;
@@ -62,8 +64,24 @@ let
family = "inet";
table = xrayTunReplyTable;
};
deleteKillSwitchTable = builders.mkNftDeleteTable {
inherit nft;
family = "inet";
table = "proxy_suite_killswitch";
};
in
{
killSwitchUpScript = pkgs.writeShellScript "proxy-suite-routing" ''
set -euo pipefail
${deleteKillSwitchTable}
${nft} -f ${killSwitchRulesFile}
'';
killSwitchDownScript = pkgs.writeShellScript "proxy-suite-routing" ''
set +e
${deleteKillSwitchTable}
'';
xrayTunUpScript = pkgs.writeShellScript "proxy-suite-routing" ''
set -euo pipefail
@@ -139,6 +157,12 @@ in
}}
${nft} -f ${nftablesRulesFile}
# Set on NixOS already; system-manager hosts only get them here.
${lib.concatStrings (
lib.mapAttrsToList (name: value: ''
${pkgs.procps}/bin/sysctl -q -w ${name}=${toString value}
'') tproxyLanSysctl
)}
${builders.mkTproxyRoutingUp {
inherit ip;
inherit ipv6;
+27 -1
View File
@@ -11,6 +11,8 @@ let
pureXrayEnabled
globalTun
globalTproxy
killSwitchEnabled
awgGlobalProfiles
perAppRoutingTun
perAppRoutingTproxy
perAppZapretEnabled
@@ -37,6 +39,8 @@ let
xrayTunUpScript
tproxyUpScript
tproxyDownScript
killSwitchUpScript
killSwitchDownScript
tunCleanupScript
;
@@ -44,6 +48,7 @@ let
socks = "proxy-suite-socks";
tproxy = "proxy-suite-tproxy";
tun = "proxy-suite-tun";
killSwitch = "proxy-suite-killswitch";
perAppTun = "proxy-suite-per-app-tun";
perAppTproxy = "proxy-suite-per-app-tproxy";
perAppZapret = "proxy-suite-per-app-zapret";
@@ -132,6 +137,23 @@ let
extraServiceConfig.RemainAfterExit = false;
};
}
# Pulled in by every global tunnel and left up when it stops or crashes: only
# proxy-ctl's off verbs take it down. After them, so a first start still fetches
# subscriptions and resolves endpoints directly.
{
enable = killSwitchEnabled;
name = serviceNames.killSwitch;
value = mkOneshotService {
description = "proxy-suite kill switch - reject traffic outside the global tunnel";
after = [
"${serviceNames.socks}.service"
"${serviceNames.tun}.service"
]
++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles);
execStart = killSwitchUpScript;
execStop = killSwitchDownScript;
};
}
{
enable = proxyEnabled && globalTproxy.enable;
name = serviceNames.tproxy;
@@ -143,6 +165,7 @@ let
];
wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ];
requires = [ "${serviceNames.socks}.service" ];
wants = lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
conflicts = [
"${serviceNames.tun}.service"
"${serviceNames.perAppTproxy}.service"
@@ -157,7 +180,10 @@ let
value = mkRestartingService {
description = "${backendDescription} TUN proxy client";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wants = [
"network-online.target"
]
++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service";
wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript;
+28 -17
View File
@@ -11,7 +11,7 @@
let
builders = import ./service/builders.nix { inherit lib pkgs; };
inherit (builders) mkOneshotService;
inherit (builders) mkRestartingService;
zapretCfg = cfg.zapret;
perAppZapretCfg = cfg.perAppRouting.zapret;
@@ -87,8 +87,16 @@ let
if userControlAllows "zapret" then "2775 -g ${lib.escapeShellArg cfg.userControl.group}" else "0755"
} ${runtime.stateDir} ${runtime.circularStateDir}
touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile}
${runtime.initScript} start_fw
'';
# nfqws2 runs supervised; the firewall comes and goes around it.
daemonConfig = runtimeEnv: {
Type = "notify";
ExecReload = "${lib.getExe' pkgs.coreutils "kill"} -HUP $MAINPID";
Environment = runtimeEnv;
};
cutoff = import ./zapret2/cutoff.nix {
inherit
lib
@@ -110,7 +118,7 @@ in
services.proxy-suite.internal.services.proxy-suite-zapret =
lib.mkIf zapretCfg.enable
(mkOneshotService {
(mkRestartingService {
description = "zapret2 DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
@@ -119,20 +127,19 @@ in
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
extraServiceConfig = {
ExecReload = "${runtime.initScript} restart";
Environment = runtime.mkEnv {
execStart = "${runtime.daemonScript}";
execStopPost = "${runtime.initScript} stop_fw";
extraServiceConfig = daemonConfig (
runtime.mkEnv {
runtime = globalRuntime;
pidDir = "/run/proxy-suite-zapret";
};
};
}
);
});
services.proxy-suite.internal.services.proxy-suite-per-app-zapret =
lib.mkIf perAppZapretCfg.enable
(mkOneshotService {
(mkRestartingService {
description = "proxy-suite per-app-routing zapret2 backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
@@ -140,13 +147,17 @@ in
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
execStart = "${runtime.daemonScript}";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
};
execStopPost = [
"${runtime.initScript} stop_fw"
"${perAppZapretMarkDownScript}"
];
extraServiceConfig = daemonConfig (
runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
}
);
});
}
+18 -7
View File
@@ -106,13 +106,11 @@ let
end
'';
# The state layer wraps circular, so it loads after the source's Lua. z2k-tcp16
# does nothing until the cutoff probe has written its maps.
# The state layer wraps circular, so it loads after the source's Lua.
optPrefix = lib.concatStringsSep " " (
map (file: "--lua-init=@${file}") (
source.luaInit
++ [
"${zapret2Sources.z2k}/files/lua/z2k-tcp16.lua"
failStamp
"${zapret2Sources.z2k}/files/lua/z2k-state-persist.lua"
]
@@ -318,13 +316,26 @@ let
"Z2K_STATE_DIR_OVERRIDE=${circularStateDir}"
"Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE=${pidDir}"
]
# The cutoff probe's maps, read by z2k-tcp16.lua; pin.txt forces one name for the line.
++ lib.optionals zapret2Cfg.cutoff.enable [
# The cutoff probe's maps, read by z2k's tcp16 name step; pin.txt forces one name for the line.
++ lib.optionals (zapret2Cfg.cutoff.enable && isZ2k) [
"Z2K_TCP16_ASN=${constants.zapret2CutoffDir}/asn.txt"
"Z2K_TCP16_SNI=${constants.zapret2CutoffDir}/sni.txt"
"Z2K_SNI_PIN=${constants.zapret2CutoffDir}/pin.txt"
"Z2K_TCP16_NETS=${zapret2Sources.z2k}/files/lists/tcp16_nets.txt"
];
initScript = "${zapretBase}/init.d/sysv/zapret2";
# nfqws2 as the unit's main process, with the command line the init script would
# build. The init script backgrounds it with stdout on /dev/null in a oneshot
# unit: when it dies, the unit stays active and the queue's bypass flag lets
# every packet through untouched, with nothing in the log.
daemonScript = pkgs.writeShellScript "proxy-suite-zapret2" ''
. "$ZAPRET_BASE/init.d/sysv/functions"
opt="--qnum=$QNUM $NFQWS2_OPT"
filter_apply_hostlist_target opt
set -f
exec "$NFQWS2" $NFQWS2_OPT_BASE $opt
'';
in
{
inherit
@@ -337,7 +348,7 @@ in
mkCustomScript
mkRuntime
mkEnv
initScript
daemonScript
;
initScript = "${zapretBase}/init.d/sysv/zapret2";
}
+7 -12
View File
@@ -45,17 +45,6 @@ let
)
);
lists = "--hostlist=${src}/etc/nfqws2/lists/user.list --hostlist-exclude=${src}/etc/nfqws2/lists/exclude.list";
# z2k's 16 KB cutoff name, as its generator places it: ahead of circular, with
# no strategy tag, so every strategy carries it.
withSniPick =
profile:
let
parts = splitString " --lua-desync=circular:" profile;
in
if builtins.length parts != 2 then
throw "proxy-suite: expected one circular in the nfqws2-keenetic TCP profile"
else
"${builtins.head parts} --lua-desync=z2k_sni_pick:payload=tls_client_hello:dir=out:blob=z2k_ch:nld=2 --lua-desync=fake:payload=tls_client_hello:dir=out:blob=z2k_ch:optional:repeats=8:tcp_ts=-1000 --lua-desync=circular:${builtins.elemAt parts 1}";
in
{
# Its init script's order. QUIC reads the learned list but never adds to it:
@@ -71,7 +60,9 @@ let
(args "NFQWS_ARGS_UDP")
)
"${args "NFQWS_ARGS_QUIC"} <HOSTLIST_NOAUTO> ${lists}"
"${withSniPick (args "NFQWS_ARGS")} <HOSTLIST> ${lists}"
# No 16 KB cutoff name step: its fake ClientHello ahead of these strategies
# broke every host on a line where the strategies alone work.
"${args "NFQWS_ARGS"} <HOSTLIST> ${lists}"
];
blobArgs = map (replaceStrings [ "@/opt/etc/nfqws2/" ] [ "@${src}/etc/nfqws2/" ]) (
filter (hasPrefix "--blob=") (words (quoted "NFQWS_BASE_ARGS"))
@@ -91,10 +82,14 @@ let
ports = name: between "config_official.sh" "\n${name}=\"" "\"" generator;
in
{
# Its S99zapret2 order. z2k-range-rand resolves the ranges its strategies
# write (repeats=6-10); without it nfqws2 sends each fake once.
luaInit = map (name: "${src}/files/lua/${name}.lua") [
"z2k-alert"
"z2k-quic-silence"
"z2k-tcp16"
"z2k-fooling-ext"
"z2k-range-rand"
"z2k-modern-core"
];
ports = {