fix: zapret2 improvements

This commit is contained in:
FUFSoB committed 2026-10-04 19:43:32 +05:00
1 parent 2452d6fbe1
commit 017a947a18
24 files changed
+1350 -99

No files matched your search

@@ -21,15 +21,32 @@ last=$(cat ts 2>/dev/null || true)
[[ $last =~ ^[0-9]+$ ]] || last=0
# 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"
# once a day. Two services name the network, and they must agree: ipinfo.io alone now
# and then named Cloudflare's for this line's, and each flip cost a full probe. One
# answer alone counts only for the network already known (or when none is yet); no
# answer at all (offline, captive portal) is no reason to probe.
asn() {
curl -sS --max-time 10 "$1" 2>/dev/null | jq -r "$2"' | select(test("^AS[0-9]+$"))' 2>/dev/null || true
}
known=$(cat egress 2>/dev/null || true)
ipinfo=$(asn https://ipinfo.io/json '(.org // "") | split(" ")[0]')
ifconfig=$(asn https://ifconfig.co/json '.asn // ""')
if [ -n "$ipinfo" ] && [ -n "$ifconfig" ] && [ "$ipinfo" != "$ifconfig" ]; then
echo "ipinfo.io says $ipinfo, ifconfig.co says $ifconfig; keeping the last probe"
exit 0
fi
if [ "$force" = 0 ] && [ "$egress" = "$(cat egress 2>/dev/null || true)" ] &&
egress=${ipinfo:-$ifconfig}
if [ -z "$egress" ]; then
echo "no answer about this line's network; not probing"
exit 0
fi
if [ -z "$ipinfo" ] || [ -z "$ifconfig" ]; then
if [ -n "$known" ] && [ "$egress" != "$known" ]; then
echo "only one service answered, with $egress for this line's $known; keeping the last probe"
exit 0
fi
fi
if [ "$force" = 0 ] && [ "$egress" = "$known" ] &&
[ $((now - last)) -lt 86400 ]; then
exit 0
fi
+398
View File
@@ -0,0 +1,398 @@
-- Failures nfqws2 and z2k do not see, and the verdicts proxy-suite routes by.
--
-- Rotation: the TLS detectors count retransmissions, resets and alerts. A ClientHello
-- DPI swallows whole can leave the client nothing to retransmit (the server only
-- acknowledges the handshake, over and over), and circular stays on a strategy that
-- never gets a reply. A ClientHello with no answer within NOREPLY_MS now counts too.
--
-- Learning (ps_learn, in the last TLS profile in place of nfqws2's own autohostlist):
-- - a success no longer wipes the failures before it, so a site DPI blocks only some
-- of the time (some connections pass, the rest are dropped) is still learned;
-- - a download that stops mid TLS record and stays stopped (the 16 KB cutoff) is a
-- failure, where nfqws2 took anything past 4 KB received for a working site;
-- - so is a ClientHello with no answer, retransmitted `retrans` times (the client gets
-- a reset then, as nfqws2 gave it, so it fails fast) or met by an early reset.
-- A site is learned at `fails` failures within `time` seconds: appended to the auto
-- hostlist, which nfqws2 reloads, so the profiles for blocked sites take it over.
--
-- Verdicts, appended to $PROXY_SUITE_ZAPRET2_VERDICTS as
-- "kind<TAB>name<TAB>proto<TAB>note<TAB>time" (the last line per name and proto wins), for
-- direct-sync.template.sh and proxy-ctl:
-- - works <site> tcp|udp: a strategy got through; only then does a learned site go direct;
-- - stalls <host> cutoff: learned from transfers cut short (the 16 KB cutoff); such a site
-- keeps the proxy's route whatever "works" says, as success is judged on the first 4 KB;
-- - unfixable <site> tcp|udp: every strategy failed in turn; the proxy carries it;
-- - blocked <ip> ip: connections to it go unanswered (blocked by address, ps_syn), and
-- reachable <ip> ip once one is answered again;
-- - retry <name> <proto>: proxy-ctl's, to give zapret2 another try.
local NOREPLY_MS = 4000
local STALL_MS = 6000
local SYN_MS = 3500
local function say(text)
io.stderr:write("zapret2: ", text, "\n")
end
-- --- verdicts --------------------------------------------------------------------------
local VERDICTS = os.getenv("PROXY_SUITE_ZAPRET2_VERDICTS")
local status = {} -- "name proto" -> its last kind, so each change is written once
-- The last verdicts, as the file has them now: proxy-ctl's retries land there too.
local function reload()
local f = VERDICTS and io.open(VERDICTS, "r")
if not f then return end
status = {}
for line in f:lines() do
local kind, name, proto = line:match("^(%w+)\t([^\t]+)\t([^\t]*)")
if kind then status[name .. " " .. proto] = kind end
end
f:close()
end
reload()
local function verdict(kind, name, proto, note)
local key = name .. " " .. proto
if not VERDICTS or status[key] == kind then return end
reload()
if status[key] == kind then return end
status[key] = kind
local f = io.open(VERDICTS, "a")
if not f then return end
f:write(kind, "\t", name, "\t", proto, "\t", note or "", "\t", os.time(), "\n")
f:close()
end
-- "<circular key> <site>" of a host record: autostate maps them to it.
local function ident(hrec)
for askey, hosts in pairs(autostate or {}) do
for host, rec in pairs(hosts) do
if rec == hrec then return askey, host end
end
end
end
local function udp_key(askey)
return askey:match("quic") or askey:match("udp")
end
-- --- rotation ----------------------------------------------------------------------------
-- Every strategy failed in turn, none got through: the site is unfixable here. Its
-- rotation stops (it would only cycle on), and the proxy carries it from now on.
local count = automate_failure_counter
function automate_failure_counter(hrec, crec, fails, maxtime)
local reached = count(hrec, crec, fails, maxtime)
if reached and hrec.ctstrategy then
hrec.ps_cycle = (hrec.ps_cycle or 0) + 1
if hrec.ps_cycle >= hrec.ctstrategy and not hrec.final then
local askey, host = ident(hrec)
if host then
hrec.final = hrec.nstrategy or 1
local proto = udp_key(askey) and "udp" or "tcp"
say(askey .. " " .. host .. ": no strategy of " .. hrec.ctstrategy .. " gets through, the proxy carries its " .. proto)
verdict("unfixable", host, proto, askey)
end
end
end
return reached
end
-- A connection that got through: its site works with zapret2.
local check = automate_failure_check
function automate_failure_check(desync, hrec, crec)
local judged = crec.nocheck
local reached = check(desync, hrec, crec)
if not judged and crec.nocheck and not crec.failure and not reached then
hrec.ps_cycle = 0
local hkf = desync.arg.hostkey and _G[desync.arg.hostkey] or standard_hostkey
local ok, host = pcall(hkf, desync)
if ok and host and desync.track and not desync.track.hostname_is_ip then
verdict("works", host, desync.dis and desync.dis.udp and "udp" or "tcp", desync.arg.key)
end
end
return reached
end
function ps_noreply_timer(_, data)
local crec, hrec = data.crec, data.hrec
-- Answered, already judged by the detector in place, or given up on by the client
-- itself (a cancelled page, the loser of a connection race): no verdict on the site.
if crec.ps_answered or crec.ps_closed or crec.nocheck or crec.failure then return end
crec.nocheck = true
if not automate_failure_counter(hrec, crec, tonumber(data.fails) or 3, tonumber(data.maxtime) or 60) then return end
-- circular's own formula, as z2k's QUIC silence timer does it outside circular.
if not hrec.ctstrategy or hrec.ctstrategy < 1 or (hrec.final and hrec.final == hrec.nstrategy) then return end
hrec.nstrategy = ((hrec.nstrategy or 1) % hrec.ctstrategy) + 1
end
-- On top of a TCP failure detector: z2k's TLS one, and nfqws2's standard one (the
-- nfqws2-keenetic strategies). Armed once per connection, whichever runs first.
local function noreply(detector)
return function(desync, crec)
local dis = desync.dis
if crec and dis and dis.tcp and desync.track then
if not desync.outgoing then
if #(dis.payload or "") > 0 then crec.ps_answered = true end
elseif bitand(dis.tcp.th_flags or 0, TH_RST + TH_FIN) ~= 0 then
crec.ps_closed = true
elseif not crec.ps_armed and desync.l7payload == "tls_client_hello" then
crec.ps_armed = true
local hrec = automate_host_record(desync)
if hrec then
timer_set("psnr_" .. dis_timer_name(dis), ps_noreply_timer, NOREPLY_MS, true, {
crec = crec,
hrec = hrec,
fails = desync.arg.fails,
maxtime = desync.arg.time,
})
end
end
end
return detector(desync, crec)
end
end
if type(z2k_fail_tls_alert) == "function" then z2k_fail_tls_alert = noreply(z2k_fail_tls_alert) end
if type(standard_failure_detector) == "function" then standard_failure_detector = noreply(standard_failure_detector) end
-- --- learning ----------------------------------------------------------------------------
local failures, tracked = {}, 0 -- host -> failure times within the window
local learned = {}
local function lines(path)
local out = {}
local f = path and io.open(path, "r")
if not f then return out end
for line in f:lines() do
line = line:gsub("^%s+", ""):gsub("%s+$", ""):lower()
if line ~= "" and line:sub(1, 1) ~= "#" then out[#out + 1] = line:gsub("^%^", "") end
end
f:close()
return out
end
-- A hostlist entry covers the name and its subdomains.
local function covered(host, entries)
for _, e in ipairs(entries) do
if host == e or host:sub(-(#e + 1)) == "." .. e then return true end
end
return false
end
local function excluded(host, arg)
for path in (arg.exclude or ""):gmatch("[^,]+") do
if covered(host, lines(path)) then return true end
end
local domains = {}
for d in (arg.exclude_domains or ""):gmatch("[^,]+") do domains[#domains + 1] = d:lower() end
return covered(host, domains)
end
local stalled = {} -- host -> a transfer of it was cut short, within the window
local function learn(host, arg, n)
learned[host] = true
if stalled[host] then verdict("stalls", host, "cutoff", "learned from transfers cut short") end
if covered(host, lines(arg.auto)) then return end
local f = io.open(arg.auto, "a")
if not f then
say("cannot learn " .. host .. ": " .. arg.auto .. " is not writable")
return
end
f:write(host, "\n")
f:close()
say("learned " .. host .. " as blocked, after " .. n .. " failures")
end
-- Failure times of `key` within the window, with one more now.
local function tally(key, window)
local now, kept = os.time(), {}
for _, t in ipairs(failures[key] or {}) do
if now - t <= window then kept[#kept + 1] = t end
end
kept[#kept + 1] = now
if not failures[key] then
tracked = tracked + 1
if tracked > 4096 then failures, tracked = {}, 1 end
end
failures[key] = kept
return #kept
end
local function failure(st, arg, why, stall)
if st.counted then return end
st.counted = true
local host = st.host
if learned[host] or excluded(host, arg) then return end
if stall then stalled[host] = true end
local n, need = tally(host, tonumber(arg.time) or 300), tonumber(arg.fails) or 3
if arg.log then say(host .. ": " .. why .. " (" .. n .. "/" .. need .. " to learn)") end
if n >= need then learn(host, arg, n) end
end
-- The server's bytes in order, read as TLS records: a stall between records is a site
-- that said all it had, one inside a record is a transfer cut short.
local function feed(st, data)
local i, n = 1, #data
while i <= n and not st.notls do
if st.need > 0 then
local take = math.min(st.need, n - i + 1)
st.need, i = st.need - take, i + take
else
local want = 5 - #st.hdr
st.hdr = st.hdr .. data:sub(i, i + want - 1)
i = i + want
if #st.hdr == 5 then
local kind = st.hdr:byte(1)
if kind < 20 or kind > 24 then
st.notls = true
else
st.need, st.hdr = st.hdr:byte(4) * 256 + st.hdr:byte(5), ""
end
end
end
end
end
-- nfqws2's own fast fail: a reset to the client retransmitting into silence, so it
-- gives up (and tries again) instead of waiting out its timeouts.
local function reset_client(desync)
local dis = deepcopy(desync.dis)
dis.payload = nil
dis_reverse(dis)
dis.tcp.th_flags = TH_RST
dis.tcp.th_win = desync.track and desync.track.pos.reverse.tcp.winsize or 64
dis.tcp.options = nil
if dis.ip6 then
dis.ip6.ip6_flow = (desync.track and desync.track.pos.reverse.ip6_flow) and desync.track.pos.reverse.ip6_flow or 0x60000000
end
rawsend_dissect(dis, { ifout = desync.ifin })
end
function ps_learn_noreply(_, data)
-- done: the client gave up first, or a failure was counted already.
if not data.st.answered and not data.st.done then failure(data.st, data.arg, "no reply to its ClientHello") end
end
function ps_learn_stall(_, data)
local st = data.st
-- Past the NFQUEUE window nothing more is seen: no telling a stall from the rest.
if st.done or st.notls or st.inpk >= (tonumber(data.arg.win) or 15) then return end
if st.need > 0 or #st.hdr > 0 or next(st.pending) then
failure(st, data.arg, "transfer stalled after " .. math.floor((st.next - 1) / 1024) .. " KB", true)
end
end
function ps_learn(_, desync)
local track, dis = desync.track, desync.dis
if not (track and dis and dis.tcp) or not track.hostname or track.hostname_is_ip then return end
local st = track.lua_state.ps_learn
if not st then
st = { host = track.hostname:lower(), next = 1, need = 0, hdr = "", pending = {}, inpk = 0, retrans = 0 }
track.lua_state.ps_learn = st
end
if st.done then return end
local flags = dis.tcp.th_flags
local payload = dis.payload or ""
if desync.outgoing then
if bitand(flags, TH_RST + TH_FIN) ~= 0 then
st.done = true
elseif not st.name and desync.l7payload == "tls_client_hello" then
st.name = dis_timer_name(dis)
timer_set("psln_" .. st.name, ps_learn_noreply, NOREPLY_MS, true, { st = st, arg = desync.arg })
elseif st.name and not st.answered and #payload > 0 and is_retransmission(desync) then
st.retrans = st.retrans + 1
if st.retrans >= (tonumber(desync.arg.retrans) or 3) then
failure(st, desync.arg, "ClientHello retransmitted " .. st.retrans .. " times")
st.done = true
reset_client(desync)
end
end
return
end
st.inpk = pos_get(desync, "n") or (st.inpk + 1)
if bitand(flags, TH_RST) ~= 0 then
if (st.next - 1) <= (tonumber(desync.arg.inseq) or 4096) then failure(st, desync.arg, "reset by the network") end
st.done = true
return
end
if #payload > 0 then
st.answered = true
local s = pos_get(desync, "s")
if s == st.next then
feed(st, payload)
st.next = s + #payload
while st.pending[st.next] do
local p = st.pending[st.next]
st.pending[st.next] = nil
feed(st, p)
st.next = st.next + #p
end
elseif s > st.next then
st.pending[s] = payload
end
if st.name then
-- Replacing the timer restarts its countdown: it fires once the server goes quiet.
timer_set("psls_" .. st.name, ps_learn_stall, STALL_MS, true, { st = st, arg = desync.arg })
end
end
if bitand(flags, TH_FIN) ~= 0 then st.done = true end
end
-- --- addresses blocked outright ------------------------------------------------------------
-- No strategy helps where the connection itself goes unanswered: the address is blocked,
-- not the name. ps_syn, in the last profile, which every new connection meets before its
-- first data tells nfqws2 what it is, times each one; `fails` unanswered within `time`
-- seconds make it a verdict, and the proxy carries the address. One answer clears it.
-- Addresses that are never the censor's: private, loopback, link-local, CGNAT, ULA.
local function local_address(ip)
local a, b = ip:match("^(%d+)%.(%d+)%.")
if a then
a, b = tonumber(a), tonumber(b)
return a == 10 or a == 127 or a == 0 or (a == 172 and b >= 16 and b <= 31) or (a == 192 and b == 168)
or (a == 169 and b == 254) or (a == 100 and b >= 64 and b <= 127) or a >= 224
end
local lower = ip:lower()
return lower == "::1" or lower:match("^f[cd]") ~= nil or lower:match("^fe[89ab]") ~= nil
end
function ps_syn_timer(_, data)
local st = data.st
if st.answered or st.closed then return end
local n, need = tally("ip " .. st.ip, tonumber(data.arg.time) or 300), tonumber(data.arg.fails) or 3
if data.arg.log then say(st.ip .. ": connection unanswered (" .. n .. "/" .. need .. ")") end
if n >= need and status[st.ip .. " ip"] ~= "blocked" then
say(st.ip .. " does not answer connections: blocked by address, the proxy carries it")
verdict("blocked", st.ip, "ip", "no answer to " .. n .. " connections")
end
end
function ps_syn(_, desync)
local track, dis = desync.track, desync.dis
if not (track and dis and dis.tcp) then return end
local flags = dis.tcp.th_flags
local st = track.lua_state.ps_syn
if desync.outgoing then
if not st and bitand(flags, TH_SYN) ~= 0 and bitand(flags, TH_ACK) == 0 then
local ip = ntop(dis_ipdst(dis))
if not ip or local_address(ip) then return end
st = { ip = ip }
track.lua_state.ps_syn = st
timer_set("pssy_" .. dis_timer_name(dis), ps_syn_timer, SYN_MS, true, { st = st, arg = desync.arg })
elseif st and bitand(flags, TH_RST + TH_FIN) ~= 0 then
st.closed = true
end
elseif st and bitand(flags, TH_SYN) ~= 0 and bitand(flags, TH_ACK) ~= 0 then
st.answered = true
failures["ip " .. st.ip] = nil
if status[st.ip .. " ip"] == "blocked" then
say(st.ip .. " answers again: zapret2 has it back")
verdict("reachable", st.ip, "ip")
end
end
end
+14 -9
View File
@@ -1,6 +1,8 @@
# 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.
# The proxy's two rule-sets from zapret2's runtime state (direct-sync.template.sh):
# direct.json, the hosts zapret2 pins (`proxy-ctl zapret auto add`) and learns and can
# fix, sent direct so zapret2 sees their traffic (directSync); proxy.json, what it cannot
# fix, for the proxy to carry (zapret2.proxyFallback). Rebuilt whenever a host list or a
# verdict changes; sing-box reloads them on the rename.
{
lib,
pkgs,
@@ -11,7 +13,7 @@ let
fillTemplate = import ../lib/fill-template.nix;
inherit (import ../derived.nix { inherit lib cfg; }) constants;
stateDir = constants.zapret2StateDir;
ruleSet = "${constants.zapret2DirectDir}/direct.json";
outDir = constants.zapret2DirectDir;
sync = pkgs.writeShellScript "proxy-suite-zapret2" (
fillTemplate ./direct-sync.template.sh {
@@ -24,17 +26,19 @@ let
);
in
{
inherit sync ruleSet;
inherit sync;
directRuleSet = "${outDir}/direct.json";
proxyRuleSet = "${outDir}/proxy.json";
service = {
description = "proxy-suite - send the hosts zapret2 pins and learns direct in the proxy";
description = "proxy-suite - route by what zapret2 can and cannot fix";
# 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
ExecStart = "${sync} ${lib.escapeShellArg stateDir} ${lib.escapeShellArg outDir}";
# Root's alone, like the cutoff's: it decides what 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";
@@ -43,12 +47,13 @@ in
};
path = {
description = "proxy-suite - watch zapret2's host lists for directSync";
description = "proxy-suite - watch zapret2's host lists and verdicts";
wantedBy = [ "paths.target" ];
pathConfig.PathChanged = map (name: "${stateDir}/${name}") [
"zapret-hosts-user.txt"
"zapret-hosts-auto.txt"
"zapret-hosts-user-exclude.txt"
"verdicts.tsv"
];
};
}
@@ -1,6 +1,13 @@
# $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.
# $1: zapret2's state directory, $2: the directory to write the two rule-sets to.
# direct.json: the hosts zapret2 handles, so the proxy sends them direct and zapret2 sees
# them: the pinned ones, and the learned ones once a strategy got through for them
# (detect.lua's "works"), unless learned from transfers cut short ("stalls"); a learned
# site zapret2 cannot fix keeps the proxy's route.
# proxy.json: what zapret2 cannot fix, for the proxy to carry: sites every strategy failed
# for ("unfixable": all of a site's TCP, or only its QUIC), and addresses that leave
# connections unanswered ("blocked").
# The last verdict per name and protocol wins ("retry", "reachable" and "works" clear one).
# Rewritten only when they change: sing-box reloads them on every rename.
set -euo pipefail
export PATH=@path@
dir=$1
@@ -14,23 +21,60 @@ lists() {
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"
write() {
if cmp -s "$1.tmp" "$1"; then
rm "$1.tmp"
else
chmod 644 "$1.tmp"
mv "$1.tmp" "$1"
fi
}
if cmp -s "$out.tmp" "$out"; then
rm "$out.tmp"
else
chmod 644 "$out.tmp"
mv "$out.tmp" "$out"
fi
# nfqws hostlists: one host per line, "#" comments, "^" for the name alone.
hosts='def hosts: split("\n") | map(gsub("^\\s+|\\s+$"; "") | ascii_downcase | ltrimstr("^"))
| map(select(. != "" and (startswith("#") | not)));
def ip: test("^[0-9.]+$|:");
def cidr: map(. + (if test(":") then "/128" else "/32" end));
# A name and a site key cover each other either way round: www.notion.so and notion.so.
def covers($b): . as $a | $a == $b or ($a | endswith("." + $b)) or ($b | endswith("." + $a));
# "kind<TAB>name<TAB>proto<TAB>...", the last per name and proto.
# The zapret scope'"'"'s group can write the file: only names a rule can take.
def verdicts: split("\n") | map(split("\t") | select(length >= 3 and (.[1] | test("^[a-z0-9.-]+$|^[0-9a-f:.]+$"))))
| reduce .[] as $v ({}; .[$v[1] + "\t" + $v[2]] = $v[0])
| to_entries | map({name: (.key | split("\t")[0]), proto: (.key | split("\t")[1]), kind: .value});
def named($kind; $proto): map(select(.kind == $kind and .proto == $proto) | .name);'
jq -n -c \
--rawfile user <(lists "$dir/zapret-hosts-user.txt") \
--rawfile auto <(lists "$dir/zapret-hosts-auto.txt") \
--rawfile excluded <(lists "$dir/zapret-hosts-user-exclude.txt") \
--rawfile verdicts <(lists "$dir/verdicts.tsv") \
"$hosts"'
($verdicts | verdicts) as $v
| ($v | named("works"; "tcp")) as $works
# Learned from a transfer cut short: success is judged on the first 4 KB, which the
# cutoff lets through, so "works" proves nothing for it.
| ($v | named("stalls"; "cutoff")) as $stalls
| ($excluded | hosts) as $excluded
| (($user | hosts) + ($auto | hosts | map(. as $h
| select(any($works[]; . as $w | $h | covers($w)) and (any($stalls[]; . as $s | $h | covers($s)) | not)))))
| unique - $excluded
| map(select(ip)) as $ips
| {version: 1, rules: (
[(. - $ips) | select(length > 0) | {domain_suffix: .}]
+ [$ips | select(length > 0) | {ip_cidr: cidr}])}
' >"$out/direct.json.tmp"
write "$out/direct.json"
jq -n -c --rawfile verdicts <(lists "$dir/verdicts.tsv") "$hosts"'
($verdicts | verdicts) as $v
# A site keyed by its address (no name seen) goes by address.
| ($v | named("unfixable"; "tcp")) as $tcp
| ($v | named("unfixable"; "udp")) as $udp
| {version: 1, rules: (
[$tcp | map(select(ip | not)) | select(length > 0) | {domain_suffix: .}]
+ [$udp | map(select(ip | not)) | select(length > 0) | {network: ["udp"], port: [443], domain_suffix: .}]
+ [$udp | map(select(ip)) | select(length > 0) | {network: ["udp"], port: [443], ip_cidr: cidr}]
+ [($v | named("blocked"; "ip")) + ($tcp | map(select(ip))) | select(length > 0) | {ip_cidr: cidr}])}
' >"$out/proxy.json.tmp"
write "$out/proxy.json"
+59 -4
View File
@@ -76,20 +76,69 @@ let
marker: marker + withSpaces staticListArgs
) hostlistMarkers) (lib.addContextFrom profile (lib.trim profile));
# detect.lua learns in place of nfqws2's autohostlist, in a last TLS profile of its
# own: z2k-profiles.template.sh puts it there, tailProfiles for nfqws2-keenetic.
learnLua = autoCfg.enable && autoCfg.extendedDetection && zapret2Cfg.profiles == null;
learnArgs = lib.optionalString learnLua (
lib.concatStringsSep ":" (
[
"auto=${autoHostlistFile}"
"exclude=${lib.concatStringsSep "," (source.learnExclude ++ [ excludeHostlistFile ])}"
"fails=${toString autoCfg.failThreshold}"
"time=${toString autoCfg.failTime}"
"inseq=${toString autoCfg.incomingMaxseq}"
"retrans=${toString autoCfg.retransThreshold}"
"win=${toString packetWindow.tcpIn}"
]
++ lib.optional (
zapret2Cfg.excludeDomains != [ ]
) "exclude_domains=${lib.concatStringsSep "," zapret2Cfg.excludeDomains}"
++ lib.optional zapret2Cfg.strategyLog "log"
)
);
z2kGenerated = sources.z2k.mkProfiles {
inherit learnArgs;
hostlistSuffix = withSpaces staticListArgs;
# z2k's category profiles filter on their own lists, not on a marker.
excludeSuffix = withSpaces ([ "--hostlist-exclude=${excludeHostlistFile}" ] ++ excludeDomainArgs);
};
# With detect.lua learning, the source's own learning profile only reads the auto list.
sourceProfiles =
if learnLua then
map (lib.replaceStrings [ "<HOSTLIST>" ] [ "<HOSTLIST_NOAUTO>" ]) source.profiles
else
source.profiles;
profilesFile =
if zapret2Cfg.profiles == null && isZ2k then
"${z2kGenerated}/profiles"
else
pkgs.writeText "proxy-suite-zapret2" (
lib.concatStringsSep " --new " (map renderProfile (orSource zapret2Cfg.profiles source.profiles))
lib.concatStringsSep " --new " (map renderProfile (orSource zapret2Cfg.profiles sourceProfiles))
);
# After every source profile, so each only takes what none of them did. ps_learn: the
# TLS sites in no list (z2k's template places its own). ps_syn: every new TCP connection
# until its first data names the protocol, to tell an address blocked outright.
tailProfiles = lib.concatMapStrings (profile: " --new " + profile) (
lib.optional (learnLua && !isZ2k) (
"--filter-tcp=443 --filter-l7=tls --in-range=-s65536 --out-range=-s32768 --payload=all"
+ " --lua-desync=ps_learn:${learnArgs}"
)
++ lib.optional zapret2Cfg.proxyFallback (
"--filter-tcp=* --out-range=<n2 --in-range=<n2 --payload=empty --lua-desync=ps_syn:"
+ lib.concatStringsSep ":" (
[
"fails=${toString autoCfg.failThreshold}"
"time=${toString autoCfg.failTime}"
]
++ lib.optional zapret2Cfg.strategyLog "log"
)
)
);
blobsFile =
if isZ2k then
"${z2kGenerated}/blobs"
@@ -140,6 +189,8 @@ let
failStamp
"${zapret2Sources.z2k}/files/lua/z2k-state-persist.lua"
./persist-every.lua
# After z2k-alert.lua, whose detector it wraps.
./detect.lua
]
++ lib.optional zapret2Cfg.strategyLog ./strategy-log.lua
)
@@ -165,7 +216,9 @@ let
# cover what the source's detectors need.
packetWindow = {
tcpOut = lib.max (6 + autoCfg.retransThreshold) (source.window.tcpOut or 0);
tcpIn = 15;
# The learner tells a stalled transfer from a finished one only while it still sees
# the server's packets; the 16 KB cutoff falls at about 12 of them.
tcpIn = if learnLua then 32 else 15;
udpOut = lib.max (6 + autoCfg.retransThreshold) (source.window.udpOut or 0);
udpIn = source.window.udpIn or 3;
};
@@ -218,14 +271,14 @@ let
pkgs.runCommand "proxy-suite-zapret2"
{
nativeBuildInputs = [ pkgs.gawk ];
inherit circularFill optPrefix;
inherit circularFill optPrefix tailProfiles;
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})"
opt="$optPrefix $(cat ${blobsFile}) $(cat ${profilesFile})$tailProfiles"
opt=$(printf '%s\n' "$opt" | awk -v fill="$circularFill" '
{
for (i = 1; i <= NF; i++) {
@@ -360,6 +413,8 @@ let
"PATH=${lib.makeBinPath runtimeDeps}"
# Read by z2k-state-persist.lua inside nfqws2, which inherits the unit's environment.
"Z2K_STATE_DIR_OVERRIDE=${circularStateDir}"
# detect.lua's verdicts: what zapret2 fixes, and what the proxy has to carry.
"PROXY_SUITE_ZAPRET2_VERDICTS=${stateDir}/verdicts.tsv"
"Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE=${pidDir}"
]
# The cutoff probe's maps, read by z2k's tcp16 name step; pin.txt forces one name for the line.
+10 -2
View File
@@ -94,6 +94,8 @@ let
);
luaInit = [ ];
daemonArgs = [ ];
# Never learned by detect.lua, as its own autohostlist never learned them.
learnExclude = [ "${src}/etc/nfqws2/lists/exclude.list" ];
ports = {
tcp = bare "TCP_PORTS";
udp = replaceStrings [ ":" ] [ "-" ] (bare "UDP_PORTS");
@@ -141,6 +143,8 @@ let
# 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" ];
# Its whitelist, which z2k-profiles.template.sh adds in front.
learnExclude = [ ];
ports = {
tcp = ports "NFQWS2_PORTS_TCP";
udp = ports "NFQWS2_PORTS_UDP";
@@ -158,7 +162,11 @@ let
# detectors, fake TTL) comes out exactly as on a router. Its tree is staged
# under $out because the generated options point into it.
mkProfiles =
{ hostlistSuffix, excludeSuffix }:
{
hostlistSuffix,
excludeSuffix,
learnArgs ? "",
}:
pkgs.runCommand "proxy-suite-zapret2-z2k-profiles" {
nativeBuildInputs = with pkgs; [
bash
@@ -168,7 +176,7 @@ let
gnugrep
gnused
];
inherit hostlistSuffix excludeSuffix;
inherit hostlistSuffix excludeSuffix learnArgs;
} (fillTemplate ./z2k-profiles.template.sh { z2k = src; });
};
in
@@ -39,10 +39,16 @@ grep -q -- '--lua-desync=circular' raw || { echo "z2k generator produced no prof
# strategies, as z2k's own autohostlist does: on rkn_tcp it would take
# YouTube from yt_tcp/gv_tcp below it. rkn_tcp then leaves their hosts to
# them even once learned or added by hand.
#
# With $learnArgs (autoHostlist.extendedDetection), detect.lua's ps_learn learns
# instead, in the same last place. It cannot ride along on the autohostlist profile:
# nfqws2 applies nothing there to a host in no list, Lua included. It writes the
# same auto list and reads the same excludes, which it checks itself.
awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \
-v wl="--hostlist-exclude=$root/lists/whitelist.txt" \
-v yt="--hostlist-exclude=$root/extra_strats/TCP/YT/List.txt --hostlist-exclude=$root/extra_strats/TCP/YT_GV/List.txt" \
-v hsuf="$hostlistSuffix" -v esuf="$excludeSuffix" '
-v hsuf="$hostlistSuffix" -v esuf="$excludeSuffix" \
-v learn="$learnArgs" -v wlfile="$root/lists/whitelist.txt" '
{
for (i = 1; i <= NF; i++) {
t = $i
@@ -67,7 +73,13 @@ awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \
}
END {
if (!seen || !(learner in ports)) { print "z2k general TLS profile not found" > "/dev/stderr"; exit 1 }
printf " --new --filter-tcp=%s --filter-l7=tls %s%s <HOSTLIST>%s", ports[learner], wl, esuf, hsuf
if (learn == "")
printf " --new --filter-tcp=%s --filter-l7=tls %s%s <HOSTLIST>%s", ports[learner], wl, esuf, hsuf
else {
# Its own excludes come first: the profile itself takes every remaining TLS flow.
sub(/:exclude=/, ":exclude=" wlfile ",", learn)
printf " --new --filter-tcp=%s --filter-l7=tls --in-range=-s65536 --out-range=-s32768 --payload=all --lua-desync=ps_learn:%s", ports[learner], learn
}
}' raw >body
# QUIC to blocked sites: z2k rotates QUIC strategies over YouTube's list alone, and DPI