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

+12
View File
@@ -122,9 +122,19 @@ let
collapseNamedOutbounds = selectionMode == "first";
clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first";
perAppZapretEnabled = perAppZapretCfg.enable;
zapretCutoffEnabled =
zapretEngine == "zapret2"
&& (zapretCfg.enable || perAppZapretEnabled)
&& zapretCfg.zapret2.cutoff.enable;
# The cut-off networks no whitelisted name fixes go through the proxy outbound.
zapretCutoffProxyFallback =
zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds;
userControlEnabled = userControlCfg.allow != [ ];
constants = {
zapret2StateDir = "/var/lib/proxy-suite/zapret2";
zapret2CutoffDir = "/var/lib/proxy-suite/zapret2/cutoff";
# Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone.
zapret2CutoffProbeCtMark = 33554432; # 0x2000000
# NFQUEUE of the global zapret instance, per engine. Both are the engine's own
# default, which proxy-suite never overrides; the per-app instance opens a
@@ -203,6 +213,8 @@ in
zapretEngine
perAppZapretCfg
perAppZapretEnabled
zapretCutoffEnabled
zapretCutoffProxyFallback
userControlCfg
userControlEnabled
sshProxyCfg
+25
View File
@@ -122,5 +122,30 @@ in
description = "Log why hosts are or are not learned to zapret-hosts-auto-debug.log.";
};
};
cutoff = {
enable = mkEnableOption "the 16 KB cutoff probe" // {
default = true;
description = ''
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
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.
'';
};
proxyFallback = mkOption {
type = types.bool;
default = true;
description = ''
Route the cut-off networks no name fixes through the proxy outbound. Needs the sing-box
backend with an outbound and a route mode other than all-bypass, and only applies to
traffic the backend sees by address (TUN, TProxy, per-app routing, clients that dial IPs);
explicit direct rules still win.
'';
};
};
};
}
+4
View File
@@ -37,6 +37,8 @@ let
perAppRoutingTproxy
perAppZapretCfg
zapretEngine
zapretCutoffEnabled
zapretCutoffProxyFallback
userControlCfg
selectionMode
builtinTags
@@ -98,6 +100,7 @@ let
selectionMode
collapseNamedOutbounds
constants
zapretCutoffProxyFallback
;
inherit
jq
@@ -163,6 +166,7 @@ let
perAppRoutingTproxy
perAppZapretCfg
zapretEngine
zapretCutoffEnabled
constants
selectionMode
userControlCfg
+2
View File
@@ -8,6 +8,7 @@
perAppRoutingTproxy,
perAppZapretCfg,
zapretEngine,
zapretCutoffEnabled,
constants,
selectionMode,
userControlCfg,
@@ -44,6 +45,7 @@
perAppRoutingZapretEnabled = if perAppZapretCfg.enable then "1" else "0";
zapretAutoEnabled = if zapretEngine == "zapret2" then "1" else "0";
zapretStateDir = constants.zapret2StateDir;
zapretCutoffEnabled = if zapretCutoffEnabled then "1" else "0";
priorityOutboundFile = constants.priorityOutboundFile;
outboundInventoryFile = constants.outboundInventoryFile;
runtimeOutboundsDir = constants.runtimeOutboundsDir;
+2
View File
@@ -14,6 +14,7 @@
selectionMode,
collapseNamedOutbounds,
constants,
zapretCutoffProxyFallback,
jq,
python3,
singBox,
@@ -159,6 +160,7 @@ let
hybridEnabled
pureXrayEnabled
constants
zapretCutoffProxyFallback
jq
singBox
xray
@@ -10,6 +10,7 @@
hybridEnabled,
pureXrayEnabled,
constants,
zapretCutoffProxyFallback,
jq,
singBox,
xray,
@@ -143,6 +144,7 @@ let
xraySidecarBasePort ? xraySidecarBasePorts.socks,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
enableAutoProxy ? false,
enableZapretCutoff ? false,
}:
pkgs.writeShellScript name ''
set -euo pipefail
@@ -234,6 +236,20 @@ let
fi
''}
${lib.optionalString enableZapretCutoff ''
# zapret2's cutoff probe lists the prefixes of cut-off networks no whitelisted
# name gets through; the proxy carries those. sing-box refuses a missing
# rule-set path and reloads the file when the probe renames a new one in.
if [ "$ROUTE_MODE" != all-bypass ]; then
CUTOFF_RULE_SET=${lib.escapeShellArg "${constants.zapret2CutoffDir}/proxy.json"}
install -d -m 0755 "$(dirname "$CUTOFF_RULE_SET")"
[ -s "$CUTOFF_RULE_SET" ] || echo '{"version":1,"rules":[]}' > "$CUTOFF_RULE_SET"
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$CUTOFF_RULE_SET" \
'. + [{type: "local", format: "source", tag: "zapret-cutoff", path: $p}]' <<< "$AUTOPROXY_RULE_SETS_JSON")
AUTOPROXY_RULES_JSON=$(${jq} -c '. + [{rule_set: ["zapret-cutoff"], outbound: "proxy"}]' <<< "$AUTOPROXY_RULES_JSON")
fi
''}
${jq} \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson probe_inbounds "$PROBE_INBOUNDS_JSON" \
@@ -309,6 +325,7 @@ let
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
# Only the socks unit: relayed traffic reaches it, and the prober needs one home.
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
enableZapretCutoff = zapretCutoffProxyFallback && !pureXrayEnabled;
};
startTun = mkStartScript {
+16 -1
View File
@@ -15,6 +15,7 @@ let
zapretCfg = cfg.zapret;
perAppZapretCfg = cfg.perAppRouting.zapret;
cutoffCfg = zapretCfg.zapret2.cutoff;
inherit (import ./derived.nix { inherit lib cfg; }) constants;
awgServiceNames = map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames cfg.amneziaWg.profiles
@@ -46,10 +47,11 @@ let
let
exemptCidrs = lib.optionals zapretCfg.cidrExemption.enable zapretCfg.cidrExemption.cidrs;
in
if perAppZapretCfg.enable || tunInterfaces != [ ] || exemptCidrs != [ ] then
if perAppZapretCfg.enable || tunInterfaces != [ ] || exemptCidrs != [ ] || cutoffCfg.enable then
runtime.mkCustomScript {
inherit tunInterfaces exemptCidrs;
excludeMark = if perAppZapretCfg.enable then perAppZapretCfg.filterMark else null;
probeCtMark = if cutoffCfg.enable then constants.zapret2CutoffProbeCtMark else null;
}
else
null;
@@ -75,6 +77,16 @@ let
touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile}
'';
cutoff = import ./zapret2/cutoff.nix {
inherit
lib
pkgs
cfg
zapret2Sources
nft
;
};
perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-per-app-zapret2-mark-up" ''
set -euo pipefail
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
@@ -89,6 +101,9 @@ in
{
environment.systemPackages = lib.mkBefore [ runtime.package ];
systemd.services.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.service;
systemd.timers.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.timer;
systemd.services.zapret-discord-youtube = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret2 DPI bypass";
after = [ "network-online.target" ];
+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/"