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

@@ -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