fix: zapret2 improvements

This commit is contained in:
FUFSoB committed 2026-10-04 17:07:45 +05:00
1 parent 65082aad88
commit 552bfd53b1
30 files changed
+872 -49

No files matched your search

+4
View File
@@ -405,14 +405,18 @@ services.proxy-suite = {
enable = true;
proxyFallback = true;
};
debug = false;
domains = [ ];
excludeDomains = [ ];
ipv6 = false;
ports = {
extraTcp = [ ];
extraUdp = [ ];
tcp = null;
udp = null;
};
profiles = null;
strategyLog = true;
strategySource = "nfqws2-keenetic";
};
};
+48 -3
View File
@@ -53,13 +53,17 @@ Part of the [proxy-suite options reference](./index.md).
- cutoff
- [enable](#services-proxy-suite-zapret-zapret2-cutoff-enable)
- [proxyFallback](#services-proxy-suite-zapret-zapret2-cutoff-proxyfallback)
- [debug](#services-proxy-suite-zapret-zapret2-debug)
- [domains](#services-proxy-suite-zapret-zapret2-domains)
- [excludeDomains](#services-proxy-suite-zapret-zapret2-excludedomains)
- [ipv6](#services-proxy-suite-zapret-zapret2-ipv6)
- ports
- [extraTcp](#services-proxy-suite-zapret-zapret2-ports-extratcp)
- [extraUdp](#services-proxy-suite-zapret-zapret2-ports-extraudp)
- [tcp](#services-proxy-suite-zapret-zapret2-ports-tcp)
- [udp](#services-proxy-suite-zapret-zapret2-ports-udp)
- [profiles](#services-proxy-suite-zapret-zapret2-profiles)
- [strategyLog](#services-proxy-suite-zapret-zapret2-strategylog)
- [strategySource](#services-proxy-suite-zapret-zapret2-strategysource)
<a id="services-proxy-suite-zapret-enable"></a>
@@ -90,7 +94,9 @@ Subnets zapret skips\.
<a id="services-proxy-suite-zapret-directsync-enable"></a>
## services\.proxy-suite\.zapret\.directSync\.enable
Send zapret’s domains direct in the proxy routing, so zapret handles them\.
Send zapret’s domains direct in the proxy routing, so zapret handles them\. With zapret2,
also the sites it pins and learns at runtime, after your own rules and autoProxy’s\.
The all-proxy and all-bypass route modes leave them out, like every direct list\.
**Type:** boolean\
**Default:** `true`
@@ -415,6 +421,14 @@ sees by IP (TUN, TProxy, per-app routing)\. Explicit direct rules still win\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-zapret-zapret2-debug"></a>
## services\.proxy-suite\.zapret\.zapret2\.debug
Log everything nfqws2 does to the journal, every packet included\. Very verbose: for troubleshooting\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-zapret-zapret2-domains"></a>
## services\.proxy-suite\.zapret\.zapret2\.domains
@@ -441,10 +455,32 @@ Handle IPv6 too\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-zapret-zapret2-ports-extratcp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.extraTcp
More TCP ports, handled like the profiles’ own: each profile that recognizes its traffic
(` --filter-l7 `, e\.g\. TLS) gets them too, so TLS to a blocked site on one of these ports
gets the same strategies\. A profile without ` --filter-l7 ` keeps its ports\.
**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]+(-\[0-9]+)?)\
**Default:** `[ ]`\
**Example:** `[ 8444 "9000-9010" ]`
<a id="services-proxy-suite-zapret-zapret2-ports-extraudp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.extraUdp
More UDP ports, handled like the profiles’ own: each profile that recognizes its traffic
(` --filter-l7 `, e\.g\. STUN, Discord, QUIC) gets them too, so a game’s or call app’s STUN
on these ports gets the same strategies as Discord’s\.
**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]+(-\[0-9]+)?)\
**Default:** `[ ]`\
**Example:** `[ "27015-27030" ]`
<a id="services-proxy-suite-zapret-zapret2-ports-tcp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.tcp
TCP ports zapret2 handles\. Must include every port a profile uses\. ` null `: use the ports from ` strategySource `\.
TCP ports zapret2 handles\. The ports the profiles filter on and ` extraTcp ` are always added\. ` null `: use the ports from ` strategySource `\.
**Type:** null or string\
**Default:** `null`\
@@ -453,7 +489,7 @@ TCP ports zapret2 handles\. Must include every port a profile uses\. ` null `: u
<a id="services-proxy-suite-zapret-zapret2-ports-udp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.udp
UDP ports zapret2 handles\. Must include every port a profile uses\. ` null `: use the ports from ` strategySource `\.
UDP ports zapret2 handles\. The ports the profiles filter on and ` extraUdp ` are always added\. ` null `: use the ports from ` strategySource `\.
**Type:** null or string\
**Default:** `null`\
@@ -476,6 +512,15 @@ learning\. ` --qnum `, ` --fwmark ` and ` --lua-init ` are added for you\. ` nul
]
```
<a id="services-proxy-suite-zapret-zapret2-strategylog"></a>
## services\.proxy-suite\.zapret\.zapret2\.strategyLog
Log each counted failure and strategy switch to the journal, per site
(` proxy-ctl logs proxy-suite-zapret `)\. Without it nfqws2 logs them only with ` debug `\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-zapret-zapret2-strategysource"></a>
## services\.proxy-suite\.zapret\.zapret2\.strategySource
+1 -12
View File
@@ -1,15 +1,4 @@
{ config, lib, pkgs, ... }:
{
services.proxy-suite = {
enable = true;
zapret = {
enable = true;
global.enable = false; # no system-wide zapret
};
perAppRouting = {
enable = true;
createDefaultProfiles = true; # adds a profile named "zapret"
zapret.enable = true;
};
};
services.proxy-suite.zapret.zapret2.ports.extraUdp = [ "27015-27030" ];
}
+15
View File
@@ -0,0 +1,15 @@
{ config, lib, pkgs, ... }:
{
services.proxy-suite = {
enable = true;
zapret = {
enable = true;
global.enable = false; # no system-wide zapret
};
perAppRouting = {
enable = true;
createDefaultProfiles = true; # adds a profile named "zapret"
zapret.enable = true;
};
};
}
+5 -2
View File
@@ -81,8 +81,11 @@ proxySuite = inputs.proxy-suite.lib.proxyHelpers {
## Reference
- `urls.http`, `urls.socks`: the proxy's URLs. A listener on `0.0.0.0` or `::` is reached on
loopback.
- `urls.http`, `urls.socks5h`, `urls.socks5`: the proxy's URLs. A listener on `0.0.0.0` or
`::` is reached on loopback. With `socks5h://` the proxy resolves names; `socks5://`
resolves them locally, for programs that do not accept `socks5h://`, such as Chromium and
Electron apps.
- `urls.socks`: the same as `urls.socks5h`.
- `env`: every proxy variable (`http_proxy`, `https_proxy`, `all_proxy`, their upper-case
forms, and `no_proxy`). `envFor "http"` or `envFor "socks"` gives one kind only.
- `wrapEnv { protocol ? "http"; programs ? null; } package`: the package, with its programs
+16 -2
View File
@@ -45,6 +45,17 @@ services.proxy-suite = {
the full RKN list and uses more memory. It also turns on a workaround for ISPs that cut
TLS to some hosting networks after about 16 KB.
Each failure zapret2 counts and each strategy switch is logged, per site:
`proxy-ctl logs proxy-suite-zapret`. A site stays on its first strategy as long as that one
works.
Other ports, such as a game's, take the same strategies with `zapret2.ports.extraUdp` or
`extraTcp`:
```nix
services.proxy-suite.zapret.zapret2.ports.extraUdp = [ "27015-27030" ];
```
## Commands
```sh
@@ -60,8 +71,10 @@ proxy-ctl zapret cutoff # networks cut off at 16 KB (z2k)
## With a proxy
zapret and the proxy work side by side. By default (`zapret.directSync`), the sites zapret
handles are sent direct, so they skip the proxy and reach zapret. Everything else follows
your [routing rules](./routing.md).
handles are sent direct, so they skip the proxy and reach zapret. With zapret2 that includes
the sites it learns and the ones you pin with `proxy-ctl zapret auto add`, as soon as they
are added; your own rules and autoProxy still come first. Everything else follows your
[routing rules](./routing.md).
## Only for some apps
@@ -100,4 +113,5 @@ belong to the system-wide zapret, so they do nothing here. See
- [`zapret.global.enable`](../options/zapret.md#services-proxy-suite-zapret-global-enable)
- [`zapret-discord-youtube.configName`](../options/zapret.md#services-proxy-suite-zapret-zapret-discord-youtube-configname)
- [`zapret2.strategySource`](../options/zapret.md#services-proxy-suite-zapret-zapret2-strategysource)
- [`zapret2.ports.extraUdp`](../options/zapret.md#services-proxy-suite-zapret-zapret2-ports-extraudp)
- [`zapret.directSync`](../options/zapret.md#services-proxy-suite-zapret-directsync-enable)
+6
View File
@@ -553,6 +553,9 @@ let
# The cut-off networks no whitelisted name fixes go through the proxy outbound.
zapretCutoffProxyFallback =
zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds;
# directSync for what zapret2 pins and learns at runtime: a rule-set the proxy reloads.
# The fixed lists go in with the routing rules (rules-zapret-direct.nix).
zapret2DirectSync = zapretEngine == "zapret2" && zapretGlobalEnabled && zapretCfg.directSync.enable;
userControlEnabled = userControlCfg.enable;
# Whether userControl.group, which owns proxy-suite's files, holds a scope; no scopes
# listed means all of them. The groups in userControl.groups get theirs through ACLs.
@@ -678,6 +681,8 @@ let
# Not under zapret2/, which the zapret scope's group writes to: root works here by
# fixed names (the group asks for probes in requests/).
zapret2CutoffDir = "${stateDir}/zapret2-cutoff";
# The same for the rule-set of zapret2's runtime hosts: what is in it skips the proxy.
zapret2DirectDir = "${stateDir}/zapret2-direct";
# Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone.
zapret2CutoffProbeCtMark = 33554432; # 0x2000000
@@ -878,6 +883,7 @@ in
zapretGlobalEnabled
zapretCutoffEnabled
zapretCutoffProxyFallback
zapret2DirectSync
userControlCfg
userControlEnabled
userControlAllows
+9 -3
View File
@@ -32,10 +32,14 @@ let
checked =
value: if envUnavailable != null then throw "proxy-suite helpers: ${envUnavailable}" else value;
urls = checked {
urls = checked rec {
http = "http://${credentials}${hostPort}";
# socks5h: names are resolved by the proxy, so they follow its routing.
socks = "socks5h://${credentials}${hostPort}";
socks5h = "socks5h://${credentials}${hostPort}";
# socks5: names are resolved locally. For programs that refuse socks5h, like
# Chromium and Electron apps (VS Code's http.proxy).
socks5 = "socks5://${credentials}${hostPort}";
socks = socks5h;
};
httpVars = [
@@ -63,7 +67,9 @@ let
or (throw "proxy-suite helpers: protocol must be \"http\", \"socks\" or \"all\", not \"${protocol}\"");
envFor =
protocol:
lib.genAttrs (varsOf protocol) (name: if builtins.elem name httpVars then urls.http else urls.socks)
lib.genAttrs (varsOf protocol) (
name: if builtins.elem name httpVars then urls.http else urls.socks5h
)
// noProxy;
# A copy of `package` whose programs (all of bin/, or the named ones) are replaced by
+5 -1
View File
@@ -31,7 +31,11 @@ in
# What zapret feeds back into the client routing table.
directSync = {
enable = bool true "Send zapret's domains direct in the proxy routing, so zapret handles them.";
enable = bool true ''
Send zapret's domains direct in the proxy routing, so zapret handles them. With zapret2,
also the sites it pins and learns at runtime, after your own rules and autoProxy's.
The all-proxy and all-bypass route modes leave them out, like every direct list.
'';
upstreamIps = bool false "Also send zapret's upstream IP lists direct.";
userIps = bool true "Also send `zapret-discord-youtube.ips` (minus `excludeIps`) direct.";
};
+43 -2
View File
@@ -4,6 +4,7 @@ let
inherit (lib) mkEnableOption mkOption types;
int = (import ./lib.nix { inherit lib; }).positiveInt;
fromSource = what: "`null`: use the ${what} from `strategySource`.";
portOrRange = types.either types.port (types.strMatching "[0-9]+(-[0-9]+)?");
in
{
options.services.proxy-suite.zapret.zapret2 = {
@@ -63,16 +64,56 @@ in
tcp = mkOption {
type = types.nullOr types.str;
default = null;
description = "TCP ports zapret2 handles. Must include every port a profile uses. ${fromSource "ports"}";
description = "TCP ports zapret2 handles. The ports the profiles filter on and `extraTcp` are always added. ${fromSource "ports"}";
example = "80,443";
};
udp = mkOption {
type = types.nullOr types.str;
default = null;
description = "UDP ports zapret2 handles. Must include every port a profile uses. ${fromSource "ports"}";
description = "UDP ports zapret2 handles. The ports the profiles filter on and `extraUdp` are always added. ${fromSource "ports"}";
example = "443";
};
extraTcp = mkOption {
type = types.listOf portOrRange;
default = [ ];
description = ''
More TCP ports, handled like the profiles' own: each profile that recognizes its traffic
(`--filter-l7`, e.g. TLS) gets them too, so TLS to a blocked site on one of these ports
gets the same strategies. A profile without `--filter-l7` keeps its ports.
'';
example = [
8444
"9000-9010"
];
};
extraUdp = mkOption {
type = types.listOf portOrRange;
default = [ ];
description = ''
More UDP ports, handled like the profiles' own: each profile that recognizes its traffic
(`--filter-l7`, e.g. STUN, Discord, QUIC) gets them too, so a game's or call app's STUN
on these ports gets the same strategies as Discord's.
'';
example = [ "27015-27030" ];
};
};
strategyLog = mkOption {
type = types.bool;
default = true;
description = ''
Log each counted failure and strategy switch to the journal, per site
(`proxy-ctl logs proxy-suite-zapret`). Without it nfqws2 logs them only with `debug`.
'';
};
debug = mkOption {
type = types.bool;
default = false;
description = "Log everything nfqws2 does to the journal, every packet included. Very verbose: for troubleshooting.";
};
ipv6 = mkOption {
+13 -2
View File
@@ -81,6 +81,12 @@ let
[ ];
zapretExcludedDomains =
if syncZapretDirectDomains then parseListFile "${zapretSrc}/hostlists/list-exclude.txt" else [ ];
# zapret2's own pinned domains; what it learns at runtime is not synced.
zapret2 = zapretCfg.engine == "zapret2";
zapret2Domains = lib.optionals (syncZapretDirectDomains && zapret2) zapretCfg.zapret2.domains;
zapret2ExcludedDomains = lib.optionals (
syncZapretDirectDomains && zapret2
) zapretCfg.zapret2.excludeDomains;
zapretExcludedIps = lib.unique (
(
if syncZapretDirectUpstreamIps then
@@ -103,12 +109,17 @@ let
subtractItems
(lib.unique (
map stripExactPrefix (
zapretDefaultDomains ++ zapretCfg.zapret-discord-youtube.domains ++ zapretCustomDomains
zapretDefaultDomains
++ zapretCfg.zapret-discord-youtube.domains
++ zapretCustomDomains
++ zapret2Domains
)
))
(
lib.unique (
map stripExactPrefix (zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains)
map stripExactPrefix (
zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains ++ zapret2ExcludedDomains
)
)
)
else
@@ -15,6 +15,7 @@ let
pureXrayEnabled
constants
zapretCutoffProxyFallback
zapret2DirectSync
jq
singBox
xray
@@ -185,6 +186,7 @@ let
enableAutoProxy ? false,
enableOutboundTest ? false,
enableZapretCutoff ? false,
enableZapretDirect ? false,
excludeServiceUserFromTun ? false,
}:
pkgs.writeShellScript "proxy-suite-core" ''
@@ -364,6 +366,25 @@ let
fi
''}
${lib.optionalString enableZapretDirect ''
# directSync for the hosts zapret2 pins and learns at runtime: direct, so zapret2
# sees them. Last, after explicit rules, autoProxy's exits and the cutoff's networks,
# which zapret2 cannot fix. all-proxy and all-bypass keep no direct lists.
case "$ROUTE_MODE" in
all-proxy | all-bypass) ;;
*)
ZAPRET_RULE_SET=${lib.escapeShellArg "${constants.zapret2DirectDir}/direct.json"}
# The sync unit owns the directory's mode: what is in it skips the proxy.
mkdir -p "$(dirname "$ZAPRET_RULE_SET")"
[ -s "$ZAPRET_RULE_SET" ] || echo '{"version":1,"rules":[]}' > "$ZAPRET_RULE_SET"
chmod 644 "$ZAPRET_RULE_SET"
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$ZAPRET_RULE_SET" \
'. + [{type: "local", format: "source", tag: "zapret-hosts", path: $p}]' <<< "$AUTOPROXY_RULE_SETS_JSON")
AUTOPROXY_RULES_JSON=$(${jq} -c '. + [{rule_set: ["zapret-hosts"], outbound: "direct"}]' <<< "$AUTOPROXY_RULES_JSON")
;;
esac
''}
# umask: the file holds credentials until the chmod below; the process
# substitutions keep them out of the argv every local user can read.
(umask 077 && ${jq} \
@@ -498,6 +519,7 @@ let
# Only the socks unit: relayed traffic reaches it, and the prober needs one home.
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
enableZapretCutoff = zapretCutoffProxyFallback && !pureXrayEnabled;
enableZapretDirect = zapret2DirectSync && !pureXrayEnabled;
enableOutboundTest = true;
};
+8
View File
@@ -22,6 +22,7 @@ let
userControlAnyAllows
userControlExtraGroupsFor
zapretGlobalEnabled
zapret2DirectSync
;
inherit
(import ./zapret/common.nix {
@@ -131,8 +132,15 @@ let
;
};
directSync = import ./zapret2/direct-sync.nix { inherit lib pkgs cfg; };
in
{
services.proxy-suite.internal.services.proxy-suite-zapret2-direct =
lib.mkIf zapret2DirectSync directSync.service;
services.proxy-suite.internal.paths.proxy-suite-zapret2-direct =
lib.mkIf zapret2DirectSync directSync.path;
services.proxy-suite.internal.earlyPackages = [ runtime.package ];
services.proxy-suite.internal.services.proxy-suite-zapret2-cutoff =
@@ -0,0 +1,54 @@
# directSync for the hosts zapret2 pins (`proxy-ctl zapret auto add`) and learns at
# runtime: a rule-set the proxy sends direct, so zapret2 sees their traffic. Rebuilt
# whenever a host list changes; sing-box reloads it on the rename.
{
lib,
pkgs,
cfg,
}:
let
fillTemplate = import ../lib/fill-template.nix;
inherit (import ../derived.nix { inherit lib cfg; }) constants;
stateDir = constants.zapret2StateDir;
ruleSet = "${constants.zapret2DirectDir}/direct.json";
sync = pkgs.writeShellScript "proxy-suite-zapret2" (
fillTemplate ./direct-sync.template.sh {
path = lib.makeBinPath [
pkgs.coreutils
pkgs.diffutils
pkgs.jq
];
}
);
in
{
inherit sync ruleSet;
service = {
description = "proxy-suite - send the hosts zapret2 pins and learns direct in the proxy";
# Ahead of the proxy at boot, so it starts with the hosts already in.
before = [ "proxy-suite-socks.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${sync} ${lib.escapeShellArg stateDir} ${lib.escapeShellArg ruleSet}";
# Root's alone, like the cutoff's: what is in it skips the proxy, so the zapret
# scope's group, which edits the host lists, only reaches it through them.
StateDirectory = "proxy-suite/zapret2-direct";
StateDirectoryMode = "0755";
}
// constants.rootInSharedDirConfig;
};
path = {
description = "proxy-suite - watch zapret2's host lists for directSync";
wantedBy = [ "paths.target" ];
pathConfig.PathChanged = map (name: "${stateDir}/${name}") [
"zapret-hosts-user.txt"
"zapret-hosts-auto.txt"
"zapret-hosts-user-exclude.txt"
];
};
}
@@ -0,0 +1,36 @@
# $1: zapret2's state directory, $2: the rule-set to write. The hosts zapret2 pins and
# learns, less the excluded ones, as a sing-box source rule-set the proxy sends direct.
# Rewritten only when it changes: sing-box reloads it on every rename.
set -euo pipefail
export PATH=@path@
dir=$1
out=$2
lists() {
local f
for f in "$@"; do
[ -r "$f" ] && cat "$f"
done
true
}
lists "$dir/zapret-hosts-user.txt" "$dir/zapret-hosts-auto.txt" \
| jq -R -n -c --rawfile excluded <(lists "$dir/zapret-hosts-user-exclude.txt") '
# nfqws hostlists: one host per line, "#" comments, "^" for the name alone.
def hosts: map(gsub("^\\s+|\\s+$"; "") | ascii_downcase | ltrimstr("^"))
| map(select(. != "" and (startswith("#") | not)));
($excluded | split("\n") | hosts) as $excluded
| ([inputs] | hosts | unique) - $excluded
| map(select(test("^[0-9.]+$|:"))) as $ips
| {version: 1, rules: (
[(. - $ips) | select(length > 0) | {domain_suffix: .}]
+ [$ips | select(length > 0)
| {ip_cidr: map(. + (if test(":") then "/128" else "/32" end))}])}
' >"$out.tmp"
if cmp -s "$out.tmp" "$out"; then
rm "$out.tmp"
else
chmod 644 "$out.tmp"
mv "$out.tmp" "$out"
fi
@@ -0,0 +1,47 @@
-- z2k-state-persist.lua keeps a host's strategy in memory and writes it to state.tsv
-- only while the change is new: a write it skips is never retried, unless some other
-- host changes later. It skips one within 2 s of the last (for router flash) and one
-- while another writer holds the lock (the per-app instance, proxy-ctl). A restart
-- then loses the switch. Every change is written now, and a minute after a change
-- the whole state is written once more, whatever happened to the first write.
local api = z2k_state_persist
if not (api and api._set_interval and api._state and api.flush) then
error("proxy-suite: z2k-state-persist.lua no longer exports _set_interval, _state and flush")
end
api._set_interval(0)
local RECHECK = 60 -- seconds
local function digest()
local rows = {}
for askey, hosts in pairs(api._state()) do
for host, rec in pairs(hosts) do
rows[#rows + 1] = table.concat({
tostring(askey), tostring(host), tostring(rec.strategy), tostring(rec.mode),
tostring(rec.sni), tostring(rec.deleted),
}, "\t")
end
end
table.sort(rows)
return table.concat(rows, "\n")
end
-- From the start: a write that failed on the first packet is retried too.
local checked, seen = os.time(), digest()
-- Checked on traffic, not on a timer: a timer would keep nfqws2 --dry-run from exiting.
local rotate = circular
if type(rotate) == "function" then
function circular(ctx, desync)
local verdict = rotate(ctx, desync)
local now = os.time()
if now - checked >= RECHECK then
checked = now
local d = digest()
if d ~= seen then api.flush() end
seen = d
end
return verdict
end
end
+62
View File
@@ -0,0 +1,62 @@
# nfqws2's options in, with the extra ports (xtcp, xudp) joined to every profile that
# tells its traffic by protocol (--filter-l7). The ports to queue go to the file named
# by `ports`: the base lists (btcp, budp), the extras, and every port a profile filters
# on, since a profile port the queue lacks never sees a packet. Overlaps are merged:
# nftables refuses overlapping intervals in a set.
function mark(proto, list, n, p, i, r, lo, hi, port) {
n = split(list, p, ",")
for (i = 1; i <= n; i++) {
# ~negated, * and empty name nothing to queue.
if (p[i] !~ /^[0-9]+(-[0-9]+)?$/) continue
split(p[i], r, "-")
lo = r[1] + 0
hi = (p[i] ~ /-/) ? r[2] + 0 : lo
if (lo < 1) lo = 1
if (hi > 65535) hi = 65535
for (port = lo; port <= hi; port++) queued[proto, port] = 1
}
}
function ranges(proto, port, lo, out) {
out = ""
lo = 0
for (port = 1; port <= 65536; port++) {
if ((proto, port) in queued) {
if (!lo) lo = port
} else if (lo) {
out = out (out == "" ? "" : ",") (lo == port - 1 ? lo : lo "-" (port - 1))
lo = 0
}
}
return out
}
{
for (i = 1; i <= NF; i++) tok[++n] = $i
}
END {
prof = 0
for (i = 1; i <= n; i++) {
if (tok[i] == "--new") prof++
else if (tok[i] ~ /^--filter-l7=/) l7[prof] = 1
}
prof = 0
for (i = 1; i <= n; i++) {
t = tok[i]
if (t == "--new") {
prof++
} else if (t ~ /^--filter-tcp=/) {
if ((prof in l7) && xtcp != "") t = t "," xtcp
mark("tcp", substr(t, 14))
} else if (t ~ /^--filter-udp=/) {
if ((prof in l7) && xudp != "") t = t "," xudp
mark("udp", substr(t, 14))
}
printf "%s%s", (i > 1 ? " " : ""), t
}
mark("tcp", btcp "," xtcp)
mark("udp", budp "," xudp)
printf "NFQWS2_PORTS_TCP=%s\nNFQWS2_PORTS_UDP=%s\n", ranges("tcp"), ranges("udp") >ports
}
@@ -0,0 +1,60 @@
-- circular keys a site's strategy by the host's last nld labels (nld=2: example.com),
-- so one strategy serves a site and its subdomains. Under a public suffix of two
-- labels that lumps unrelated sites together: every *.co.uk shared one strategy, and
-- one that worked kept the failures of another from counting. nld now counts from the
-- public suffix (the list's ICANN section): foo.co.uk, not co.uk. A key the state layer
-- remembered under the old scheme is simply no longer used.
local exact, wild, except = {}, {}, {}
for rule in io.lines("@suffixes@") do
if rule:sub(1, 1) == "!" then
except[rule:sub(2)] = true
elseif rule:sub(1, 2) == "*." then
wild[rule:sub(3)] = true
else
exact[rule] = true
end
end
-- How many trailing labels the public suffix spans: the longest rule that matches, an
-- exception taking one label off its rule, and a single label when no rule does.
local function suffix_labels(labels)
local n = #labels
for i = 1, n do
local tail = table.concat(labels, ".", i, n)
if except[tail] then return n - i end
if exact[tail] or (i < n and wild[table.concat(labels, ".", i + 1, n)]) then return n - i + 1 end
end
return 1
end
local cache, cached = {}, 0
local function public_suffix_nld(host, nld)
local id = nld .. " " .. host
local key = cache[id]
if key then return key end
local labels = {}
for label in host:lower():gsub("%.$", ""):gmatch("[^.]+") do labels[#labels + 1] = label end
if #labels == 0 then return nil end
local first = math.max(1, #labels - (suffix_labels(labels) + nld - 1) + 1)
key = table.concat(labels, ".", first)
if cached >= 8192 then cache, cached = {}, 0 end
cache[id], cached = key, cached + 1
return key
end
local standard = standard_hostkey
if type(standard) ~= "function" then
error("proxy-suite: zapret-auto.lua no longer defines standard_hostkey")
end
function standard_hostkey(desync)
local nld = tonumber(desync.arg.nld)
local track = desync.track
if nld and nld > 0 and track and track.hostname and not track.hostname_is_ip then
local key = public_suffix_nld(track.hostname, nld)
if key then return key end
end
return standard(desync)
end
@@ -0,0 +1,29 @@
# The ICANN section of the public suffix list, one rule per line, every label in the
# xn-- form a TLS SNI carries ("рф" is "xn--p1ai" on the wire).
import sys
def ascii_label(label):
return label if label == "*" or label.isascii() else "xn--" + label.encode("punycode").decode()
def ascii_rule(rule):
bang = "!" if rule.startswith("!") else ""
return bang + ".".join(ascii_label(label) for label in rule.removeprefix("!").lower().split("."))
inside = False
rules = []
with open(sys.argv[1], encoding="utf-8") as f:
for line in f:
line = line.strip()
if line == "// ===BEGIN ICANN DOMAINS===":
inside = True
elif line == "// ===END ICANN DOMAINS===":
break
elif inside and line and not line.startswith("//"):
rules.append(ascii_rule(line.split()[0]))
if len(rules) < 1000:
sys.exit(f"only {len(rules)} ICANN rules: did the list's format change?")
print("\n".join(rules))
+36 -5
View File
@@ -109,18 +109,45 @@ let
end
'';
# The state layer wraps circular, so it loads after the source's Lua.
publicSuffixHostkey = pkgs.writeText "proxy-suite-zapret2-public-suffix-hostkey.lua" (
fillTemplate ./public-suffix-hostkey.lua {
suffixes =
pkgs.runCommand "proxy-suite-zapret2-public-suffixes"
{
nativeBuildInputs = [ pkgs.python3 ];
}
"python3 ${./public-suffixes.py} ${pkgs.publicsuffix-list}/share/publicsuffix/public_suffix_list.dat >$out";
}
);
# The state layer wraps circular, so it loads after the source's Lua; the writes it
# skips are retried after it, and the log wraps them all, to report the switch that stuck.
#
# --bind-fix: a fake leaves by the interface its connection does. Under policy routing
# (an app or a domain sent through a tunnel) it would otherwise take the default route,
# away from the connection it was meant to precede; without such routing it is a no-op.
optPrefix = lib.concatStringsSep " " (
map (file: "--lua-init=@${file}") (
lib.optional zapret2Cfg.debug "--debug=1"
++ [
"--bind-fix4"
"--bind-fix6"
]
++ source.daemonArgs
++ map (file: "--lua-init=@${file}") (
source.luaInit
++ [
publicSuffixHostkey
failStamp
"${zapret2Sources.z2k}/files/lua/z2k-state-persist.lua"
./persist-every.lua
]
++ lib.optional zapret2Cfg.strategyLog ./strategy-log.lua
)
++ lib.mapAttrsToList (name: file: "--blob=${name}:@${blobPath file}") zapret2Cfg.blobs
);
portList = lib.concatMapStringsSep "," toString;
# Detector args a circular instance leaves unset come from autoHostlist, so
# learning and rotation agree; each source keeps its own fails and time.
circularFill = lib.concatStringsSep " " (
@@ -169,8 +196,6 @@ let
++ lib.optional (!zapret2Cfg.ipv6) "DISABLE_IPV6=1"
++ [
"NFQWS2_ENABLE=1"
"NFQWS2_PORTS_TCP=${orSource zapret2Cfg.ports.tcp source.ports.tcp}"
"NFQWS2_PORTS_UDP=${orSource zapret2Cfg.ports.udp source.ports.udp}"
"NFQWS2_TCP_PKT_OUT=${toString packetWindow.tcpOut}"
"NFQWS2_TCP_PKT_IN=${toString packetWindow.tcpIn}"
"NFQWS2_UDP_PKT_OUT=${toString packetWindow.udpOut}"
@@ -194,6 +219,10 @@ let
{
nativeBuildInputs = [ pkgs.gawk ];
inherit circularFill optPrefix;
basePortsTcp = orSource zapret2Cfg.ports.tcp source.ports.tcp;
basePortsUdp = orSource zapret2Cfg.ports.udp source.ports.udp;
extraPortsTcp = portList zapret2Cfg.ports.extraTcp;
extraPortsUdp = portList zapret2Cfg.ports.extraUdp;
}
''
opt="$optPrefix $(cat ${blobsFile}) $(cat ${profilesFile})"
@@ -212,13 +241,15 @@ let
printf "%s%s", (i > 1 ? " " : ""), t
}
}')
opt=$(printf '%s\n' "$opt" | awk -v btcp="$basePortsTcp" -v budp="$basePortsUdp" \
-v xtcp="$extraPortsTcp" -v xudp="$extraPortsUdp" -v ports=ports -f ${./ports.awk})
case "$opt" in
*"'"*)
echo "nfqws2 options must not contain a single quote" >&2
exit 1
;;
esac
{ cat ${header}; printf "NFQWS2_OPT='%s'\n" "$opt"; } >"$out"
{ cat ${header} ports; printf "NFQWS2_OPT='%s'\n" "$opt"; } >"$out"
'';
# {circular key: {strategy: [its desync instances]}}, for proxy-ctl to name the
+37 -8
View File
@@ -31,6 +31,14 @@ let
else
builtins.head (splitString stop (builtins.elemAt parts 1));
# The same for a fix to a pinned file: one that no longer applies must fail the build.
patch =
what: from: to: text:
if lib.hasInfix from text then
replaceStrings [ from ] [ to ] text
else
throw "proxy-suite: expected `${from}` in ${what}; did a flake input bump change it?";
keenetic =
let
src = sources.nfqws2-keenetic;
@@ -46,29 +54,46 @@ let
)
);
lists = "--hostlist=${src}/etc/nfqws2/lists/user.list --hostlist-exclude=${src}/etc/nfqws2/lists/exclude.list";
circular = "--lua-desync=circular:fails=2:time=300:retrans=3:nld=2";
tcpPayload = "--payload=tls_client_hello,mtproto_initial";
udpPayload = "--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown";
in
{
# Its init script's order. QUIC reads the learned list but never adds to it:
# browsers retry over TCP. The UDP profile carries no SNI, so no lists.
#
# circular counts failures on the packets Lua is handed, and nfqws2 hands it no
# incoming ones by default. As shipped it never saw a reset or a server's reply
# (only a silent drop rotated TCP), and on UDP, behind <n2, only the first packet
# of the udp_out it waits for: UDP never rotated. circular gets them now, as in
# zapret2's manual, and the strategies after it keep their own filters. The NFQUEUE
# window still bounds what reaches Lua.
profiles = [
# Its first UDP strategy's fake has no blob, which zapret2 rejects on every
# packet; nfqws1's default for unknown UDP was 64 zero bytes.
(replaceStrings
[ "--lua-desync=fake:repeats=6:strategy=1" ]
[
(lib.pipe (args "NFQWS_ARGS_UDP") [
(patch "NFQWS_ARGS_UDP" "--lua-desync=fake:repeats=6:strategy=1"
"--lua-desync=fake:blob=0x${lib.fixedWidthString 128 "0" ""}:repeats=6:strategy=1"
]
(args "NFQWS_ARGS_UDP")
)
)
(patch "NFQWS_ARGS_UDP" "--out-range=<n2 ${udpPayload} ${circular}"
"--out-range=a --in-range=a ${udpPayload} ${circular} --out-range=<n2 --in-range=x"
)
])
"${args "NFQWS_ARGS_QUIC"} <HOSTLIST_NOAUTO> ${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}"
# broke every host on a line where the strategies alone work. Its HTTP strategy
# has no strategy=N, so circular must not take http_req: it would skip it.
"${
patch "NFQWS_ARGS" "${tcpPayload} ${circular}"
"--in-range=-s5556 ${tcpPayload},tls_server_hello,empty,unknown ${circular} --in-range=x ${tcpPayload}"
(args "NFQWS_ARGS")
} <HOSTLIST> ${lists}"
];
blobArgs = map (replaceStrings [ "@/opt/etc/nfqws2/" ] [ "@${src}/etc/nfqws2/" ]) (
filter (hasPrefix "--blob=") (words (quoted "NFQWS_BASE_ARGS"))
);
luaInit = [ ];
daemonArgs = [ ];
ports = {
tcp = bare "TCP_PORTS";
udp = replaceStrings [ ":" ] [ "-" ] (bare "UDP_PORTS");
@@ -93,6 +118,10 @@ let
"z2k-range-rand"
"z2k-modern-core"
];
# As its S99zapret2 runs nfqws2: a connection without SNI (some TVs and apps, a
# SYN before the ClientHello its syndata strategies act on) takes the name last
# seen on that IP, so it still meets its site's profile and strategy.
daemonArgs = [ "--ipcache-hostname=1" ];
ports = {
tcp = ports "NFQWS2_PORTS_TCP";
udp = ports "NFQWS2_PORTS_UDP";
@@ -0,0 +1,57 @@
-- One journal line per counted failure and per strategy switch. nfqws2 logs them
-- only with --debug, among every packet's lines. Loaded after z2k-state-persist.lua,
-- so the switch it reports is the one that stuck, after its sticky-success revert.
local count, rotate = automate_failure_counter, circular
-- host record -> its strategy when the failure count was reached: circular, or
-- z2k's QUIC silence timer, switches it right after.
local pending = setmetatable({}, { __mode = "k" })
-- "<circular key> <host>": the record knows neither, autostate maps them to it.
local function name(hrec)
for askey, hosts in pairs(autostate or {}) do
for host, rec in pairs(hosts) do
if rec == hrec then return tostring(askey) .. " " .. tostring(host) end
end
end
return "?"
end
local function log(hrec, text)
io.stderr:write("zapret2: ", name(hrec), ": ", text, "\n")
end
local function of(hrec)
return tostring(hrec.nstrategy or 1) .. "/" .. tostring(hrec.ctstrategy or "?")
end
function automate_failure_counter(hrec, crec, fails, maxtime)
local duplicate = crec and crec.failure
local reached = count(hrec, crec, fails, maxtime)
if reached then
pending[hrec] = hrec.nstrategy or 1
elseif not duplicate and hrec.failure_counter then
log(hrec, "failure " .. tostring(hrec.failure_counter) .. "/" .. tostring(fails) .. " on strategy " .. of(hrec))
end
return reached
end
local function report()
for hrec, before in pairs(pending) do
pending[hrec] = nil
if (hrec.nstrategy or 1) ~= before then
log(hrec, "switched from strategy " .. tostring(before) .. " to " .. of(hrec))
else
log(hrec, "failed enough to switch, but stays on strategy " .. of(hrec) .. ": it worked moments ago, or that strategy is final")
end
end
end
if type(rotate) == "function" then
function circular(ctx, desync)
local verdict = rotate(ctx, desync)
-- Also what the QUIC timer switched since the last packet.
if next(pending) then report() end
return verdict
end
end
+2
View File
@@ -273,6 +273,8 @@ let
pkgs
evalProxySuite
baseModule
mkRoutingRules
hasDirectDomain
mkProxyCtlDerived
mkBadFixture
mkFailingAssertions
+3
View File
@@ -57,6 +57,9 @@ let
viaTun = helpers.wrapPerApp { profile = "tun"; } fake;
in
assert helpers.urls.http == "http://127.0.0.1:1080";
assert helpers.urls.socks5h == "socks5h://127.0.0.1:1080";
assert helpers.urls.socks5 == "socks5://127.0.0.1:1080";
assert helpers.urls.socks == helpers.urls.socks5h;
assert helpers.env.ALL_PROXY == "socks5h://127.0.0.1:1080";
assert refuses (bare.wrapProxychains { } fake);
assert refuses (bare.wrapPerApp { profile = "tun"; } fake);
+161 -1
View File
@@ -2,6 +2,8 @@
pkgs,
evalProxySuite,
baseModule,
mkRoutingRules,
hasDirectDomain,
mkProxyCtlDerived,
mkBadFixture,
mkFailingAssertions,
@@ -18,6 +20,7 @@ let
zapret2Tuned
zapret2NoAuto
zapret2Z2k
zapret2Z2kTuned
zapret2NoFallback
;
@@ -43,10 +46,14 @@ let
tunedRuntime = runtimeDir zapret2Tuned globalService;
noAutoRuntime = runtimeDir zapret2NoAuto globalService;
z2kRuntime = runtimeDir zapret2Z2k globalService;
z2kTunedRuntime = runtimeDir zapret2Z2kTuned 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;
directSync = builtins.head (
lib.splitString " " zapret2Global.config.systemd.services.proxy-suite-zapret2-direct.serviceConfig.ExecStart
);
proxyCtlEnv = fixture: (mkProxyCtlDerived fixture).wrapperEnv;
in
@@ -128,6 +135,27 @@ in
true
)
# directSync sends zapret2's pinned domains direct, so zapret2 sees them; its excludes stay out.
(
let
rules = mkRoutingRules zapret2Tuned;
in
assert hasDirectDomain rules "pinned.example";
assert !(hasDirectDomain rules "excluded.example");
assert !(hasDirectDomain (mkRoutingRules zapretDiscordYoutubeGlobal) "pinned.example");
true
)
# The hosts zapret2 pins and learns at runtime are synced too, whenever a list changes.
(
assert zapret2Global.config.systemd.paths ? proxy-suite-zapret2-direct;
assert
zapret2Global.config.systemd.services.proxy-suite-zapret2-direct.serviceConfig.StateDirectoryMode
== "0755";
assert !(zapretDiscordYoutubeGlobal.config.systemd.services ? proxy-suite-zapret2-direct);
true
)
# `proxy-ctl zapret auto` only makes sense when something is learning.
(
assert (proxyCtlEnv zapret2Global).ZAPRET_AUTO_ENABLED == "1";
@@ -177,6 +205,17 @@ in
grep -qF -- '<HOSTLIST_NOAUTO> --hostlist-domains=pinned.example --hostlist-exclude-domains=excluded.example' "${tunedRuntime}/config"
test "$(grep -oF -- '--hostlist-domains=pinned.example' "${tunedRuntime}/config" | wc -l)" = 2
# Extra ports join every profile that tells its traffic by protocol, and the
# queue, merged with what overlaps.
grep -qF -- '--filter-tcp=443,80,1984,5222,8444 --filter-l7=http,tls,mtproto' "${tunedRuntime}/config"
grep -qF -- '--filter-udp=443,27015-27030,50000-50100 --filter-l7=quic' "${tunedRuntime}/config"
grep -qx 'NFQWS2_PORTS_TCP=80,443,1984,2053,2083,2087,2096,5222,8443-8444' "${tunedRuntime}/config"
grep -qx 'NFQWS2_PORTS_UDP=443,590-600,1400,3478-3481,5349,19294-19344,27015-27030,49152-65535' "${tunedRuntime}/config"
# A profile that does not check the protocol keeps its ports: on 5222 it splits anything.
grep -qF -- '--filter-tcp=5222 --payload=unknown' "${z2kTunedRuntime}/config"
grep -qF -- '--filter-tcp=80 ' "${z2kTunedRuntime}/config"
grep -qF -- ' --new --filter-tcp=443,2053,2083,2087,2096,8443,8444 --filter-l7=tls ' "${z2kTunedRuntime}/config"
# --- strategy sources -----------------------------------------------
# nfqws2-keenetic by default; every source remembers strategies across restarts.
grep -qx 'NFQWS2_PORTS_TCP=80,443,1984,2053,2083,2087,2096,5222,8443' "${globalRuntime}/config"
@@ -195,16 +234,114 @@ in
automate_failure_counter(hrec, crec, 2, 60)
assert(hrec.z2k_last_fail_ts == 1, "a duplicate failure is not counted, so not stamped")
'
# Every new host or switch reaches state.tsv, or a restart loses it; a z2k bump
# that drops the setter must fail the start, not quietly lose switches again.
grep -qE -- 'z2k-state-persist\.lua --lua-init=@[^ ]+-persist-every\.lua --lua-init=@[^ ]+-strategy-log\.lua' "${z2kRuntime}/config"
EVERY=$(grep -oE '/nix/store/[^ ]+-persist-every\.lua' "${globalRuntime}/config") lua -e '
local set, flushed, now = nil, 0, 1000
local state = { rkn_tcp = { ["example.com"] = { strategy = 1 } } }
z2k_state_persist = {
_set_interval = function(n) set = n end,
_state = function() return state end,
flush = function() flushed = flushed + 1 end,
}
os.time = function() return now end
function circular() return "verdict" end
dofile(os.getenv("EVERY"))
assert(set == 0)
-- A switch whose write was skipped is written within a minute; no change, no write.
state.rkn_tcp["example.com"].strategy = 2
assert(circular() == "verdict" and flushed == 0)
now = now + 60
circular()
assert(flushed == 1)
now = now + 60
circular()
assert(flushed == 1)
z2k_state_persist = { _set_interval = function() end }
assert(not pcall(dofile, os.getenv("EVERY")))
'
# nld counts from the public suffix, so sites under co.uk no longer share a strategy;
# the private section (github.io) stays one site, as before.
PSL=$(grep -oE '/nix/store/[^ ]+-proxy-suite-zapret2-public-suffix-hostkey\.lua' "${z2kRuntime}/config") lua -e '
function standard_hostkey() return "standard" end
dofile(os.getenv("PSL"))
local function key(host, nld, ip)
return standard_hostkey({ arg = { nld = nld }, track = { hostname = host, hostname_is_ip = ip } })
end
for host, want in pairs({
["www.google.com"] = "google.com",
["rr1.sn-abc.googlevideo.com"] = "googlevideo.com",
["a.b.foo.co.uk"] = "foo.co.uk",
["co.uk"] = "co.uk",
["x.y.github.io"] = "github.io",
["WWW.Example.COM."] = "example.com",
["www.xn--80aswg.xn--p1ai"] = "xn--80aswg.xn--p1ai",
["a.www.ck"] = "www.ck",
["foo.bar.ck"] = "foo.bar.ck",
}) do
assert(key(host, "2") == want, host .. ": " .. tostring(key(host, "2")))
end
assert(key("a.b.foo.co.uk", "3") == "b.foo.co.uk")
assert(key("1.2.3.4", "2", true) == "standard")
assert(key("www.google.com", nil) == "standard")
'
# Counted failures and switches, named by circular key and host; the switch
# is the one that stuck, after the state layer's revert.
LOG=$(grep -oE '/nix/store/[^ ]+-strategy-log\.lua' "${z2kRuntime}/config") lua -e '
function automate_failure_counter(hrec, crec, fails)
if crec.failure then return false end
crec.failure = true
hrec.failure_counter = (hrec.failure_counter or 0) + 1
if hrec.failure_counter < fails then return false end
hrec.failure_counter = nil
return true
end
local revert = false
function circular()
local hrec = autostate.rkn_tcp["example.com"]
local before = hrec.nstrategy
if automate_failure_counter(hrec, {}, 2) then hrec.nstrategy = hrec.nstrategy % hrec.ctstrategy + 1 end
if revert then hrec.nstrategy = before end
return "verdict"
end
autostate = { rkn_tcp = { ["example.com"] = { nstrategy = 1, ctstrategy = 50 } } }
dofile(os.getenv("LOG"))
assert(circular() == "verdict")
circular()
automate_failure_counter(autostate.rkn_tcp["example.com"], { failure = true }, 2)
revert = true
circular()
circular()
' 2>strategy.log
diff - strategy.log <<'EOF'
zapret2: rkn_tcp example.com: failure 1/2 on strategy 1/50
zapret2: rkn_tcp example.com: switched from strategy 1 to 2/50
zapret2: rkn_tcp example.com: failure 1/2 on strategy 2/50
zapret2: rkn_tcp example.com: failed enough to switch, but stays on strategy 2/50: it worked moments ago, or that strategy is final
EOF
# Off, the log is gone; debug hands nfqws2 its own.
if grep -qF -- 'strategy-log.lua' "${z2kTunedRuntime}/config"; then exit 1; fi
grep -qF -- "NFQWS2_OPT='--debug=1 --bind-fix4 --bind-fix6 --ipcache-hostname=1 --lua-init=" "${z2kTunedRuntime}/config"
# z2k's own daemon flags; the other source runs without the experimental name cache.
grep -qF -- "NFQWS2_OPT='--bind-fix4 --bind-fix6 --ipcache-hostname=1 --lua-init=" "${z2kRuntime}/config"
grep -qF -- "NFQWS2_OPT='--bind-fix4 --bind-fix6 --lua-init=" "${globalRuntime}/config"
# Every UDP fake carries a blob; zapret2 errors on each packet otherwise.
grep -qF -- '--lua-desync=fake:blob=0x0000' "${globalRuntime}/config"
if grep -qF -- '--lua-desync=fake:repeats=' "${globalRuntime}/config"; then exit 1; fi
# circular sees what it counts: incoming resets and replies on TCP, as many UDP
# packets as udp_out; the strategies after it keep their own filters.
grep -qF -- '--in-range=-s5556 --payload=tls_client_hello,mtproto_initial,tls_server_hello,empty,unknown --lua-desync=circular:' "${globalRuntime}/config"
grep -qE -- ':reset --in-range=x --payload=tls_client_hello,mtproto_initial --lua-desync=fake:' "${globalRuntime}/config"
grep -qE -- '--out-range=a --in-range=a --payload=[^ ]+ --lua-desync=circular:[^ ]+ --out-range=<n2 --in-range=x --lua-desync=fake:' "${globalRuntime}/config"
# autoHostlist fills what circular leaves unset; the source keeps its fails and time.
grep -qF -- '--lua-desync=circular:fails=2:time=300:retrans=3:nld=2:maxseq=32768:inseq=4096:udp_out=4:udp_in=1:reset ' "${globalRuntime}/config"
# z2k: its generator's pools, detectors and fake TTL; only the general profile learns.
grep -qx 'NFQWS2_TCP_PKT_OUT=20' "${z2kRuntime}/config"
grep -qx 'NFQWS2_UDP_PKT_IN=8' "${z2kRuntime}/config"
grep -qx 'NFQWS2_PORTS_UDP=443,50000-50099,1400,3478-3481,5349,19294-19344' "${z2kRuntime}/config"
# Its Discord profile filters up to 50100, one port past its queue: the queue takes it.
grep -qx 'NFQWS2_PORTS_UDP=443,1400,3478-3481,5349,19294-19344,50000-50100' "${z2kRuntime}/config"
grep -qF -- 'key=rkn_tcp:nld=2:failure_detector=z2k_fail_tls_alert:retrans=3:maxseq=32768:inseq=4096:udp_out=4:udp_in=1:reset' "${z2kRuntime}/config"
grep -qF -- 'failure_detector=z2k_fail_quic_silence' "${z2kRuntime}/config"
grep -qF -- ':fool=z2k_dynamic_ttl' "${z2kRuntime}/config"
@@ -266,6 +403,25 @@ in
grep -qF 'tag: "zapret-cutoff"' ${socksStart zapret2Global}
if grep -qF 'zapret-cutoff' ${socksStart zapret2NoFallback}; then exit 1; fi
# --- directSync of runtime hosts --------------------------------------
# Last before the final rule, and only where direct lists apply.
grep -qF 'tag: "zapret-hosts"' ${socksStart zapret2Global}
grep -qF 'all-proxy | all-bypass) ;;' ${socksStart zapret2Global}
if grep -qF 'zapret-hosts' ${socksStart zapretDiscordYoutubeGlobal}; then exit 1; fi
# Pinned and learned hosts less the excluded ones; IP literals as single addresses.
mkdir -p direct-lists empty-lists
printf 'pinned.example\n# a comment\n\n' >direct-lists/zapret-hosts-user.txt
printf 'Learned.Example\nexcluded.example\n203.0.113.7\n2001:db8::1\npinned.example\n' >direct-lists/zapret-hosts-auto.txt
printf 'excluded.example\n' >direct-lists/zapret-hosts-user-exclude.txt
${directSync} direct-lists direct.json
test "$(cat direct.json)" = '{"version":1,"rules":[{"domain_suffix":["learned.example","pinned.example"]},{"ip_cidr":["2001:db8::1/128","203.0.113.7/32"]}]}'
# Unchanged, the file stays as it was: sing-box reloads on every rename.
inode=$(stat -c %i direct.json)
${directSync} direct-lists direct.json
test "$(stat -c %i direct.json)" = "$inode"
${directSync} empty-lists empty.json
test "$(cat empty.json)" = '{"version":1,"rules":[]}'
# --- per-app instance -------------------------------------------------
# Wrapped apps opted in explicitly, so no hostlist gates them.
grep -qx 'MODE_FILTER=none' "${perAppRuntime}/config"
@@ -337,6 +493,10 @@ in
test "$(sed -n '/^--hostlist-auto=/,$p' z2k.args | grep -c -- '^--new$')" = 0
if sed -n '/^--hostlist-auto=/,$p' z2k.args | grep -q -- '^--lua-desync='; then exit 1; fi
# Extra ports and --debug are options nfqws2 takes.
dry_run ${tunedRuntime} tuned.args
dry_run ${z2kTunedRuntime} z2k-tuned.args >/dev/null
touch "$out"
'';
}
+17
View File
@@ -45,6 +45,13 @@ in
zapret2 = {
domains = [ "pinned.example" ];
excludeDomains = [ "excluded.example" ];
ports = {
extraTcp = [ 8444 ];
extraUdp = [
"27015-27030"
"50000-50100"
];
};
autoHostlist = {
failThreshold = 5;
failTime = 120;
@@ -64,6 +71,16 @@ in
zapret2.strategySource = "z2k";
};
zapret2Z2kTuned = mkZapret2 {
enable = true;
zapret2 = {
strategySource = "z2k";
ports.extraTcp = [ 8444 ];
strategyLog = false;
debug = true;
};
};
zapret2NoFallback = mkZapret2 {
enable = true;
zapret2.cutoff.proxyFallback = false;
+1 -1
View File
@@ -5292,7 +5292,7 @@ def _follow_in_pager(argv, pager):
signal.signal(signal.SIGINT, old)
die(f"proxy-ctl: {argv[0]}: {e.strerror}", 127)
try:
return subprocess.call([pager, "-R", "-S", "-M", "+F"], stdin=source.stdout)
return subprocess.call([pager, "-R", "-M", "+F"], stdin=source.stdout)
finally:
source.stdout.close()
source.terminate()
+23 -3
View File
@@ -1106,6 +1106,10 @@ class ProxySuiteGui(Adw.Application):
self.pending = False
self.generation = 0
self.failed = None # units in failed state at the last load; None before the first
# model.FAILURE_EVENTS failures (unit -> mark): on screen in the window now, and seen there
# before. A seen one stops marking the tray and the status line once the window is left.
self.viewing = {}
self.seen = {}
self.root_read_refused = False # pkexec for a tab read was dismissed: not asked again until Ctrl+E flips
self.timer = None
@@ -1177,6 +1181,8 @@ class ProxySuiteGui(Adw.Application):
def present(self, tab=None):
if self.window is None:
self.window = Window(self)
# Hidden to the tray or switched away from: what it showed has been seen.
self.window.connect("notify::is-active", lambda w, _: w.is_active() or self.leave_window())
self.window.show_tabs(model.available_tabs(self.states) if self.states else ["services"])
if tab and tab in self.window.pages:
self.window.stack.set_visible_child_name(tab)
@@ -1191,6 +1197,12 @@ class ProxySuiteGui(Adw.Application):
else:
self.present()
def leave_window(self):
if self.viewing:
self.seen.update(self.viewing)
self.viewing.clear()
self.reload()
def on_tray_available(self, available):
if not available and self.window is None:
# Started hidden, and nothing shows the tray: no way back to the window but this.
@@ -1212,15 +1224,17 @@ class ProxySuiteGui(Adw.Application):
if window:
window.set_busy(True)
tab = window.pages[window.stack.get_visible_child_name()].tab if window and window.stack.get_visible_child_name() else None
threading.Thread(target=self.load, args=(self.generation, tab, self.elevated()), daemon=True).start()
threading.Thread(target=self.load, args=(self.generation, tab, self.elevated(), dict(self.seen)), daemon=True).start()
def load(self, generation, tab, elevated):
def load(self, generation, tab, elevated, seen):
model.new_load()
states = model._read_states()
marks = model._safe(model.failure_marks, states, fallback={})
states = model.unseen(states, marks, seen)
snap = model.snapshot(states) if states else None
outbound = model._safe(ctl._status_outbound, fallback="") if snap and snap["proxy"]["active"] else ""
tray = (model.tray_menu(snap, model.tray_outbounds(snap)), ctl._overall_state(snap), outbound)
result = {"states": states, "snap": snap, "tray": tray}
result = {"states": states, "snap": snap, "tray": tray, "marks": marks}
if tab is not None:
result["visible"] = model.available_tabs(states)
result["status"] = model._safe(model.status_items, states, fallback=[("", "Status unavailable", "bad")])
@@ -1252,6 +1266,12 @@ class ProxySuiteGui(Adw.Application):
stale = not result["states"] and bool(self.states)
if not stale:
self.states = result["states"]
marks = result["marks"]
# A failure that is over, or failed again since, is no longer the one seen.
self.seen = {u: m for u, m in self.seen.items() if marks.get(u) == m}
self.viewing = {u: m for u, m in self.viewing.items() if marks.get(u) == m}
if "tab" in result and self.window and self.window.is_active():
self.viewing.update((u, m) for u, m in marks.items() if u not in self.seen)
snap = result["snap"]
tree, overall, outbound = result["tray"]
if self.tray:
+30 -2
View File
@@ -213,6 +213,30 @@ def _controllable(row):
return row["unit"] in TOGGLES or bool(_awg_profile(row)) or bool(_wl_entry(row))
# Units whose failure is one run's, not something still down: once seen, it stops marking the
# suite failed until a later run fails again.
FAILURE_EVENTS = (ctl.SUBSCRIPTION_UPDATE,)
def failure_marks(states):
"""unit -> when it last failed, for the failed FAILURE_EVENTS: a later failure is a new mark.
Empty where the manager does not say (the supervisor): a run that does not fail ends the mark there."""
units = [u for u in FAILURE_EVENTS if states.get(u) == "failed"]
if not units:
return {}
_, out = ctl.systemctl("show", "--property=Id,InactiveEnterTimestampMonotonic", "--", *units, capture=True, quiet=True)
marks = {}
for unit, block in zip(units, out.strip().split("\n\n"), strict=False):
props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
marks[unit] = props.get("InactiveEnterTimestampMonotonic", "")
return {u: marks.get(u, "") for u in units}
def unseen(states, marks, seen):
"""states with the failures already seen (unit -> mark) read as inactive: nothing counts them as failed."""
return {u: "inactive" if u in marks and seen.get(u) == marks[u] else s for u, s in states.items()}
def service_rows(states):
return [
{"key": u, "unit": u, "name": u.removeprefix("proxy-suite-"), "state": s}
@@ -582,8 +606,8 @@ def _enabled(name):
return lambda _: ctl.env(name) == "1"
def _sub_url(row):
return bool(row["user"]) and bool(ctl.env("INBOUNDS_SUB_BASE_URL"))
def _sub_url(row, user="user"):
return bool(row[user]) and bool(ctl.env("INBOUNDS_SUB_BASE_URL"))
def _add_args(text):
@@ -937,6 +961,10 @@ TABS = [
Action("e", "set its order…", lambda r, t, _: ["inbounds", "users", "order", r["name"], t.strip()], when=_runtime_row, prompt="<order>", offered=_inbounds_runtime),
Action("b", "bind it to a listener…", lambda r, t, _: ["inbounds", "bind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
Action("x", "unbind it from a listener…", lambda r, t, _: ["inbounds", "unbind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
# The user's one subscription, as the inbounds tab has it on each of the user's rows.
Action("s", "subscription URL", lambda r, *_: ["inbounds", "sub", r["name"]], when=ROW, mode="dialog"),
Action("c", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["name"]], when=lambda r: _sub_url(r, "name"), mode="copy"),
Action("Q", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["name"], "--qr"], when=lambda r: _sub_url(r, "name"), mode="dialog"),
Action("i", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
],
),
+22 -2
View File
@@ -72,6 +72,21 @@ class ModelTest(unittest.TestCase):
rows = model.service_rows({"proxy-suite-socks": "active", ctl.SUBSCRIPTION_UPDATE: "inactive"})
self.assertEqual([r["unit"] for r in rows], ["proxy-suite-socks"])
def test_a_seen_failure_event_reads_inactive(self):
sub = ctl.SUBSCRIPTION_UPDATE
states = {"proxy-suite-socks": "failed", sub: "failed"}
with mock.patch.object(ctl, "systemctl", return_value=(0, f"Id={sub}\nInactiveEnterTimestampMonotonic=42\n")) as systemctl:
marks = model.failure_marks(states)
self.assertEqual(marks, {sub: "42"})
self.assertIn(sub, systemctl.call_args.args)
# A long-running unit that failed is still down: only the event is let go.
self.assertEqual(model.unseen(states, marks, {sub: "42"}), {"proxy-suite-socks": "failed", sub: "inactive"})
# Failed again since: a new mark, counted again.
self.assertEqual(model.unseen(states, {sub: "99"}, {sub: "42"}), states)
with mock.patch.object(ctl, "systemctl") as systemctl:
self.assertEqual(model.failure_marks({sub: "inactive"}), {})
systemctl.assert_not_called()
def test_warp_over_amneziawg_toggles_with_warp(self):
tab = model.TABS[0]
row = model.service_rows({"proxy-suite-awg-warp": "inactive"})[0]
@@ -109,7 +124,7 @@ class ModelTest(unittest.TestCase):
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "1", "INBOUNDS_RUNTIME_ENABLED": "0"}):
# Listed from the configuration; nothing to change them with.
self.assertTrue(users.available({}))
self.assertEqual([a.key for a in users.actions if model.offered(a)], ["i"])
self.assertEqual([a.key for a in users.actions if model.offered(a)], ["s", "c", "Q", "i"])
self.assertNotIn("n", [a.key for a in inbounds.actions if model.offered(a)])
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "0"}):
self.assertFalse(users.available({}))
@@ -124,7 +139,12 @@ class ModelTest(unittest.TestCase):
self.assertEqual(actions["n"].argv(None, "carol 7 in ws", {}),
["inbounds", "users", "add", "carol", "--order", "7", "--listener", "in", "--listener", "ws"])
self.assertEqual(actions["n"].argv(None, "carol", {}), ["inbounds", "users", "add", "carol"])
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "x", "i"])
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "x", "s", "i"])
self.assertEqual(actions["s"].argv(bob), ["inbounds", "sub", "bob"])
# A URL to copy or encode only with subscriptions.baseUrl: else it is a file path.
with mock.patch.dict(os.environ, {"INBOUNDS_SUB_BASE_URL": "https://sub.example"}):
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "x", "s", "c", "Q", "i"])
self.assertEqual(actions["Q"].argv(bob), ["inbounds", "sub", "bob", "--qr"])
self.assertEqual(actions["e"].argv(alice, " 9 ", {}), ["inbounds", "users", "order", "alice", "9"])
self.assertEqual(actions["b"].argv(alice, "in", {}), ["inbounds", "bind", "alice", "in"])
actions = {a.key: a for a in inbounds.actions}