feat: z2k 16kb probe

This commit is contained in:
fufsob committed 2026-09-13 20:15:20 +00:00
1 parent 441be87b61
commit 09e9945351
18 files changed
+436 -5

No files matched your search

+169
View File
@@ -0,0 +1,169 @@
# 16 KB cutoff: some lines let TLS to certain hosting networks handshake and then
# kill the connection at 12-34 KB, which no strategy rotation fixes. z2k-detect
# probes which networks (AS) this line cuts and finds a whitelisted name per network
# that z2k-tcp16.lua puts into a fake ClientHello; the networks no name fixes go to
# a sing-box rule-set that sends them through the proxy.
{
lib,
pkgs,
cfg,
zapret2Sources,
nft,
}:
let
inherit (import ../derived.nix { inherit lib cfg; }) constants;
z2k = zapret2Sources.z2k;
lists = "${z2k}/files/lists";
dir = constants.zapret2CutoffDir;
unit = "proxy-suite-zapret2-cutoff";
table = "proxy_suite_cutoff_probe";
z2kDetect = pkgs.buildGoModule {
pname = "z2k-detect";
version = "0-unstable-${z2k.shortRev or "local"}";
src = "${z2k}/z2k-detect";
vendorHash = "sha256-9Qv6O6/8MP9N44GPSDULEV/NcrHdEC3YZmIQmpaa1nE=";
subPackages = [ "cmd/z2k-detect" ];
# Its tests open raw sockets and dial out.
doCheck = false;
meta.mainProgram = "z2k-detect";
};
# $1 asn.txt, $2 sni.txt, $3 AS-to-prefix map; prints a sing-box source rule-set
# with the prefixes of every cut-off network that no whitelisted name fixes.
proxyRules = pkgs.writeShellScript "proxy-suite-zapret2-cutoff-rules" ''
set -euo pipefail
${pkgs.gawk}/bin/awk -F'\t' '
FILENAME == ARGV[1] { if ($1 ~ /^[0-9]+$/) cut[$1] = 1; next }
FILENAME == ARGV[2] { if ($1 ~ /^[0-9]+$/) named[$1] = 1; next }
($1 in cut) && !($1 in named) { print $2 }
' "$1" "$2" "$3" \
| ${pkgs.jq}/bin/jq -R -s -c '
split("\n") | map(select(. != ""))
| {version: 1, rules: (if length > 0 then [{ip_cidr: .}] else [] end)}'
'';
probe = pkgs.writeShellScript unit ''
set -euo pipefail
export PATH=${
lib.makeBinPath [
pkgs.coreutils
pkgs.curl
pkgs.diffutils
pkgs.gnugrep
pkgs.jq
pkgs.systemd
z2kDetect
]
}
cd ${lib.escapeShellArg dir}
touch asn.txt sni.txt
force=0
if [ -e force ]; then
force=1
rm -f force
fi
now=$(date +%s)
# The name map belongs to this line: probe again when its network changes, else
# once a day. No answer (offline, captive portal) is no reason to probe.
info=$(curl -sS --max-time 10 https://ipinfo.io/json 2>/dev/null || true)
egress=$(jq -r '((.org // "") | split(" ")[0]) as $as
| if ($as | test("^AS[0-9]+$")) then $as else (.ip // "") end' <<<"$info" 2>/dev/null || true)
if [ -z "$egress" ]; then
echo "no answer about this line's address; not probing"
exit 0
fi
if [ "$force" = 0 ] && [ "$egress" = "$(cat egress 2>/dev/null || true)" ] &&
[ $((now - $(cat ts 2>/dev/null || echo 0))) -lt 86400 ]; then
exit 0
fi
echo "probing the line from $egress"
rc=0
z2k-detect tcp16 -targets ${lists}/tcp16_targets.txt -parallel 50 -asn-out asn.new || rc=$?
case "$rc" in
1)
rc=0
z2k-detect tcp16 -targets ${lists}/tcp16_targets.txt -scan ${lists}/sni_wl_candidates.txt \
-per-asn -batch 5 -parallel 50 -sni-out sni.new || rc=$?
# 2: no network took any name; the list of cut-off networks still stands.
if [ "$rc" != 0 ] && [ "$rc" != 2 ]; then
rm -f asn.new sni.new
echo "name search failed ($rc); keeping the previous maps"
exit 0
fi
[ -e sni.new ] || : >sni.new
;;
0)
: >asn.new
: >sni.new
;;
*)
rm -f asn.new
echo "the probe did not run ($rc); keeping the previous maps"
exit 0
;;
esac
changed=0
{ cmp -s asn.new asn.txt && cmp -s sni.new sni.txt; } || changed=1
mv -f asn.new asn.txt
mv -f sni.new sni.txt
${proxyRules} asn.txt sni.txt ${lists}/tcp16_nets.txt >proxy.json.tmp
mv -f proxy.json.tmp proxy.json
printf '%s\n' "$egress" >egress
printf '%s\n' "$now" >ts
echo "cut-off networks: $(grep -c '^[0-9]' asn.txt || true), with a name: $(grep -c '^[0-9]' sni.txt || true)"
# nfqws2 reads the maps once; learned strategies survive the restart.
if [ "$changed" = 1 ]; then
systemctl try-restart zapret-discord-youtube.service proxy-suite-per-app-zapret.service
fi
'';
# The probe measures this line, so its traffic leaves directly: proxyMark keeps it
# out of TUN/TProxy like the backend's own, and the conntrack bit keeps zapret2 from
# touching or learning it.
exempt = pkgs.writeShellScript "${unit}-exempt" ''
set -euo pipefail
${nft} delete table inet ${table} 2>/dev/null || true
${nft} -f - <<EOF
table inet ${table} {
chain output {
type route hook output priority mangle - 1; policy accept;
socket cgroupv2 level 2 "system.slice/${unit}.service" meta mark set ${toString cfg.proxy.tproxy.proxyMark} ct mark set ct mark or ${toString constants.zapret2CutoffProbeCtMark}
}
}
EOF
'';
in
{
inherit z2kDetect proxyRules;
service = {
description = "proxy-suite - probe this line for the 16 KB cutoff and find a name per network";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "oneshot";
StateDirectory = "proxy-suite/zapret2/cutoff";
ExecStartPre = "${exempt}";
ExecStart = "${probe}";
ExecStopPost = "-${nft} delete table inet ${table}";
};
};
timer = {
description = "proxy-suite 16 KB cutoff probe schedule";
wantedBy = [ "timers.target" ];
timerConfig = {
# Cheap unless the line changed or a day passed. Not OnBootSec: see autoproxy.nix.
OnActiveSec = "5m";
OnUnitActiveSec = "10m";
RandomizedDelaySec = "1m";
Persistent = true;
};
};
}
+19 -2
View File
@@ -93,10 +93,15 @@ let
else
pkgs.writeText "proxy-suite-zapret2-blobs" (lib.concatStringsSep " " source.blobArgs);
# The state layer wraps circular, so it loads after the source's Lua.
# 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.
optPrefix = lib.concatStringsSep " " (
map (file: "--lua-init=@${file}") (
source.luaInit ++ [ "${zapret2Sources.z2k}/files/lua/z2k-state-persist.lua" ]
source.luaInit
++ map (name: "${zapret2Sources.z2k}/files/lua/${name}.lua") [
"z2k-tcp16"
"z2k-state-persist"
]
)
++ lib.mapAttrsToList (name: file: "--blob=${name}:@${blobPath file}") zapret2Cfg.blobs
);
@@ -208,6 +213,7 @@ let
tunInterfaces ? [ ],
excludeMark ? null,
exemptCidrs ? [ ],
probeCtMark ? null,
}:
let
chains = [
@@ -241,6 +247,10 @@ let
lib.optional (excludeMark != null) (
mkRule chain.name "mark and ${toHex excludeMark} != 0" "proxy-suite per-app-zapret bypass"
)
# Replies carry no socket, so the cutoff probe is matched by conntrack.
++ lib.optional (probeCtMark != null) (
mkRule chain.name "ct mark and ${toHex probeCtMark} != 0" "proxy-suite cutoff probe bypass"
)
++ map (
interface: mkRule chain.name "${chain.direction} '\"${interface}\"'" "proxy-suite TUN bypass"
) tunInterfaces
@@ -293,6 +303,13 @@ let
# Read by z2k-state-persist.lua inside nfqws2, which inherits the unit's environment.
"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 [
"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"
];
in
{
+16 -1
View File
@@ -45,6 +45,17 @@ 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:
@@ -52,7 +63,7 @@ let
profiles = [
(args "NFQWS_ARGS_UDP")
"${args "NFQWS_ARGS_QUIC"} <HOSTLIST_NOAUTO> ${lists}"
"${args "NFQWS_ARGS"} <HOSTLIST> ${lists}"
"${withSniPick (args "NFQWS_ARGS")} <HOSTLIST> ${lists}"
];
blobArgs = map (replaceStrings [ "@/opt/etc/nfqws2/" ] [ "@${src}/etc/nfqws2/" ]) (
filter (hasPrefix "--blob=") (words (quoted "NFQWS_BASE_ARGS"))
@@ -116,6 +127,10 @@ let
cp "$root/extra_strats/TCP/RKN/Discord.txt" "$root/extra_strats/TCP_Discord.txt"
cp ${src}/files/lists/cf_extra_check_ips.txt "$root/lists/"
: >"$root/lists/discovered-domains.txt"
# Its cutoff name step is emitted only on lines its probe flagged; ours is
# a no-op until the cutoff probe writes maps, so emit it unconditionally.
mkdir -p "$root/state"
echo 1 >"$root/state/tcp16.flag"
# The generator wires its detectors only when their Lua files exist.
ln -s ${src}/files/lua/*.lua "$root/lua/"