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

+6 -1
View File
@@ -16,6 +16,7 @@ Inspired by [Throne](https://github.com/throneproj/Throne) (formerly NekoRay), [
- Local SOCKS5/HTTP proxy on `127.0.0.1:1080`, backed by sing-box, XRay, or both
- Global TProxy or TUN mode, on demand or at boot
- A kill switch for the global tunnels (TUN, TProxy, AmneziaWG): nothing leaves outside them while they restart or after they fail
- Per-app routing: `proxy-ctl apps run <profile> -- <cmd>` through proxychains, a per-app TUN/TProxy, or zapret
- Outbounds from URLs, raw JSON or subscriptions; manual or latency-based selection; per-outbound routing
- vless (REALITY, TLS), vmess, trojan, shadowsocks, hysteria2, socks, http; TUIC, AnyTLS and NaïveProxy on sing-box, XHTTP/ECH on XRay
@@ -26,7 +27,7 @@ Inspired by [Throne](https://github.com/throneproj/Throne) (formerly NekoRay), [
- Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel
- Cloudflare WARP from a `wgcf` profile, as an outbound or an AWG VPN profile
- Tor as an outbound, with `.onion` names routed to it automatically, bridges (obfs4, webtunnel, meek, snowflake), and an onion service in front of the server inbounds
- Server inbounds (XRay protocols and multi-user AmneziaWG) with share links, QR codes, per-user subscriptions and traffic stats
- Server inbounds (XRay protocols, hysteria2, and multi-user AmneziaWG) with share links, QR codes, per-user subscriptions and traffic stats
- Proxy Suite GUI (a desktop app with a tray icon), the `proxy-ctl` CLI, and the `proxy-tui` terminal UI
## Setup
@@ -158,6 +159,7 @@ Secrets and changes need root, or the userControl group.
proxy subs add [tag] <url> add a subscription at runtime; no tag: named after its host
proxy subs rm <tag> remove a runtime subscription
proxy subs link <tag> [--qr] its URL
proxy rulesets [list|update] routing rule sets: when each was fetched; update fetches them now
proxy config [--raw] client config to import elsewhere; --raw: as running
proxy tun [status|on|off] global TUN mode
proxy tproxy [status|on|off] global TProxy mode
@@ -182,6 +184,9 @@ Secrets and changes need root, or the userControl group.
awg [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile]
killswitch [status|on|off] reject traffic outside the global tunnel; up with
TUN, TProxy or AWG, lifted only by off here or on them
ssh [status|on|off] SSH SOCKS5 tunnel
warp [status|on|off] WARP tunnel behind the warp outbound
tor [status|on|off] Tor, behind the tor outbound and the onion service
+1 -1
View File
@@ -95,7 +95,7 @@ done
while true; do
ask SSH_PORT "SSH port" "22"
if [[ $SSH_PORT =~ ^[0-9]+$ ]] && ((SSH_PORT >= 1 && SSH_PORT <= 65535)) &&
[[ ! " 80 443 2053 8443 18533 18534 18535 18536 " == *" $SSH_PORT "* ]]; then
[[ ! " 80 443 2053 8443 18533 18534 18535 " == *" $SSH_PORT "* ]]; then
break
fi
reject "A free port from 1 to 65535 (80, 443, 2053 and 8443 are taken)." SSH_PORT
+26 -2
View File
@@ -48,6 +48,8 @@ Part of the [proxy-suite options reference](./index.md).
- [subnet](#services-proxy-suite-inbounds-listeners-name-amneziawg-subnet)
- [subnet6](#services-proxy-suite-inbounds-listeners-name-amneziawg-subnet6)
- [flow](#services-proxy-suite-inbounds-listeners-name-flow)
- hysteria
- [masquerade](#services-proxy-suite-inbounds-listeners-name-hysteria-masquerade)
- [jsonFile](#services-proxy-suite-inbounds-listeners-name-jsonfile)
- [method](#services-proxy-suite-inbounds-listeners-name-method)
- [port](#services-proxy-suite-inbounds-listeners-name-port)
@@ -770,6 +772,27 @@ null
"xtls-rprx-vision"
```
<a id="services-proxy-suite-inbounds-listeners-name-hysteria-masquerade"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.hysteria\.masquerade
Site that a hysteria2 listener serves, reverse-proxied, to anything that is not a client
(a browser, a prober)\. Null answers them with 404\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"https://www.example.com"
```
<a id="services-proxy-suite-inbounds-listeners-name-jsonfile"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.jsonFile
@@ -1292,10 +1315,11 @@ one of “raw”, “ws”, “grpc”, “httpupgrade”, “xhttp”
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\.
*Type:*
null or one of “vless”, “vmess”, “trojan”, “shadowsocks”, “socks”, “http”, “amneziawg”
null or one of “vless”, “vmess”, “trojan”, “hysteria2”, “shadowsocks”, “socks”, “http”, “amneziawg”
*Default:*
+10
View File
@@ -10,6 +10,7 @@ Update the module option docs there instead of editing these files by hand.
- [geodata](./geodata.md)
- [gui](./gui.md)
- [inbounds](./inbounds.md)
- [killSwitch](./killSwitch.md)
- [perAppRouting](./perAppRouting.md)
- [proxy](./proxy.md)
- [sshProxy](./sshProxy.md)
@@ -72,6 +73,9 @@ services.proxy-suite = {
group = "nginx";
};
};
killSwitch = {
enable = false;
};
perAppRouting = {
createDefaultProfiles = false;
enable = false;
@@ -159,6 +163,7 @@ services.proxy-suite = {
geoips = [ ];
geosites = [ ];
ips = [ ];
ruleSets = [ ];
};
default = "proxy";
direct = {
@@ -166,6 +171,7 @@ services.proxy-suite = {
geoips = [ ];
geosites = [ ];
ips = [ ];
ruleSets = [ ];
};
directRu = true;
proxy = {
@@ -173,7 +179,10 @@ services.proxy-suite = {
geoips = [ ];
geosites = [ ];
ips = [ ];
ruleSets = [ ];
};
ruleSetUpdateInterval = "1d";
ruleSets = { };
rules = [ ];
};
selection = "first";
@@ -187,6 +196,7 @@ services.proxy-suite = {
tproxy = {
enable = false;
fwmark = 1;
lanInterfaces = [ ];
localSubnets = [
"192.168.0.0/16"
];
+34
View File
@@ -0,0 +1,34 @@
# services.proxy-suite.killSwitch
Part of the [proxy-suite options reference](./index.md).
## Options
- killSwitch
- [enable](#services-proxy-suite-killswitch-enable)
<a id="services-proxy-suite-killswitch-enable"></a>
## services\.proxy-suite\.killSwitch\.enable
Whether to enable 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)
\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
+235
View File
@@ -51,6 +51,7 @@ Part of the [proxy-suite options reference](./index.md).
- [geoips](#services-proxy-suite-proxy-outbounds-routing-geoips)
- [geosites](#services-proxy-suite-proxy-outbounds-routing-geosites)
- [ips](#services-proxy-suite-proxy-outbounds-routing-ips)
- [ruleSets](#services-proxy-suite-proxy-outbounds-routing-rulesets)
- [singBoxJson](#services-proxy-suite-proxy-outbounds-singboxjson)
- [tag](#services-proxy-suite-proxy-outbounds-tag)
- [url](#services-proxy-suite-proxy-outbounds-url)
@@ -62,18 +63,27 @@ Part of the [proxy-suite options reference](./index.md).
- [geoips](#services-proxy-suite-proxy-routing-block-geoips)
- [geosites](#services-proxy-suite-proxy-routing-block-geosites)
- [ips](#services-proxy-suite-proxy-routing-block-ips)
- [ruleSets](#services-proxy-suite-proxy-routing-block-rulesets)
- [default](#services-proxy-suite-proxy-routing-default)
- direct
- [domains](#services-proxy-suite-proxy-routing-direct-domains)
- [geoips](#services-proxy-suite-proxy-routing-direct-geoips)
- [geosites](#services-proxy-suite-proxy-routing-direct-geosites)
- [ips](#services-proxy-suite-proxy-routing-direct-ips)
- [ruleSets](#services-proxy-suite-proxy-routing-direct-rulesets)
- [directRu](#services-proxy-suite-proxy-routing-directru)
- proxy
- [domains](#services-proxy-suite-proxy-routing-proxy-domains)
- [geoips](#services-proxy-suite-proxy-routing-proxy-geoips)
- [geosites](#services-proxy-suite-proxy-routing-proxy-geosites)
- [ips](#services-proxy-suite-proxy-routing-proxy-ips)
- [ruleSets](#services-proxy-suite-proxy-routing-proxy-rulesets)
- [ruleSetUpdateInterval](#services-proxy-suite-proxy-routing-rulesetupdateinterval)
- [ruleSets](#services-proxy-suite-proxy-routing-rulesets)
- `<name>`
- [detour](#services-proxy-suite-proxy-routing-rulesets-name-detour)
- [format](#services-proxy-suite-proxy-routing-rulesets-name-format)
- [url](#services-proxy-suite-proxy-routing-rulesets-name-url)
- [rules](#services-proxy-suite-proxy-routing-rules)
- item
- [domains](#services-proxy-suite-proxy-routing-rules-domains)
@@ -81,6 +91,7 @@ Part of the [proxy-suite options reference](./index.md).
- [geosites](#services-proxy-suite-proxy-routing-rules-geosites)
- [ips](#services-proxy-suite-proxy-routing-rules-ips)
- [outbound](#services-proxy-suite-proxy-routing-rules-outbound)
- [ruleSets](#services-proxy-suite-proxy-routing-rules-rulesets)
- [selection](#services-proxy-suite-proxy-selection)
- [selectionExclude](#services-proxy-suite-proxy-selectionexclude)
- singBox
@@ -96,6 +107,7 @@ Part of the [proxy-suite options reference](./index.md).
- tproxy
- [enable](#services-proxy-suite-proxy-tproxy-enable)
- [fwmark](#services-proxy-suite-proxy-tproxy-fwmark)
- [lanInterfaces](#services-proxy-suite-proxy-tproxy-laninterfaces)
- [localSubnets](#services-proxy-suite-proxy-tproxy-localsubnets)
- [port](#services-proxy-suite-proxy-tproxy-port)
- [proxyMark](#services-proxy-suite-proxy-tproxy-proxymark)
@@ -859,6 +871,28 @@ list of string
]
```
<a id="services-proxy-suite-proxy-outbounds-routing-rulesets"></a>
## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.ruleSets
Names from proxy\.routing\.ruleSets to match (sing-box and hybrid backends)\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"antifilter"
]
```
<a id="services-proxy-suite-proxy-outbounds-singboxjson"></a>
## services\.proxy-suite\.proxy\.outbounds\.\*\.singBoxJson
@@ -1050,6 +1084,28 @@ list of string
]
```
<a id="services-proxy-suite-proxy-routing-block-rulesets"></a>
## services\.proxy-suite\.proxy\.routing\.block\.ruleSets
Names from ruleSets blocked\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"ads"
]
```
<a id="services-proxy-suite-proxy-routing-default"></a>
## services\.proxy-suite\.proxy\.routing\.default
@@ -1158,6 +1214,28 @@ list of string
]
```
<a id="services-proxy-suite-proxy-routing-direct-rulesets"></a>
## services\.proxy-suite\.proxy\.routing\.direct\.ruleSets
Names from ruleSets sent direct\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"ru-services"
]
```
<a id="services-proxy-suite-proxy-routing-directru"></a>
## services\.proxy-suite\.proxy\.routing\.directRu
@@ -1260,6 +1338,117 @@ list of string
]
```
<a id="services-proxy-suite-proxy-routing-proxy-rulesets"></a>
## services\.proxy-suite\.proxy\.routing\.proxy\.ruleSets
Names from ruleSets sent through the proxy\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"antifilter"
]
```
<a id="services-proxy-suite-proxy-routing-rulesetupdateinterval"></a>
## services\.proxy-suite\.proxy\.routing\.ruleSetUpdateInterval
How often ruleSets are downloaded again (systemd time span)\.
*Type:*
string
*Default:*
```nix
"1d"
```
*Example:*
```nix
"6h"
```
<a id="services-proxy-suite-proxy-routing-rulesets"></a>
## services\.proxy-suite\.proxy\.routing\.ruleSets
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”\.
*Type:*
attribute set of (submodule)
*Default:*
```nix
{ }
```
*Example:*
```nix
{
antifilter = {
url = "https://example.com/antifilter.srs";
};
}
```
<a id="services-proxy-suite-proxy-routing-rulesets-name-detour"></a>
## services\.proxy-suite\.proxy\.routing\.ruleSets\.\<name>\.detour
Downloaded through the local proxy, or directly\.
*Type:*
one of “proxy”, “direct”
*Default:*
```nix
"proxy"
```
<a id="services-proxy-suite-proxy-routing-rulesets-name-format"></a>
## services\.proxy-suite\.proxy\.routing\.ruleSets\.\<name>\.format
“binary” (\.srs) or “source” (JSON)\. Null goes by the URL: \.srs is binary\.
*Type:*
null or one of “binary”, “source”
*Default:*
```nix
null
```
<a id="services-proxy-suite-proxy-routing-rulesets-name-url"></a>
## services\.proxy-suite\.proxy\.routing\.ruleSets\.\<name>\.url
Where the sing-box rule set is downloaded from\.
*Type:*
string matching the pattern https?://\.+
*Example:*
```nix
"https://example.com/antifilter.srs"
```
<a id="services-proxy-suite-proxy-routing-rules"></a>
## services\.proxy-suite\.proxy\.routing\.rules
@@ -1395,6 +1584,28 @@ string
"vps-de"
```
<a id="services-proxy-suite-proxy-routing-rules-rulesets"></a>
## services\.proxy-suite\.proxy\.routing\.rules\.\*\.ruleSets
Names from proxy\.routing\.ruleSets to match (sing-box and hybrid backends)\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"antifilter"
]
```
<a id="services-proxy-suite-proxy-selection"></a>
## services\.proxy-suite\.proxy\.selection
@@ -1638,6 +1849,30 @@ signed integer
1
```
<a id="services-proxy-suite-proxy-tproxy-laninterfaces"></a>
## services\.proxy-suite\.proxy\.tproxy\.lanInterfaces
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\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"br0"
]
```
<a id="services-proxy-suite-proxy-tproxy-localsubnets"></a>
## services\.proxy-suite\.proxy\.tproxy\.localSubnets
+2 -1
View File
@@ -718,7 +718,8 @@ attribute set of string
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\.
+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 = {
+342
View File
@@ -0,0 +1,342 @@
{
pkgs,
checkLib,
}:
let
inherit (checkLib)
ok
mkRouting
evalProxySuite
mkRoutingRules
mkRouteModeRules
mkTProxyConfig
mkTunConfig
mkPerAppTunConfig
mkInboundsConfig
mkInboundsSpec
mkTProxyNftRules
mkNftRules
mkPerAppZapretNftRules
mkPerAppUserRules
hasDirectDomain
hasDirectIP
hasRuleSet
dnsHasRuleSet
dnsServerByTag
mkZapretBaseFor
mkZapretBase
packagePathMatches
shellValueByPrefix
baseModule
mkBadFixture
mkBadFixtureRaw
mkBadProxySuiteFixture
mkFailingAssertions
rejects
rejectsProxySuite
mkProxyCtlDerived
;
minimal = evalProxySuite [ baseModule ];
checkConstants =
(import ../../modules/proxy-suite/derived.nix {
lib = pkgs.lib;
cfg = minimal.config.services.proxy-suite;
}).constants;
_minimalProxyCtl = mkProxyCtlDerived minimal;
minimalProxyCtlWrapper = _minimalProxyCtl.wrapper;
minimalProxyCtlScript = _minimalProxyCtl.script;
minimalSocksService = minimal.config.systemd.services."proxy-suite-socks";
coreProxyChecks = import ./core-proxy.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
minimal
mkRoutingRules
mkTProxyConfig
hasRuleSet
dnsHasRuleSet
dnsServerByTag
;
};
inherit (coreProxyChecks) ruDefaultConfig;
routeModeChecks = import ./route-mode.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
mkRouteModeRules
shellValueByPrefix
minimalProxyCtlWrapper
minimalProxyCtlScript
;
};
subscriptionChecks = import ./subscriptions.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
mkBadFixtureRaw
mkFailingAssertions
mkProxyCtlDerived
minimal
;
};
guiChecks = import ./gui.nix {
inherit
evalProxySuite
baseModule
packagePathMatches
;
};
localProxyAuthChecks = import ./local-proxy-auth.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
mkProxyCtlDerived
shellValueByPrefix
mkBadFixture
mkFailingAssertions
ruDefaultConfig
;
};
sshProxyChecks = import ./ssh-proxy.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
mkBadProxySuiteFixture
mkFailingAssertions
mkRoutingRules
;
};
warpChecks = import ./warp.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
mkBadProxySuiteFixture
mkFailingAssertions
;
};
torChecks = import ./tor.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
mkBadProxySuiteFixture
mkFailingAssertions
mkRouting
mkTunConfig
mkTProxyConfig
mkInboundsSpec
mkInboundsConfig
mkProxyCtlDerived
;
};
proxyInboundsChecks = import ./proxy-inbounds.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
mkInboundsConfig
mkInboundsSpec
;
};
perAppRoutingChecks = import ./per-app-routing.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
mkProxyCtlDerived
mkPerAppUserRules
mkPerAppZapretNftRules
mkPerAppTunConfig
dnsServerByTag
mkZapretBase
mkZapretBaseFor
mkBadFixture
mkFailingAssertions
rejects
minimalProxyCtlScript
;
};
outboundValidationChecks = import ./outbound-validation.nix {
inherit mkBadProxySuiteFixture mkFailingAssertions;
};
chainingDnsChecks = import ./chaining-dns.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
mkTunConfig
mkTProxyConfig
mkBadProxySuiteFixture
mkFailingAssertions
;
};
amneziaWgChecks = import ./amnezia-wg.nix {
inherit checkLib;
inherit
rejectsProxySuite
pkgs
evalProxySuite
mkBadProxySuiteFixture
mkFailingAssertions
mkProxyCtlDerived
;
};
amneziaWgOutboundChecks = import ./amnezia-wg-outbound.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
mkBadProxySuiteFixture
mkFailingAssertions
mkProxyCtlDerived
mkTProxyConfig
dnsServerByTag
;
};
globalProxyModeChecks = import ./global-proxy-modes.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
mkBadFixture
mkFailingAssertions
mkTunConfig
mkTProxyConfig
mkTProxyNftRules
mkNftRules
dnsServerByTag
checkConstants
;
};
zapretChecks = import ./zapret.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
mkRoutingRules
mkZapretBase
mkBadFixture
mkFailingAssertions
hasDirectDomain
hasDirectIP
;
};
zapret2Checks = import ./zapret2.nix {
inherit
pkgs
evalProxySuite
baseModule
mkProxyCtlDerived
mkBadFixture
mkFailingAssertions
;
};
tgWsProxyChecks = import ./tg-ws-proxy.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
baseModule
mkRoutingRules
mkTProxyNftRules
mkBadFixture
mkFailingAssertions
hasDirectIP
minimal
minimalSocksService
;
zapretSyncService = zapretChecks.syncService;
};
serverModuleChecks = import ./server-module.nix {
inherit checkLib pkgs mkInboundsSpec;
inherit (checkLib) system nixpkgs proxySuiteModule;
};
xrayBackendChecks = import ./xray-backends.nix {
inherit checkLib;
inherit
pkgs
evalProxySuite
mkTProxyConfig
mkTunConfig
mkPerAppTunConfig
shellValueByPrefix
mkBadProxySuiteFixture
mkFailingAssertions
dnsServerByTag
checkConstants
;
};
validated = builtins.all (x: x) (
[
(ok (minimal.config.services.proxy-suite.proxy.listener.address == "127.0.0.1"))
]
++ coreProxyChecks.assertions
++ localProxyAuthChecks.assertions
++ sshProxyChecks.assertions
++ warpChecks.assertions
++ torChecks.assertions
++ proxyInboundsChecks.assertions
++ tgWsProxyChecks.assertions
++ xrayBackendChecks.assertions
++ outboundValidationChecks.assertions
++ chainingDnsChecks.assertions
++ amneziaWgChecks.assertions
++ amneziaWgOutboundChecks.assertions
++ zapretChecks.assertions
++ zapret2Checks.assertions
++ globalProxyModeChecks.assertions
++ guiChecks.assertions
++ subscriptionChecks.assertions
++ routeModeChecks.assertions
++ perAppRoutingChecks.assertions
++ serverModuleChecks.assertions
);
in
{
_groups = { inherit coreProxyChecks localProxyAuthChecks sshProxyChecks warpChecks torChecks proxyInboundsChecks tgWsProxyChecks xrayBackendChecks outboundValidationChecks chainingDnsChecks amneziaWgChecks amneziaWgOutboundChecks zapretChecks zapret2Checks globalProxyModeChecks guiChecks subscriptionChecks routeModeChecks perAppRoutingChecks serverModuleChecks ; minimalOk = { assertions = [ (ok (minimal.config.services.proxy-suite.proxy.listener.address == "127.0.0.1")) ]; }; };
proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok");
amneziawg-secret-manifest = amneziaWgChecks.manifest;
xray-jq-filter-runtime = xrayBackendChecks.runtime;
tor-guard-runtime = torChecks.runtime;
per-app-zapret-runtime = perAppRoutingChecks.runtime;
zapret-hostlist-rules = zapretChecks.rules;
zapret2-config = zapret2Checks.runtime;
proxy-suite-gui-build = _minimalProxyCtl.proxyCtl.gui;
}
+89
View File
@@ -8,6 +8,7 @@
mkTunConfig,
mkTProxyConfig,
mkTProxyNftRules,
mkNftRules,
dnsServerByTag,
checkConstants,
}:
@@ -23,6 +24,7 @@ let
mkTunConfig
mkTProxyConfig
mkTProxyNftRules
mkNftRules
;
};
@@ -34,6 +36,14 @@ let
tproxyManualStopScript
tproxyManualConfig
tproxyManualNftRules
tproxyLanFixture
tproxyLanNftRules
tproxyLanStartScript
killSwitchFixture
killSwitchNftRules
awgKillSwitchFixture
awgKillSwitchNftRules
awgKillSwitchPrepare
tproxyIPv4OnlyStartScript
tproxyIPv4OnlyConfig
tproxyIPv4OnlyNftRules
@@ -70,6 +80,85 @@ in
assert pkgs.lib.hasInfix "set +e" tproxyManualStopScript;
true
)
# Gateway clients: diverted past the LAN destinations, let through the host firewall by
# mark only, with forwarding for the rest.
(
let
cfg = tproxyLanFixture.config;
rules = tproxyLanNftRules;
at =
needle:
pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix needle) null (pkgs.lib.splitString "\n" rules);
in
assert pkgs.lib.hasInfix
''iifname { "br0" } meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:1085 meta mark set 1''
rules;
assert pkgs.lib.hasInfix ''iifname { "br0" } meta l4proto { tcp, udp } tproxy ip6'' rules;
assert at "ip daddr 192.168.0.0/16 tcp dport != 53 return" < at ''iifname { "br0" }'';
assert at ''iifname { "br0" }'' < at "ip saddr $RESERVED_IP return";
assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 accept''
cfg.networking.firewall.extraInputRules;
assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 accept''
cfg.networking.firewall.extraReversePathFilterRules;
assert !builtins.elem "br0" cfg.networking.firewall.trustedInterfaces;
assert cfg.boot.kernel.sysctl."net.ipv4.ip_forward" == 1;
assert pkgs.lib.hasInfix "sysctl -q -w net.ipv4.ip_forward=1" tproxyLanStartScript;
assert !(pkgs.lib.hasInfix "iifname {" tproxyManualNftRules);
assert !(pkgs.lib.hasInfix "sysctl" tproxyManualStartScript);
true
)
# The kill switch: pulled in by both modes, but not stopped with them; it lets the proxy's
# own traffic and its DNS hand-off past, and cuts gateway clients off from the internet.
(
let
units = killSwitchFixture.config.systemd.services;
ks = units."proxy-suite-killswitch";
rules = killSwitchNftRules;
before =
a: b:
pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix a) null (pkgs.lib.splitString "\n" rules)
< pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix b) null (pkgs.lib.splitString "\n" rules);
in
assert builtins.elem "proxy-suite-killswitch.service" units."proxy-suite-tun".wants;
assert builtins.elem "proxy-suite-killswitch.service" units."proxy-suite-tproxy".wants;
assert !(units."proxy-suite-tun" ? bindsTo) || units."proxy-suite-tun".bindsTo == [ ];
assert !(ks ? partOf) || ks.partOf == [ ];
assert builtins.elem "proxy-suite-tun.service" ks.after;
assert ks.wantedBy == [ ];
assert pkgs.lib.hasInfix ''meta skuid "proxy-suite-daemon" accept'' rules;
assert pkgs.lib.hasInfix "meta mark { 1, 2 } accept" rules;
assert pkgs.lib.hasInfix ''oifname "singtun0" accept'' rules;
assert before "ip daddr 172.19.0.1/30 accept" "th dport 53 reject";
assert before "th dport 53 reject" "ip daddr $RESERVED_IP accept";
assert pkgs.lib.hasInfix ''iifname { "br0" } reject'' rules;
assert !(tproxyManualFixture.config.systemd.services ? "proxy-suite-killswitch");
true
)
# A global AmneziaWG profile under the kill switch: a mark the rules know, its interface,
# and a group for awg-quick's own lookups. Stopping the profile no longer lifts it.
(
let
cfg = awgKillSwitchFixture.config;
units = cfg.systemd.services;
home = units.proxy-suite-awg-home;
rules = awgKillSwitchNftRules;
in
assert builtins.elem "proxy-suite-killswitch.service" home.wants;
assert builtins.elem "proxy-suite-awg-home.service" units.proxy-suite-killswitch.after;
assert !builtins.elem "proxy-suite-killswitch.service" (home.conflicts or [ ]);
assert (units.proxy-suite-killswitch.conflicts or [ ]) == [ ];
assert home.serviceConfig.Group == "proxy-suite-awg";
assert cfg.users.groups ? proxy-suite-awg;
assert pkgs.lib.hasInfix "--fwmark 51820" awgKillSwitchPrepare;
assert pkgs.lib.hasInfix ''meta skgid "proxy-suite-awg" accept'' rules;
assert pkgs.lib.hasInfix
''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}" } accept''
rules;
assert pkgs.lib.hasInfix "meta mark { 1, 2, 51820 } accept" rules;
assert !(pkgs.lib.hasInfix "skgid" killSwitchNftRules);
assert !(units.proxy-suite-awg-home-watchdog.serviceConfig ? Group);
true
)
# IPv6 goes through the same port on ::1; without it IPv6 is left alone.
(
let
@@ -6,6 +6,7 @@
mkTunConfig,
mkTProxyConfig,
mkTProxyNftRules,
mkNftRules,
}:
let
@@ -45,6 +46,55 @@ let
tproxyManualConfig = mkTProxyConfig tproxyManualFixture;
tproxyManualNftRules = mkTProxyNftRules tproxyManualFixture;
tproxyLanFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.tproxy = {
enable = true;
lanInterfaces = [ "br0" ];
};
}
];
tproxyLanNftRules = mkTProxyNftRules tproxyLanFixture;
tproxyLanStartScript =
generated.readDerivation
tproxyLanFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig.ExecStart;
killSwitchFixture = evalProxySuite [
baseModule
{
services.proxy-suite.killSwitch.enable = true;
services.proxy-suite.proxy = {
tun.enable = true;
tproxy = {
enable = true;
lanInterfaces = [ "br0" ];
};
};
}
];
killSwitchNftRules = mkNftRules killSwitchFixture "killSwitchRulesFile";
# A global AmneziaWG profile alone, no proxy.
awgKillSwitchFixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
killSwitch.enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = null;
profiles.home.configFile = "/run/secrets/awg.conf";
};
};
}
];
awgKillSwitchNftRules = mkNftRules awgKillSwitchFixture "killSwitchRulesFile";
awgKillSwitchPrepare = generated.readDerivation (
builtins.head awgKillSwitchFixture.config.systemd.services.proxy-suite-awg-home.serviceConfig.ExecStartPre
);
tproxyIPv4OnlyFixture = evalProxySuite [
baseModule
{
@@ -135,6 +185,9 @@ let
};
}
]
# The kill switch guards a global mode, and a gateway needs TProxy.
[ { services.proxy-suite.killSwitch.enable = true; } ]
[ { services.proxy-suite.proxy.tproxy.lanInterfaces = [ "br0" ]; } ]
];
tunDefaultConfig = mkTunConfig tunManualFixture;
@@ -150,6 +203,14 @@ in
tproxyManualStopScript
tproxyManualConfig
tproxyManualNftRules
tproxyLanFixture
tproxyLanNftRules
tproxyLanStartScript
killSwitchFixture
killSwitchNftRules
awgKillSwitchFixture
awgKillSwitchNftRules
awgKillSwitchPrepare
tproxyIPv4OnlyStartScript
tproxyIPv4OnlyConfig
tproxyIPv4OnlyNftRules
+1
View File
@@ -245,6 +245,7 @@ in
mkInboundsConfig
mkInboundsSpec
mkTProxyNftRules
mkNftRules
mkPerAppZapretNftRules
mkPerAppUserRules
ok
+2
View File
@@ -16,6 +16,7 @@ let
mkInboundsConfig
mkInboundsSpec
mkTProxyNftRules
mkNftRules
mkPerAppZapretNftRules
mkPerAppUserRules
hasDirectDomain
@@ -232,6 +233,7 @@ let
mkTunConfig
mkTProxyConfig
mkTProxyNftRules
mkNftRules
dnsServerByTag
checkConstants
;
+1 -1
View File
@@ -125,7 +125,7 @@ pkgs.testers.runNixOSTest {
with subtest("safety rules are present and ordered first"):
cfg = "/run/proxy-suite-inbounds/config.json"
server.succeed(f"test $(jq -r '.routing.rules[0].ruleTag' {cfg}) = inbound-block-private")
server.succeed(f"test $(jq -r '.routing.rules[1].ruleTag' {cfg}) = inbound-block-private")
server.succeed(f"jq -e '.routing.rules[] | select(.ruleTag == \"inbound-block-ru-domain\")' {cfg}")
server.succeed(f"test $(jq -r '.routing.rules[-1].outboundTag' {cfg}) = direct")
+55 -5
View File
@@ -171,6 +171,17 @@ let
alpn = [ "h3" ];
};
};
# hysteria2 is QUIC: UDP only.
listeners.hy2-in = {
type = "hysteria2";
port = 8444;
users = [ { passwordFile = "/run/secrets/hy2"; } ];
tls = {
certificateFile = "/run/acme/fullchain.pem";
keyFile = "/run/acme/key.pem";
};
hysteria.masquerade = "https://www.example.com";
};
};
firewallSpec = mkInboundsSpec firewallFixture;
wsListener = lib.head (builtins.filter (l: l.tag == "ws-in") firewallSpec.listeners);
@@ -314,7 +325,7 @@ let
failing = [
(mkRejectsListener (
realityListener // { port = 18536; }
realityListener // { port = 18533; }
) "collides with a port proxy-suite uses internally")
# Every user is checked, not only the first.
(mkRejectsListener (
@@ -434,6 +445,39 @@ let
}
) "flow is only valid on a vless listener")
(mkRejects (
baseProxy
// {
inbounds = {
enable = true;
listeners.hy2-in = {
type = "hysteria2";
port = 8444;
users = [ { passwordFile = "/run/secrets/hy2"; } ];
transport.type = "ws";
tls = {
certificateFile = "/c";
keyFile = "/k";
};
};
};
}
) "hysteria2 takes no reality or transport")
(mkRejects (
baseProxy
// {
inbounds = {
enable = true;
listeners.hy2-in = {
type = "hysteria2";
port = 8444;
users = [ { passwordFile = "/run/secrets/hy2"; } ];
};
};
}
) "needs both tls.certificateFile and tls.keyFile")
(mkRejects (
baseProxy
// {
@@ -516,8 +560,8 @@ let
];
assertions = [
# Listeners are rendered at start time.
(ok (relayConfig.inbounds == [ ]))
# Listeners are rendered at start time; only the stats API's is fixed.
(ok (map (ib: ib.tag) relayConfig.inbounds == [ "api-in" ]))
# AsIs when relayed through sing-box; IPOnDemand when XRay dials (see the template).
(ok (relayConfig.routing.domainStrategy == "AsIs"))
@@ -547,7 +591,7 @@ let
(ok ((ruleByTag exitConfig "inbound-final").outboundTag == "direct"))
# Safety rules come first.
(ok (builtins.head (ruleTags relayConfig) == "inbound-block-private"))
(ok (lib.take 2 (ruleTags relayConfig) == [ "inbound-stats-api" "inbound-block-private" ]))
(ok ((ruleByTag relayConfig "inbound-block-private").outboundTag == "block"))
(ok ((ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ]))
(ok ((ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ]))
@@ -555,7 +599,8 @@ let
# serverAddress is exempt after blockPrivate, before the country blocks.
(
assert
lib.take 3 (ruleTags namedConfig) == [
lib.take 4 (ruleTags namedConfig) == [
"inbound-stats-api"
"inbound-block-private"
"inbound-server-address-direct"
"inbound-block-ru-domain"
@@ -642,10 +687,15 @@ let
lib.sort lib.lessThan firewallFixture.config.networking.firewall.allowedUDPPorts == [
8388
8443
8444
];
true
)
(ok (wsListener.port == 10002 && wsListener.sharePort == 443))
(ok (
(lib.head (builtins.filter (l: l.tag == "hy2-in") firewallSpec.listeners)).hysteria.masquerade
== "https://www.example.com"
))
(ok (noFirewallFixture.config.networking.firewall.allowedTCPPorts == [ ]))
# The unit exists, and only waits on the client stack when it relays.
+2 -1
View File
@@ -146,7 +146,8 @@ let
};
exitNode = mkFixture "sing-box" exitInbounds;
exitNodeConfig = mkInboundsConfig exitNode;
exitNodeRules = exitNodeConfig.routing.rules;
# Past the stats API's own rule, which matches only its inbound.
exitNodeRules = builtins.tail exitNodeConfig.routing.rules;
exitNodeNoOnion = mkInboundsConfig (
mkFixture "sing-box" (exitInbounds // { tor.routeOnion = false; })
);
+36 -5
View File
@@ -43,6 +43,7 @@ let
tunedRuntime = runtimeDir zapret2Tuned globalService;
noAutoRuntime = runtimeDir zapret2NoAuto globalService;
z2kRuntime = runtimeDir zapret2Z2k globalService;
daemonStart = zapret2Global.config.systemd.services.${globalService}.serviceConfig.ExecStart;
cutoffProbe =
zapret2Global.config.systemd.services.proxy-suite-zapret2-cutoff.serviceConfig.ExecStart;
socksStart = fixture: fixture.config.systemd.services.proxy-suite-socks.serviceConfig.ExecStart;
@@ -81,14 +82,32 @@ in
true
)
# The cutoff probe comes with zapret2, on a timer, and nfqws2 reads its maps.
# nfqws2 is the unit's supervised main process: if it dies, systemd sees it and
# restarts it, instead of a oneshot staying active while the queue bypasses it.
(
let
sc = zapret2PerApp.config.systemd.services.${perAppService}.serviceConfig;
gc = zapret2Global.config.systemd.services.${globalService}.serviceConfig;
in
assert gc.Type == "notify" && sc.Type == "notify";
assert gc.Restart == "on-failure" && sc.Restart == "on-failure";
assert lib.hasSuffix "stop_fw" gc.ExecStopPost;
assert builtins.length sc.ExecStopPost == 2;
true
)
# The cutoff probe comes with zapret2, on a timer; z2k's nfqws2 reads its maps.
(
assert zapret2Global.config.systemd.timers ? proxy-suite-zapret2-cutoff;
assert !(zapretDiscordYoutubeGlobal.config.systemd.services ? proxy-suite-zapret2-cutoff);
assert (proxyCtlEnv zapret2Global).ZAPRET_CUTOFF_ENABLED == "1";
assert
envValue zapret2Global globalService "Z2K_TCP16_ASN="
envValue zapret2Z2k globalService "Z2K_TCP16_ASN="
== "/var/lib/proxy-suite/zapret2/cutoff/asn.txt";
assert
!(builtins.any (lib.hasPrefix "Z2K_TCP16_ASN=")
zapret2Global.config.systemd.services.${globalService}.serviceConfig.Environment
);
true
)
@@ -175,11 +194,16 @@ in
test "$(grep -oF -- '<HOSTLIST>' "${z2kRuntime}/config" | wc -l)" = 1
grep -qF -- '/lists/whitelist.txt --hostlist-exclude=/var/lib/proxy-suite/zapret2/zapret-hosts-user-exclude.txt' "${z2kRuntime}/config"
# z2k's Lua in its own order: ranges (repeats=6-10) resolve before its strategies fire.
grep -qE -- 'z2k-fooling-ext\.lua --lua-init=@[^ ]+/z2k-range-rand\.lua --lua-init=@[^ ]+/z2k-modern-core\.lua' "${z2kRuntime}/config"
# --- 16 KB cutoff ---------------------------------------------------
# The whitelisted-name step runs ahead of rotation, in both sources.
grep -qF -- '/files/lua/z2k-tcp16.lua' "${globalRuntime}/config"
grep -qF -- 'blob=z2k_ch:optional:repeats=8:tcp_ts=-1000 --lua-desync=circular:fails=2:time=300' "${globalRuntime}/config"
# The whitelisted-name step runs ahead of rotation, in z2k only: ahead of the
# nfqws2-keenetic strategies it broke hosts they reach on their own.
grep -qF -- '/files/lua/z2k-tcp16.lua' "${z2kRuntime}/config"
grep -qF -- 'blob=z2k_ch:optional:repeats=8:tcp_ts=-1000 --lua-desync=circular:fails=3:time=60:key=rkn_tcp' "${z2kRuntime}/config"
if grep -qF -- 'z2k_sni_pick' "${globalRuntime}/config"; then exit 1; fi
if grep -qF -- 'z2k-tcp16.lua' "${globalRuntime}/config"; then exit 1; fi
# zapret2 leaves the probe's own connections alone, in every chain.
test "$(grep -c 'ct mark and 0x2000000 != 0 return' "${globalRuntime}/init.d/sysv/custom.d/50-proxy-suite-custom.sh")" = 4
@@ -253,6 +277,13 @@ in
grep -qx -- '--hostlist-auto-fail-threshold=3' global.args
grep -qx -- '--hostlist-auto-fail-time=300' global.args
# The supervised launcher execs nfqws2 with the command line the init script builds.
printf '#!/bin/sh\nprintf "%%s\\n" "$@"\n' >fake-nfqws2
chmod +x fake-nfqws2
ZAPRET_RW=${globalRuntime} NFQWS2="$PWD/fake-nfqws2" ${daemonStart} >daemon.args
head -n1 daemon.args | grep -qx -- '--user=root'
tail -n +6 daemon.args | diff - global.args
dry_run ${z2kRuntime} z2k.args
test "$(grep -cx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" z2k.args)" = 1
+82 -17
View File
@@ -25,6 +25,7 @@ ALL_SERVICES = [
"proxy-suite-socks",
"proxy-suite-tproxy",
"proxy-suite-tun",
"proxy-suite-killswitch",
"proxy-suite-inbounds",
"proxy-suite-ssh-proxy",
"proxy-suite-warp",
@@ -80,6 +81,7 @@ Secrets and changes need root, or the userControl group.
proxy subs add [tag] <url> add a subscription at runtime; no tag: named after its host
proxy subs rm <tag> remove a runtime subscription
proxy subs link <tag> [--qr] its URL
proxy rulesets [list|update] routing rule sets: when each was fetched; update fetches them now
proxy config [--raw] client config to import elsewhere; --raw: as running
proxy tun [status|on|off] global TUN mode
proxy tproxy [status|on|off] global TProxy mode
@@ -104,6 +106,9 @@ Secrets and changes need root, or the userControl group.
awg [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile]
killswitch [status|on|off] reject traffic outside the global tunnel; up with
TUN, TProxy or AWG, lifted only by off here or on them
ssh [status|on|off] SSH SOCKS5 tunnel
warp [status|on|off] WARP tunnel behind the warp outbound
tor [status|on|off] Tor, behind the tor outbound and the onion service
@@ -464,6 +469,7 @@ COMPLETE = {
"proxy": "local proxy backend",
"zapret": "DPI bypass",
"awg": "AmneziaWG profiles",
"killswitch": "reject traffic outside the global tunnel",
"ssh": "SSH SOCKS5 tunnel",
"warp": "WARP tunnel behind the warp outbound",
"tor": "Tor, behind the tor outbound and the onion service",
@@ -484,6 +490,7 @@ COMPLETE = {
"unpin": "let the configured selection pick again",
"mode": "show or override the routing mode",
"subs": "subscription caches",
"rulesets": "routing rule sets",
"tun": "global TUN mode",
"tproxy": "global TProxy mode",
"auto": "what autoProxy routed",
@@ -533,6 +540,7 @@ COMPLETE = {
"link": "its URL",
}
},
"proxy rulesets": {"words": {"list": "when each rule set was fetched", "update": "fetch the rule sets now"}},
"proxy subs link": {"args": lambda: _names(_sub_tags() + _runtime_tags("subscription")), "flags": {"--qr": "print a QR code"}},
"proxy subs rm": {"args": lambda: _names(_runtime_tags("subscription"))},
"proxy tun": {"words": TOGGLE},
@@ -588,6 +596,7 @@ COMPLETE = {
"awg restart": {"args": lambda: _names(_awg_profiles())},
"ssh": {"words": TOGGLE},
"warp": {"words": TOGGLE},
"killswitch": {"words": TOGGLE},
"tor": {"words": {**TOGGLE, "newnym": "new circuits for new connections"}},
"tg": {"words": TOGGLE},
"apps": {"words": {"list": "per-app routing profiles", "run": "run a command through a profile"}},
@@ -692,9 +701,11 @@ SNAPSHOT_UNITS = {
"proxy": "proxy-suite-socks",
"tproxy": "proxy-suite-tproxy",
"tun": "proxy-suite-tun",
"killswitch": "proxy-suite-killswitch",
"zapret": "proxy-suite-zapret",
}
SUBSCRIPTION_UPDATE = "proxy-suite-subscription-update"
KILL_SWITCH = "proxy-suite-killswitch"
BUSY_STATES = ("activating", "deactivating", "reloading")
@@ -831,6 +842,8 @@ def _status_autoproxy():
if env("AUTOPROXY_ENABLED") != "1":
return ""
state = os.path.join(_autoproxy_dir(), "state.json")
if _autoproxy_unreadable(_autoproxy_dir()):
return "state not readable"
if not readable(state):
return ""
try:
@@ -906,7 +919,7 @@ def cmd_proxy(verb="status", *args):
elif verb == "off":
if not svc_exists("proxy-suite-socks"):
die("proxy is not enabled in this configuration.")
for svc in ("proxy-suite-tproxy", "proxy-suite-tun"):
for svc in ("proxy-suite-tproxy", "proxy-suite-tun", KILL_SWITCH):
if svc_exists(svc):
systemctl("stop", svc)
must("stop", "proxy-suite-socks")
@@ -922,16 +935,19 @@ def cmd_proxy(verb="status", *args):
cmd_route_mode(*args)
elif verb == "subs":
cmd_subscription(*args)
elif verb == "tun":
_toggle("proxy-suite-tun", "proxy tun", *args)
elif verb == "tproxy":
_toggle("proxy-suite-tproxy", "proxy tproxy", *args)
elif verb == "rulesets":
cmd_rulesets(*args)
elif verb in ("tun", "tproxy"):
_toggle(f"proxy-suite-{verb}", f"proxy {verb}", *args)
# A mode stopped on purpose lifts the kill switch; one that fails leaves it up.
if args[:1] == ("off",) and svc_exists(KILL_SWITCH):
systemctl("stop", KILL_SWITCH)
elif verb == "auto":
cmd_proxy_auto(*args)
elif verb in ("probe", "learn", "forget", "relearn", "queue", "learned"):
cmd_proxy_auto(verb, *args)
else:
usage("proxy [status|on|off|outbounds|pin|unpin|mode|subs|tun|tproxy|auto|config]")
usage("proxy [status|on|off|outbounds|pin|unpin|mode|subs|rulesets|tun|tproxy|auto|config]")
def cmd_outbounds(verb="list", *args):
@@ -1732,6 +1748,39 @@ def cmd_subscription(verb="list", *args):
usage("proxy subs [list|update|add [tag] <url>|rm <tag>|link <tag>]")
RULE_SETS_UNIT = "proxy-suite-rulesets"
def cmd_rulesets(verb="list", *_):
rule_sets = read_json_or(env("RULE_SETS_FILE"), [])
if verb == "update":
if not rule_sets or not svc_exists(RULE_SETS_UNIT):
die("No proxy.routing.ruleSets in this configuration.")
# A oneshot: this returns once every rule set was tried.
status, _ = systemctl("start", RULE_SETS_UNIT)
print("Rule sets updated." if status == 0 else f"Some rule sets were not updated: {journal_hint(RULE_SETS_UNIT, 20)}")
sys.exit(status)
elif verb == "list":
if not rule_sets:
print("No rule sets configured.")
return
print(f" {'NAME':<24} {'LAST UPDATED':<22} SIZE")
for rs in rule_sets:
try:
stat = os.stat(rs["path"])
except OSError:
print(f" {rs['name']:<24} {'(missing)':<22} -")
continue
updated = datetime.datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M:%S")
print(f" {rs['name']:<24} {updated:<22} {stat.st_size}")
next_run = _timer_next_run(f"{RULE_SETS_UNIT}.timer")
if next_run:
print()
print(f"Next update: {datetime.datetime.fromtimestamp(next_run):%H:%M:%S}, {_in_time(next_run)}")
else:
usage("proxy rulesets [list|update]")
# --- proxy auto: reachability probe -------------------------------------------
#
# Fetches a URL through one exit after another (direct first) and finds one
@@ -2648,7 +2697,9 @@ def cmd_where(domain="", *_):
config_path = _runtime_file("config.json")
geosite_dir = ""
if readable(config_path):
if os.path.exists(config_path) and not readable(config_path):
_where_row("sing-box", f"routing is not readable - {ask_group()}")
elif readable(config_path):
try:
config = read_json(config_path)
except (OSError, ValueError):
@@ -2683,7 +2734,7 @@ def cmd_where(domain="", *_):
_where_row("inbounds", f"{shown} - {why}")
if env("AUTOPROXY_ENABLED") == "1":
if not readable(os.path.join(_autoproxy_dir(), "state.json")):
if _autoproxy_unreadable(_autoproxy_dir()):
_where_row("autoProxy", f"state is not readable - {ask_group()}")
else:
domains = _autoproxy_state(_autoproxy_dir()).get("domains")
@@ -2750,12 +2801,13 @@ def cmd_awg(verb="list", *args):
must("start", _awg_service(args[0]))
elif verb in ("off", "restart"):
targets = list(args[:1]) or _active_awg_profiles()
if not targets:
if verb == "off":
return
if not targets and verb == "restart":
die("No AmneziaWG profile is active.")
for profile in targets:
must("stop" if verb == "off" else "restart", _awg_service(profile))
# Also after a profile that already failed: off is how its kill switch is lifted.
if verb == "off" and svc_exists(KILL_SWITCH):
systemctl("stop", KILL_SWITCH)
else:
usage("awg [list] | on <profile> | off [profile] | restart [profile]")
@@ -3028,9 +3080,20 @@ AWG_ONLINE_SECONDS = 180
def _inbound_presence():
"""user -> (state, addresses): "online", "seen <time>" or "never seen"; dies when the stats API is silent."""
"""(user -> (state, addresses), links readable): "online", "seen <time>" or "never seen".
Who is online and from where is as private as the traffic stats, so it takes the
same read access; dies without it, or when the stats API is silent.
"""
stats_path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
if os.path.exists(stats_path) and not readable(stats_path):
denied(stats_path)
api = env("INBOUNDS_API", f"unix://{runtime_dir()}/proxy-suite-inbounds/api/stats.sock")
sock = api.removeprefix("unix://")
if os.path.exists(sock) and not os.access(sock, os.W_OK):
denied(sock, "connect to")
status, out = _run(
[env("INBOUNDS_XRAY", "xray"), "api", "statsonlineiplist", f"--server={env('INBOUNDS_API', '127.0.0.1:18536')}", "-all"],
[env("INBOUNDS_XRAY", "xray"), "api", "statsonlineiplist", f"--server={api}", "-all"],
capture=True,
quiet=True,
)
@@ -3048,8 +3111,7 @@ def _inbound_presence():
# the XRay API already told who else is online now.
if any(x.get("type") == "amneziawg" for x in links):
systemctl("--no-ask-password", "start", "proxy-suite-inbound-stats.service", quiet=True)
path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
stats = read_json(path) if readable(path) else {}
stats = read_json(stats_path) if readable(stats_path) else {}
seen = stats.get("seen") or {}
now = time.time()
for user, peer in (stats.get("awgPeers") or {}).items():
@@ -3071,13 +3133,13 @@ def _inbound_presence():
presence[user] = (f"seen {when(seen[user])}", "")
else:
presence[user] = ("never seen", "")
return presence
return presence, not path or readable(path)
def _inbound_online():
"""Users connected right now with their addresses, then when the others were last seen."""
row = " {:<20} {:<24} {}"
presence = _inbound_presence()
presence, links_read = _inbound_presence()
print(row.format("USER", "STATE", "ADDRESSES"))
for user, (state, addresses) in presence.items():
print(row.format(user, state, addresses))
@@ -3088,6 +3150,8 @@ def _inbound_online():
"or everyone reads as never seen.",
file=sys.stderr,
)
if not links_read:
print(f"Users never seen are left out: the share links name them - {ask_group()}.", file=sys.stderr)
def _inbound_subscriptions(*args):
@@ -3191,6 +3255,7 @@ COMMANDS = {
"proxy": cmd_proxy,
"zapret": cmd_zapret,
"awg": cmd_awg,
"killswitch": lambda *args: _toggle(KILL_SWITCH, "killswitch", *args),
"ssh": lambda *args: _toggle("proxy-suite-ssh-proxy", "ssh", *args),
"warp": lambda *args: _toggle(_warp_unit(), "warp", *args),
"tor": cmd_tor,
+1
View File
@@ -130,6 +130,7 @@ TOGGLES = {
"proxy-suite-socks": ["proxy"],
"proxy-suite-tun": ["proxy", "tun"],
"proxy-suite-tproxy": ["proxy", "tproxy"],
"proxy-suite-killswitch": ["killswitch"],
"proxy-suite-ssh-proxy": ["ssh"],
"proxy-suite-warp-tunnel": ["warp"],
# WARP as an AmneziaWG outbound: `proxy-ctl warp`, not `awg`, which only knows global profiles.
+36
View File
@@ -332,6 +332,42 @@ class ServiceManagerTest(EnvTest):
self.assertEqual(seen, [["systemctl", "--user", "start", "anchor.service"], ["systemctl", "start", "proxy-suite-socks"]])
self.assertEqual(ctl.journal_hint("proxy-suite-autoproxy-learn", 20), "journalctl -u proxy-suite-autoproxy-learn -n 20")
def test_kill_switch_lifts_only_on_purpose(self):
seen = self.calls()
stops = lambda: [argv[2] for argv in seen if argv[1] == "stop"]
ctl.cmd_proxy("tun", "on")
self.assertEqual(stops(), [])
ctl.cmd_proxy("tun", "off")
self.assertEqual(stops(), ["proxy-suite-tun", ctl.KILL_SWITCH])
seen.clear()
ctl.cmd_proxy("off")
self.assertEqual(stops(), ["proxy-suite-tproxy", "proxy-suite-tun", ctl.KILL_SWITCH, "proxy-suite-socks"])
# A profile that already failed is not active, and its kill switch still lifts.
seen.clear()
self.patch("_active_awg_profiles", lambda: [])
ctl.cmd_awg("off")
self.assertEqual(stops(), [ctl.KILL_SWITCH])
seen.clear()
ctl.COMMANDS["killswitch"]("off")
self.assertEqual(stops(), [ctl.KILL_SWITCH])
def test_rulesets_list(self):
self.calls()
with tempfile.TemporaryDirectory() as tmp:
fetched = os.path.join(tmp, "antifilter.srs")
with open(fetched, "wb") as handle:
handle.write(b"SRS" + b"\0" * 29)
listing = os.path.join(tmp, "rulesets.json")
with open(listing, "w", encoding="utf-8") as handle:
json.dump([{"name": "antifilter", "path": fetched}, {"name": "gone", "path": os.path.join(tmp, "x.srs")}], handle)
os.environ["RULE_SETS_FILE"] = listing
out = io.StringIO()
with contextlib.redirect_stdout(out):
ctl.cmd_proxy("rulesets")
rows = out.getvalue().splitlines()
self.assertRegex(rows[1], r"^ antifilter +\d{4}-\d\d-\d\d \d\d:\d\d:\d\d +32$")
self.assertRegex(rows[2], r"^ gone +\(missing\) +-$")
def test_user_units(self):
# home-manager: every unit is the user's, and a --user of the caller's is not doubled.
os.environ["SERVICE_MANAGER"] = "systemd-user"
+39
View File
@@ -10,6 +10,7 @@ import ipaddress
import json
import os
import re
import socket
import tempfile
import zlib
from pathlib import Path
@@ -366,6 +367,29 @@ def as_outbound(config: str, fwmark: int) -> str:
return _set_interface_value(config, "FwMark", str(fwmark))
ENDPOINT_LINE = re.compile(r"^(\s*Endpoint\s*=\s*)(\S+):(\d+)\s*$", re.IGNORECASE | re.MULTILINE)
def resolve_endpoints(config: str) -> str:
"""Endpoint names looked up here, by this process, as awg would; one that does not resolve is left."""
def resolve(match: re.Match[str]) -> str:
prefix, host, port = match.groups()
try:
ipaddress.ip_address(host.strip("[]"))
return match.group(0)
except ValueError:
pass
try:
family, *_, address = socket.getaddrinfo(host, int(port), type=socket.SOCK_DGRAM, flags=socket.AI_ADDRCONFIG)[0]
except (OSError, UnicodeError):
return match.group(0)
ip = f"[{address[0]}]" if family == socket.AF_INET6 else address[0]
return f"{prefix}{ip}:{port}"
return ENDPOINT_LINE.sub(resolve, config)
# Read once by wireproxy: repeated lines are joined into one list.
WIREPROXY_LIST_KEYS = {"address", "dns", "allowedips"}
# wg-quick's, which wireproxy has no use for.
@@ -737,6 +761,17 @@ def main() -> int:
metavar="ADDRESS",
help="render for wireproxy, as a SOCKS5 listener on ADDRESS (packets marked with --outbound-fwmark)",
)
parser.add_argument(
"--fwmark",
type=int,
metavar="MARK",
help="render a global profile whose own packets carry MARK (awg-quick routes it with table MARK)",
)
parser.add_argument(
"--resolve-endpoints",
action="store_true",
help="write Endpoint names as the addresses they resolve to here",
)
parser.add_argument(
"--inspect",
metavar="CONFIG",
@@ -765,6 +800,10 @@ def main() -> int:
config = as_wireproxy(config, args.wireproxy, args.outbound_fwmark)
elif args.outbound_fwmark is not None:
config = as_outbound(config, args.outbound_fwmark)
elif args.fwmark is not None:
config = _set_interface_value(config, "FwMark", str(args.fwmark))
if args.resolve_endpoints:
config = resolve_endpoints(config)
write_private(args.output, config)
except (ConfigError, KeyError, OSError, json.JSONDecodeError) as exc:
parser.exit(1, f"amneziawg-config: {exc}\n")
+38 -13
View File
@@ -17,8 +17,7 @@ from awg_inbound import client_entries
from proxy_parsing import build_outbound
UUID_TYPES = ("vless", "vmess")
PASSWORD_TYPES = ("trojan", "shadowsocks", "socks", "http")
UDP_TYPES = ("shadowsocks", "socks")
PASSWORD_TYPES = ("trojan", "hysteria2", "shadowsocks", "socks", "http")
TRANSPORT_SETTINGS_KEY = {
"ws": "wsSettings",
@@ -78,6 +77,8 @@ def _clients(listener: dict, tag: str) -> list[dict]:
client = {"id": secret, "email": email}
if listener["type"] == "vless" and listener.get("flow"):
client["flow"] = listener["flow"]
elif listener["type"] == "hysteria2":
client = {"auth": secret, "email": email}
else:
client = {"password": secret, "email": email}
clients.append(client)
@@ -93,6 +94,19 @@ def _accounts(listener: dict, tag: str) -> list[dict]:
def _xray_stream(listener: dict, tag: str) -> dict:
if listener["type"] == "hysteria2":
# QUIC: the transport is hysteria's own, always under TLS.
settings = {"version": 2}
masquerade = (listener.get("hysteria") or {}).get("masquerade")
if masquerade:
settings["masquerade"] = {"type": "proxy", "url": masquerade, "rewriteHost": True}
return {
"network": "hysteria",
"hysteriaSettings": settings,
"security": "tls",
"tlsSettings": _tls_settings(listener["tls"], ["h3"]),
}
transport = listener["transport"]
network = transport["type"]
stream: dict = {"network": network}
@@ -131,22 +145,24 @@ def _xray_stream(listener: dict, tag: str) -> dict:
}
elif tls["enable"] or listener["type"] == "trojan":
stream["security"] = "tls"
certificate = {
"certificateFile": tls["certificateFile"],
"keyFile": tls["keyFile"],
}
stream["tlsSettings"] = {"certificates": [certificate]}
if tls.get("serverName"):
stream["tlsSettings"]["serverName"] = tls["serverName"]
# ["h3"] alone is what makes an xhttp listener serve HTTP/3, on UDP.
if tls.get("alpn"):
stream["tlsSettings"]["alpn"] = tls["alpn"]
stream["tlsSettings"] = _tls_settings(tls)
else:
stream["security"] = "none"
return stream
def _tls_settings(tls: dict, default_alpn: list[str] | None = None) -> dict:
settings: dict = {"certificates": [{"certificateFile": tls["certificateFile"], "keyFile": tls["keyFile"]}]}
if tls.get("serverName"):
settings["serverName"] = tls["serverName"]
# ["h3"] alone is what makes an xhttp listener serve HTTP/3, on UDP.
alpn = tls.get("alpn") or default_alpn
if alpn:
settings["alpn"] = alpn
return settings
def render_xray_inbound(listener: dict) -> dict:
"""Build one XRay inbound object from a typed listener spec."""
tag = listener["tag"]
@@ -158,6 +174,8 @@ def render_xray_inbound(listener: dict) -> dict:
settings["decryption"] = "none"
elif listener_type == "trojan":
settings = {"clients": _clients(listener, tag)}
elif listener_type == "hysteria2":
settings = {"version": 2, "clients": _clients(listener, tag)}
elif listener_type == "shadowsocks":
settings = {"method": listener["method"], "network": "tcp,udp"}
users = listener["users"]
@@ -179,7 +197,8 @@ def render_xray_inbound(listener: dict) -> dict:
"tag": tag,
"listen": listener["listen"],
"port": listener["port"],
"protocol": listener_type,
# XRay names hysteria2 "hysteria", and takes the version in its settings.
"protocol": "hysteria" if listener_type == "hysteria2" else listener_type,
"settings": settings,
"streamSettings": _xray_stream(listener, tag),
# routeOnly keeps the sniffed domain for routing decisions without
@@ -316,6 +335,12 @@ def build_share_link(
scheme = "https" if listener["tls"]["enable"] else "http"
return f"{scheme}://{credentials}@{endpoint}#{fragment}"
if listener_type == "hysteria2":
tls = listener["tls"]
params = {"sni": tls.get("serverName") or server_address, "alpn": ",".join(tls.get("alpn") or ["h3"])}
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
return f"hysteria2://{urllib.parse.quote(secret, safe='')}@{endpoint}?{query}#{fragment}"
params = _link_transport_params(listener)
params.update(_link_security_params(listener, server_address))
if listener_type == "vless" and listener.get("flow"):
+36
View File
@@ -458,6 +458,42 @@ class AmneziaWgConfigTests(unittest.TestCase):
# The peer is untouched.
self.assertIn("Endpoint = vpn.example.com:51820", rendered)
def test_resolve_endpoints(self):
# Under the kill switch awg-quick gets addresses; a name that does not resolve is left.
config = "[Peer]\nEndpoint = vpn.example:51820\n[Peer]\nEndpoint = 192.0.2.1:1\nendpoint = [2001:db8::1]:2\n[Peer]\nEndpoint = gone.invalid:3\n"
def lookup(host, *_args, **_kwargs):
if host == "vpn.example":
return [(amneziawg_config.socket.AF_INET6, None, None, "", ("2001:db8::7", 51820, 0, 0))]
raise amneziawg_config.socket.gaierror("no such name")
with patch.object(amneziawg_config.socket, "getaddrinfo", side_effect=lookup):
rendered = amneziawg_config.resolve_endpoints(config)
self.assertEqual(
rendered,
"[Peer]\nEndpoint = [2001:db8::7]:51820\n[Peer]\nEndpoint = 192.0.2.1:1\nendpoint = [2001:db8::1]:2\n[Peer]\nEndpoint = gone.invalid:3\n",
)
def test_global_render_pins_the_fwmark(self):
# The kill switch knows the tunnel's own packets by it; one set in the file is replaced.
with tempfile.TemporaryDirectory() as directory:
source = Path(directory) / "home.conf"
output = Path(directory) / "out" / "home.conf"
source.write_text(
BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1").replace(
"Address = 10.8.0.2/32", "Address = 10.8.0.2/32\nFwMark = 7"
)
)
result = subprocess.run(
[sys.executable, str(Path(__file__).with_name("amneziawg_config.py")),
"--config", str(source), "--output", str(output), "--fwmark", "51820"],
capture_output=True, text=True,
)
self.assertEqual(result.returncode, 0, result.stderr)
rendered = output.read_text()
self.assertEqual(amneziawg_config.section_values(rendered, "interface", "fwmark"), ["51820"])
self.assertIn("DNS = 1.1.1.1", rendered)
def test_wireproxy_render_joins_lists_and_adds_socks_listener(self):
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1").replace(
"Address = 10.8.0.2/32",
+29 -1
View File
@@ -214,7 +214,7 @@ class RenderInboundTests(unittest.TestCase):
def test_unsupported_type_fails(self):
with self.assertRaisesRegex(ValueError, "unsupported type"):
render_xray_inbound(listener(type="hysteria2"))
render_xray_inbound(listener(type="tuic"))
class ShareLinkTests(unittest.TestCase):
@@ -374,6 +374,34 @@ class RoundTripTests(unittest.TestCase):
self.assertEqual(ob["transport"]["path"], "/download")
self.assertEqual(ob["tls"]["server_name"], "cdn.example.com")
def test_hysteria2_round_trip(self):
spec = listener(
type="hysteria2",
port=8443,
users=[{"name": "phone", "password": "p@ss/word", "passwordFile": None}],
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": "hy.example.com"},
hysteria={"masquerade": "https://www.example.com"},
)
ib = render_xray_inbound(spec)
self.assertEqual(ib["protocol"], "hysteria")
self.assertEqual(ib["settings"], {"version": 2, "clients": [{"auth": "p@ss/word", "email": "phone"}]})
stream = ib["streamSettings"]
self.assertEqual(stream["network"], "hysteria")
self.assertEqual(stream["security"], "tls")
self.assertEqual(stream["tlsSettings"]["alpn"], ["h3"])
self.assertEqual(stream["hysteriaSettings"]["masquerade"]["url"], "https://www.example.com")
link = build_share_link(spec, "vpn.example.com")
self.assertTrue(link.startswith("hysteria2://p%40ss%2Fword@vpn.example.com:8443?"), link)
self.assertEqual(link_params(link)["alpn"], "h3")
ob = build_outbound(link, "round-trip", backend="sing-box")
self.assertEqual(ob["type"], "hysteria2")
self.assertEqual(ob["password"], "p@ss/word")
self.assertEqual(ob["server_port"], 8443)
self.assertEqual(ob["tls"]["server_name"], "hy.example.com")
# Without masquerade XRay answers non-clients with 404; nothing to render.
plain = render_xray_inbound(dict(spec, hysteria={"masquerade": None}))
self.assertEqual(plain["streamSettings"]["hysteriaSettings"], {"version": 2})
def test_trojan_round_trip(self):
link = build_share_link(
listener(