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

+1
View File
@@ -194,6 +194,7 @@ Changes and secrets need root or the userControl group.
zapret auto add|forget|exclude <domain>
treat a site as blocked, forget it, or never touch it
zapret auto unpin|include <domain> undo add or exclude
zapret auto retry <domain|ip> give zapret2 another try where it sent the proxy
zapret auto clear forget learned sites and strategies
zapret cutoff [status] networks cut off at 16 KB, and names that pass
zapret cutoff probe probe again now
+2
View File
@@ -391,6 +391,7 @@ services.proxy-suite = {
autoHostlist = {
debugLog = false;
enable = true;
extendedDetection = true;
failThreshold = 3;
failTime = 300;
incomingMaxseq = 4096;
@@ -416,6 +417,7 @@ services.proxy-suite = {
udp = null;
};
profiles = null;
proxyFallback = true;
strategyLog = true;
strategySource = "nfqws2-keenetic";
};
+31 -3
View File
@@ -41,6 +41,7 @@ Part of the [proxy-suite options reference](./index.md).
- autoHostlist
- [enable](#services-proxy-suite-zapret-zapret2-autohostlist-enable)
- [debugLog](#services-proxy-suite-zapret-zapret2-autohostlist-debuglog)
- [extendedDetection](#services-proxy-suite-zapret-zapret2-autohostlist-extendeddetection)
- [failThreshold](#services-proxy-suite-zapret-zapret2-autohostlist-failthreshold)
- [failTime](#services-proxy-suite-zapret-zapret2-autohostlist-failtime)
- [incomingMaxseq](#services-proxy-suite-zapret-zapret2-autohostlist-incomingmaxseq)
@@ -63,6 +64,7 @@ Part of the [proxy-suite options reference](./index.md).
- [tcp](#services-proxy-suite-zapret-zapret2-ports-tcp)
- [udp](#services-proxy-suite-zapret-zapret2-ports-udp)
- [profiles](#services-proxy-suite-zapret-zapret2-profiles)
- [proxyFallback](#services-proxy-suite-zapret-zapret2-proxyfallback)
- [strategyLog](#services-proxy-suite-zapret-zapret2-strategylog)
- [strategySource](#services-proxy-suite-zapret-zapret2-strategysource)
@@ -95,8 +97,9 @@ Subnets zapret skips\.
## services\.proxy-suite\.zapret\.directSync\.enable
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\.
also the sites pinned at runtime, and the ones it learns once a strategy is seen getting
through for them, 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`
@@ -322,11 +325,23 @@ blocked\. When off, only ` zapret2.domains ` and ` proxy-ctl zapret auto add ` a
<a id="services-proxy-suite-zapret-zapret2-autohostlist-debuglog"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.debugLog
Log why sites are or are not learned\.
Log why sites are or are not learned (nfqws2’s own learner)\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-zapret-zapret2-autohostlist-extendeddetection"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.extendedDetection
Learn with proxy-suite’s detector instead of nfqws2’s\. It also learns sites blocked
only some of the time (a working connection no longer clears the failures before it),
downloads that stall partway (the 16 KB cutoff), and requests that never get an
answer\. Learned sites are logged with ` strategyLog `\. Only with the source’s own
` profiles `, and for TLS: nfqws2-keenetic no longer learns plain HTTP sites\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-zapret-zapret2-autohostlist-failthreshold"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.failThreshold
@@ -512,6 +527,19 @@ learning\. ` --qnum `, ` --fwmark ` and ` --lua-init ` are added for you\. ` nul
]
```
<a id="services-proxy-suite-zapret-zapret2-proxyfallback"></a>
## services\.proxy-suite\.zapret\.zapret2\.proxyFallback
Send through the proxy what zapret2 cannot fix: a site none of its strategies get
through for (only its QUIC, when that alone fails), and an address that leaves
connections unanswered (blocked by address, as Telegram’s are)\. Learned sites go
direct (` zapret.directSync `) only once a strategy is seen working for them\. Needs an
outbound; works for traffic the proxy sees (TUN, TProxy, per-app routing; by address
only where it sees the address)\. ` proxy-ctl zapret auto retry ` gives one another try\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-zapret-zapret2-strategylog"></a>
## services\.proxy-suite\.zapret\.zapret2\.strategyLog
+12 -5
View File
@@ -28,7 +28,13 @@ as `"general (ALT9)"`.
## Blocked sites found automatically: zapret2
zapret2 notices failing connections, marks the site as blocked, and finds a strategy that
works for it. Each site's strategy is remembered.
works for it. Each site's strategy is remembered. It also learns sites blocked only some of
the time, downloads that stall partway, and requests that never get an answer.
What zapret2 cannot fix goes through your proxy, when you have one: a site none of its
strategies get through for (only its QUIC, when that alone fails), and an address that
never answers at all, as Telegram's are blocked. That works for traffic the proxy sees
(TUN, TProxy, per-app routing).
```nix
services.proxy-suite = {
@@ -61,8 +67,9 @@ services.proxy-suite.zapret.zapret2.ports.extraUdp = [ "27015-27030" ];
```sh
proxy-ctl zapret # status
proxy-ctl zapret off # or: on, toggle, restart
proxy-ctl zapret auto # sites zapret2 learned
proxy-ctl zapret auto # sites zapret2 learned, and what goes to the proxy
proxy-ctl zapret auto add example.com # treat a site as blocked
proxy-ctl zapret auto retry example.com # give zapret2 another try at what it sent the proxy
proxy-ctl zapret auto exclude example.com # never touch or learn a site
proxy-ctl zapret auto forget example.com # forget it and its strategy
proxy-ctl zapret cutoff # networks cut off at 16 KB (z2k)
@@ -72,9 +79,9 @@ proxy-ctl zapret cutoff # networks cut off at 16 KB (z2k)
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. 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).
the ones you pin with `proxy-ctl zapret auto add`, and the sites it learns once one of its
strategies is seen getting through; your own rules and autoProxy still come first.
Everything else follows your [routing rules](./routing.md).
## Only for some apps
+7
View File
@@ -556,6 +556,12 @@ let
# 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;
# What zapret2 cannot fix (detect.lua's verdicts) goes through the proxy outbound.
zapret2ProxyFallback =
zapretEngine == "zapret2"
&& zapretGlobalEnabled
&& zapretCfg.zapret2.proxyFallback
&& hasAvailableOutbounds;
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.
@@ -884,6 +890,7 @@ in
zapretCutoffEnabled
zapretCutoffProxyFallback
zapret2DirectSync
zapret2ProxyFallback
userControlCfg
userControlEnabled
userControlAllows
+3 -2
View File
@@ -33,8 +33,9 @@ in
directSync = {
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.
also the sites pinned at runtime, and the ones it learns once a strategy is seen getting
through for them, 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.";
+26 -1
View File
@@ -101,6 +101,19 @@ in
};
};
proxyFallback = mkOption {
type = types.bool;
default = true;
description = ''
Send through the proxy what zapret2 cannot fix: a site none of its strategies get
through for (only its QUIC, when that alone fails), and an address that leaves
connections unanswered (blocked by address, as Telegram's are). Learned sites go
direct (`zapret.directSync`) only once a strategy is seen working for them. Needs an
outbound; works for traffic the proxy sees (TUN, TProxy, per-app routing; by address
only where it sees the address). `proxy-ctl zapret auto retry` gives one another try.
'';
};
strategyLog = mkOption {
type = types.bool;
default = true;
@@ -149,7 +162,19 @@ in
debugLog = mkOption {
type = types.bool;
default = false;
description = "Log why sites are or are not learned.";
description = "Log why sites are or are not learned (nfqws2's own learner).";
};
extendedDetection = mkOption {
type = types.bool;
default = true;
description = ''
Learn with proxy-suite's detector instead of nfqws2's. It also learns sites blocked
only some of the time (a working connection no longer clears the failures before it),
downloads that stall partway (the 16 KB cutoff), and requests that never get an
answer. Learned sites are logged with `strategyLog`. Only with the source's own
`profiles`, and for TLS: nfqws2-keenetic no longer learns plain HTTP sites.
'';
};
};
@@ -16,6 +16,7 @@ let
constants
zapretCutoffProxyFallback
zapret2DirectSync
zapret2ProxyFallback
jq
singBox
xray
@@ -187,6 +188,7 @@ let
enableOutboundTest ? false,
enableZapretCutoff ? false,
enableZapretDirect ? false,
enableZapretProxy ? false,
excludeServiceUserFromTun ? false,
}:
pkgs.writeShellScript "proxy-suite-core" ''
@@ -366,6 +368,21 @@ let
fi
''}
${lib.optionalString enableZapretProxy ''
# What zapret2 cannot fix (its strategies all failed for a site, or an address
# leaves connections unanswered) goes through the proxy: after explicit rules,
# autoProxy and the cutoff's networks, ahead of the hosts zapret2 does fix.
if [ "$ROUTE_MODE" != all-bypass ]; then
ZAPRET_PROXY_SET=${lib.escapeShellArg "${constants.zapret2DirectDir}/proxy.json"}
mkdir -p "$(dirname "$ZAPRET_PROXY_SET")"
[ -s "$ZAPRET_PROXY_SET" ] || echo '{"version":1,"rules":[]}' > "$ZAPRET_PROXY_SET"
chmod 644 "$ZAPRET_PROXY_SET"
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$ZAPRET_PROXY_SET" \
'. + [{type: "local", format: "source", tag: "zapret-unfixable", path: $p}]' <<< "$AUTOPROXY_RULE_SETS_JSON")
AUTOPROXY_RULES_JSON=$(${jq} -c '. + [{rule_set: ["zapret-unfixable"], outbound: "proxy"}]' <<< "$AUTOPROXY_RULES_JSON")
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,
@@ -520,6 +537,7 @@ let
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
enableZapretCutoff = zapretCutoffProxyFallback && !pureXrayEnabled;
enableZapretDirect = zapret2DirectSync && !pureXrayEnabled;
enableZapretProxy = zapret2ProxyFallback && !pureXrayEnabled;
enableOutboundTest = true;
};
+7 -4
View File
@@ -23,6 +23,7 @@ let
userControlExtraGroupsFor
zapretGlobalEnabled
zapret2DirectSync
zapret2ProxyFallback
;
inherit
(import ./zapret/common.nix {
@@ -136,10 +137,12 @@ let
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.services.proxy-suite-zapret2-direct = lib.mkIf (
zapret2DirectSync || zapret2ProxyFallback
) directSync.service;
services.proxy-suite.internal.paths.proxy-suite-zapret2-direct = lib.mkIf (
zapret2DirectSync || zapret2ProxyFallback
) directSync.path;
services.proxy-suite.internal.earlyPackages = [ runtime.package ];
@@ -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
+4
View File
@@ -57,6 +57,9 @@ let
amneziaWgInboundsRuntime = import ./checks/amnezia-wg-inbound-runtime.nix {
inherit pkgs proxySuiteModule;
};
zapret2Runtime = import ./checks/zapret2-runtime.nix {
inherit pkgs proxySuiteModule;
};
in
moduleSuiteChecks
// {
@@ -72,6 +75,7 @@ moduleSuiteChecks
amneziawg-runtime = amneziaWgRuntime;
proxy-inbounds-runtime = proxyInboundsRuntime;
amneziawg-inbounds-runtime = amneziaWgInboundsRuntime;
zapret2-runtime = zapret2Runtime;
}
// pythonChecks
// repoChecks
+184
View File
@@ -0,0 +1,184 @@
# zapret2's learning and verdicts against a censor in the middle (detect.lua): a router
# that blocks one site two connections out of three, cuts another after 16 KB, and drops
# every connection to an address. The client must learn the first two, record that the
# first works once it gets through, and hand the address to the proxy until it answers.
# Public test ranges throughout: detect.lua never judges private addresses.
{
pkgs,
proxySuiteModule,
}:
let
state = "/var/lib/proxy-suite/zapret2";
direct = "/var/lib/proxy-suite/zapret2-direct";
cert = pkgs.runCommand "zapret2-runtime-cert" { nativeBuildInputs = [ pkgs.openssl ]; } ''
mkdir -p "$out"
openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -subj /CN=fine.test \
-addext "subjectAltName=DNS:fine.test,DNS:flaky.test,DNS:stall.test,DNS:blocked.test" \
-keyout "$out/key.pem" -out "$out/cert.pem"
'';
# Big enough for the success detector (past 4 KB in) and, at /big, for the cutoff.
site = pkgs.runCommand "zapret2-runtime-site" { } ''
mkdir -p "$out"
head -c 65536 /dev/zero | tr '\0' a >"$out/index.html"
head -c 1048576 /dev/zero | tr '\0' b >"$out/big"
'';
address = interface: addresses: {
networking.interfaces.${interface}.ipv4.addresses = map (address: {
inherit address;
prefixLength = 24;
}) addresses;
};
in
pkgs.testers.runNixOSTest {
name = "proxy-suite-zapret2-runtime";
nodes = {
server = {
imports = [
(address "eth1" [
"203.0.113.2"
"203.0.113.3"
])
];
virtualisation.vlans = [ 2 ];
networking.useDHCP = false;
networking.defaultGateway = "203.0.113.1";
networking.firewall.allowedTCPPorts = [ 443 ];
services.nginx = {
enable = true;
virtualHosts.default = {
default = true;
onlySSL = true;
sslCertificate = "${cert}/cert.pem";
sslCertificateKey = "${cert}/key.pem";
root = site;
};
};
};
router = {
imports = [
(address "eth1" [ "198.51.100.1" ])
(address "eth2" [ "203.0.113.1" ])
];
virtualisation.vlans = [
1
2
];
networking.useDHCP = false;
networking.firewall.enable = false;
networking.nftables.enable = false;
boot.kernel.sysctl."net.ipv4.ip_forward" = 1;
environment.systemPackages = [ pkgs.iptables ];
};
client = {
imports = [
proxySuiteModule
(address "eth1" [ "198.51.100.2" ])
];
virtualisation.vlans = [ 1 ];
networking.useDHCP = false;
networking.defaultGateway = "198.51.100.1";
networking.hosts."203.0.113.2" = [
"fine.test"
"flaky.test"
"stall.test"
];
networking.hosts."203.0.113.3" = [ "blocked.test" ];
environment.systemPackages = [ pkgs.curl ];
services.proxy-suite = {
enable = true;
# An outbound to hand what zapret2 cannot fix to; nothing here dials it.
proxy = {
enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
url = "http://192.0.2.1:8080";
}
];
};
zapret = {
enable = true;
engine = "zapret2";
zapret2 = {
strategySource = "z2k";
# The probe dials the internet.
cutoff.enable = false;
};
};
};
};
};
testScript = ''
start_all()
server.wait_for_unit("nginx.service")
router.wait_for_unit("multi-user.target")
# The censor. Per connection, by the name in its ClientHello: flaky.test passes one
# in three; stall.test is cut once 16 KB came back; 203.0.113.3 never answers.
router.succeed(
"iptables -t mangle -A FORWARD -p tcp --dport 443 -m connmark --mark 0 -m string --string flaky.test --algo bm"
" -m statistic --mode nth --every 3 --packet 0 -j CONNMARK --set-mark 3",
"iptables -t mangle -A FORWARD -p tcp --dport 443 -m connmark --mark 0 -m string --string flaky.test --algo bm"
" -j CONNMARK --set-mark 2",
"iptables -t mangle -A FORWARD -p tcp --dport 443 -m connmark --mark 0 -m string --string stall.test --algo bm"
" -j CONNMARK --set-mark 4",
"iptables -A FORWARD -m connmark --mark 2 -j DROP",
"iptables -A FORWARD -p tcp --sport 443 -m connmark --mark 4"
" -m connbytes --connbytes 16384: --connbytes-dir reply --connbytes-mode bytes -j DROP",
"iptables -A FORWARD -d 203.0.113.3 -p tcp --syn -j DROP",
# Byte counts for connbytes; the rules above loaded conntrack.
"sysctl -w net.netfilter.nf_conntrack_acct=1",
)
client.wait_for_unit("proxy-suite-zapret.service")
client.wait_until_succeeds("curl -sk --max-time 5 -o /dev/null https://fine.test/")
def curl(host, path="/", seconds=8):
client.execute(f"curl -sk --noproxy '*' --max-time {seconds} -o /dev/null https://{host}{path}")
def learned(host):
return f"grep -qx {host} ${state}/zapret-hosts-auto.txt"
with subtest("a site blocked two times in three is learned, successes in between"):
for _ in range(9):
curl("flaky.test")
client.wait_until_succeeds(learned("flaky.test"), timeout=60)
with subtest("a transfer cut after 16 KB is learned"):
for _ in range(4):
curl("stall.test", "/big", 12)
client.wait_until_succeeds(learned("stall.test"), timeout=60)
with subtest("a working site is not"):
for _ in range(4):
curl("fine.test", "/big")
client.fail(learned("fine.test"))
with subtest("an address that never answers goes to the proxy, until it does"):
for _ in range(4):
curl("blocked.test", "/", 5)
client.wait_until_succeeds("grep -qP '^blocked\\t203\\.0\\.113\\.3\\tip' ${state}/verdicts.tsv", timeout=60)
client.wait_until_succeeds("grep -qF 203.0.113.3/32 ${direct}/proxy.json", timeout=60)
client.succeed("proxy-ctl zapret auto | grep -F 'blocked by address'")
router.succeed("iptables -D FORWARD -d 203.0.113.3 -p tcp --syn -j DROP")
curl("blocked.test")
client.wait_until_succeeds("grep -qP '^reachable\\t203\\.0\\.113\\.3\\tip' ${state}/verdicts.tsv", timeout=60)
client.wait_until_succeeds("! grep -qF 203.0.113.3 ${direct}/proxy.json", timeout=60)
with subtest("a learned site goes direct once a strategy gets through for it"):
for _ in range(9):
curl("flaky.test")
client.wait_until_succeeds("grep -qP '^works\\tflaky\\.test\\ttcp' ${state}/verdicts.tsv", timeout=60)
client.wait_until_succeeds("grep -qF '\"flaky.test\"' ${direct}/direct.json", timeout=60)
# stall.test never got through: it keeps the proxy's route.
client.fail("grep -qF stall.test ${direct}/direct.json")
'';
}
+81 -25
View File
@@ -189,7 +189,9 @@ in
# The NFQUEUE window must exceed the retransmission threshold.
grep -qx 'NFQWS2_TCP_PKT_OUT=9' "${globalRuntime}/config"
grep -qx 'NFQWS2_TCP_PKT_IN=15' "${globalRuntime}/config"
# Wider with detect.lua learning, to see a transfer stall past the 16 KB cutoff.
grep -qx 'NFQWS2_TCP_PKT_IN=32' "${globalRuntime}/config"
grep -qx 'NFQWS2_TCP_PKT_IN=15' "${tunedRuntime}/config"
# Learning off means list mode, not "no lists".
grep -qx 'MODE_FILTER=hostlist' "${noAutoRuntime}/config"
@@ -236,7 +238,7 @@ in
'
# 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"
grep -qE -- 'z2k-state-persist\.lua --lua-init=@[^ ]+-persist-every\.lua --lua-init=@[^ ]+-detect\.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 } } }
@@ -286,6 +288,21 @@ in
assert(key("1.2.3.4", "2", true) == "standard")
assert(key("www.google.com", nil) == "standard")
'
# What nfqws2's learner and z2k's detector miss: flaky sites, stalled transfers,
# unanswered ClientHellos, for learning and for rotation; and the verdicts the
# proxy routes by: works, unfixable, blocked by address.
mkdir -p detect
touch detect/verdicts.tsv
DETECT=$(grep -oE '/nix/store/[^ ]+-detect\.lua' "${z2kRuntime}/config") WORK="$PWD/detect" \
PROXY_SUITE_ZAPRET2_VERDICTS="$PWD/detect/verdicts.tsv" lua ${./zapret2/detect-test.lua}
# nfqws2 finds the verdicts file by its environment; the last profile watches
# connections for addresses blocked outright.
grep -qF '"PROXY_SUITE_ZAPRET2_VERDICTS=/var/lib/proxy-suite/zapret2/verdicts.tsv"' \
<<<'${builtins.toJSON zapret2Z2k.config.systemd.services.proxy-suite-zapret.serviceConfig.Environment}'
grep -qE -- " --new --filter-tcp=\* --out-range=<n2 --in-range=<n2 --payload=empty --lua-desync=ps_syn:fails=3:time=300:log'$" "${z2kRuntime}/config"
# nfqws2-keenetic learns with detect.lua too: its own profile only reads the auto list.
grep -qE -- " --new --filter-tcp=443 --filter-l7=tls --in-range=-s65536 --out-range=-s32768 --payload=all --lua-desync=ps_learn:auto=[^ ]+:exclude=[^ ]+/etc/nfqws2/lists/exclude.list,[^ ]+zapret-hosts-user-exclude.txt:" "${globalRuntime}/config"
test "$(grep -oF -- '<HOSTLIST>' "${globalRuntime}/config" | wc -l)" = 0
# 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 '
@@ -350,8 +367,15 @@ in
# YouTube's hosts to yt_tcp/gv_tcp.
grep -qF -- '/extra_strats/TCP_Discord.txt <HOSTLIST_NOAUTO> --hostlist-exclude=' "${z2kRuntime}/config"
grep -qE -- '<HOSTLIST_NOAUTO> --hostlist-exclude=[^ ]+/extra_strats/TCP/YT/List.txt --hostlist-exclude=[^ ]+/extra_strats/TCP/YT_GV/List.txt --filter-tcp=' "${z2kRuntime}/config"
test "$(grep -oF -- '<HOSTLIST>' "${z2kRuntime}/config" | wc -l)" = 1
grep -qE -- " --new --filter-tcp=443,2053,2083,2087,2096,8443 --filter-l7=tls --hostlist-exclude=[^ ]+/lists/whitelist.txt --hostlist-exclude=/var/lib/proxy-suite/zapret2/zapret-hosts-user-exclude.txt <HOSTLIST>'$" "${z2kRuntime}/config"
# nfqws2's own learner, without extendedDetection.
test "$(grep -oF -- '<HOSTLIST>' "${z2kTunedRuntime}/config" | wc -l)" = 1
grep -qE -- " --new --filter-tcp=443,2053,2083,2087,2096,8443,8444 --filter-l7=tls --hostlist-exclude=[^ ]+/lists/whitelist.txt --hostlist-exclude=/var/lib/proxy-suite/zapret2/zapret-hosts-user-exclude.txt <HOSTLIST> --new --filter-tcp=\* " "${z2kTunedRuntime}/config"
grep -qx 'NFQWS2_TCP_PKT_IN=15' "${z2kTunedRuntime}/config"
# detect.lua's in its place by default: same ports, the same auto list and excludes,
# and the server's packets past the 16 KB cutoff.
test "$(grep -oF -- '<HOSTLIST>' "${z2kRuntime}/config" | wc -l)" = 0
grep -qE -- " --new --filter-tcp=443,2053,2083,2087,2096,8443 --filter-l7=tls --in-range=-s65536 --out-range=-s32768 --payload=all --lua-desync=ps_learn:auto=/var/lib/proxy-suite/zapret2/zapret-hosts-auto.txt:exclude=[^ ]+/lists/whitelist.txt,/var/lib/proxy-suite/zapret2/zapret-hosts-user-exclude.txt:fails=3:time=300:inseq=4096:retrans=3:win=32:log --new --filter-tcp=\* " "${z2kRuntime}/config"
grep -qx 'NFQWS2_TCP_PKT_IN=32' "${z2kRuntime}/config"
grep -qF -- '/lists/whitelist.txt --hostlist-exclude=/var/lib/proxy-suite/zapret2/zapret-hosts-user-exclude.txt' "${z2kRuntime}/config"
# proxy-ctl names state.tsv's rows by this map: keyed circulars by key, the
@@ -431,19 +455,37 @@ in
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
# What zapret2 cannot fix goes to the proxy, ahead of what it does.
grep -qF 'tag: "zapret-unfixable"' ${socksStart zapret2Global}
test "$(grep -n 'zapret-unfixable' ${socksStart zapret2Global} | head -n1 | cut -d: -f1)" -lt \
"$(grep -n 'zapret-hosts' ${socksStart zapret2Global} | head -n1 | cut -d: -f1)"
# Pinned hosts, and learned ones a strategy was seen working for, less the excluded;
# IP literals as single addresses.
mkdir -p direct-lists empty-lists out empty-out
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 'Learned.Example\nexcluded.example\n203.0.113.7\n2001:db8::1\npinned.example\nunseen.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":[]}'
{
printf 'works\tlearned.example\ttcp\trkn_tcp\t1\nworks\texcluded.example\ttcp\trkn_tcp\t1\n'
printf 'works\t203.0.113.7\ttcp\trkn_tcp\t1\n'
printf 'stalls\tunseen.example\tcutoff\t\t1\nworks\tunseen.example\ttcp\trkn_tcp\t2\n'
printf 'unfixable\tchat.example\ttcp\trkn_tcp\t2\nunfixable\tdiscord.com\tudp\trkn_quic\t2\n'
printf 'works\tdiscord.com\ttcp\trkn_tcp\t2\n'
printf 'blocked\t149.154.167.99\tip\tx\t3\nblocked\t198.51.100.1\tip\tx\t3\nreachable\t198.51.100.1\tip\t\t4\n'
printf 'unfixable\tretried.example\ttcp\t\t5\nretry\tretried.example\ttcp\tproxy-ctl\t6\n'
printf 'unfixable\tBAD NAME\ttcp\t\t7\n'
} >direct-lists/verdicts.tsv
${directSync} direct-lists out
test "$(cat out/direct.json)" = '{"version":1,"rules":[{"domain_suffix":["learned.example","pinned.example"]},{"ip_cidr":["203.0.113.7/32"]}]}'
# A site's TCP, or only its QUIC; addresses blocked outright.
test "$(cat out/proxy.json)" = '{"version":1,"rules":[{"domain_suffix":["chat.example"]},{"network":["udp"],"port":[443],"domain_suffix":["discord.com"]},{"ip_cidr":["149.154.167.99/32"]}]}'
# Unchanged, the files stay as they were: sing-box reloads on every rename.
inode=$(stat -c %i out/direct.json)
${directSync} direct-lists out
test "$(stat -c %i out/direct.json)" = "$inode"
${directSync} empty-lists empty-out
test "$(cat empty-out/direct.json)" = '{"version":1,"rules":[]}'
test "$(cat empty-out/proxy.json)" = '{"version":1,"rules":[]}'
# --- per-app instance -------------------------------------------------
# Wrapped apps opted in explicitly, so no hostlist gates them.
@@ -490,7 +532,9 @@ in
opt=$(printf '%s' "$opt" | sed "s|/var/lib/proxy-suite/zapret2/|$HOSTLIST_BASE/|g")
printf '%s\n' "$opt" | tr ' ' '\n' >"$2"
# --user is deliberately omitted: the sandbox is not root.
# --user is deliberately omitted: the sandbox is not root. No globbing, as in
# the launcher: --filter-tcp=* is nfqws2's.
set -f
"$base/nfq2/nfqws2" --dry-run --fwmark="$DESYNC_MARK" \
--lua-init=@"$base/lua/zapret-lib.lua" \
--lua-init=@"$base/lua/zapret-antidpi.lua" \
@@ -499,26 +543,38 @@ in
)
dry_run ${globalRuntime} global.args
grep -qx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" global.args
grep -qx -- '--hostlist-auto-fail-threshold=3' global.args
grep -qx -- '--hostlist-auto-fail-time=300' global.args
# detect.lua learns; the auto list is read like the others.
if grep -q -- '^--hostlist-auto=' global.args; then exit 1; fi
grep -qx -- "--hostlist=$HOSTLIST_BASE/zapret-hosts-auto.txt" global.args
grep -q -- '^--lua-desync=ps_learn:' global.args
# The supervised launcher execs nfqws2 with the command line the init script builds.
printf '#!/bin/sh\nprintf "%%s\\n" "$@"\n' >fake-nfqws2
chmod +x fake-nfqws2
ZAPRET_RW=${globalRuntime} NFQWS2="$PWD/fake-nfqws2" ${daemonStart} >daemon.args
head -n1 daemon.args | grep -qx -- '--user=root'
tail -n +6 daemon.args | diff - global.args
# dry_run moved the state files into the sandbox, detect.lua's arguments with them.
tail -n +6 daemon.args | sed "s|/var/lib/proxy-suite/zapret2/|$HOSTLIST_BASE/|g" | diff - global.args
dry_run ${z2kRuntime} z2k.args
test "$(grep -cx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" z2k.args)" = 1
# Nothing follows the learning profile, so no profile after it can lose to it.
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
# The learner is the last profile: nothing after it, and nfqws2's own autohostlist off.
test "$(grep -cx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" z2k.args)" = 0
# Only ps_syn follows it, last: it takes connections before their data names them.
test "$(sed -n '/^--lua-desync=ps_learn:/,$p' z2k.args | grep -c -- '^--new$')" = 1
tail -n1 z2k.args | grep -q -- '^--lua-desync=ps_syn:'
# Extra ports and --debug are options nfqws2 takes.
# Extra ports and --debug are options nfqws2 takes; nfqws2's own learner, tuned.
dry_run ${tunedRuntime} tuned.args
grep -qx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" tuned.args
grep -qx -- '--hostlist-auto-fail-threshold=5' tuned.args
grep -qx -- '--hostlist-auto-fail-time=120' tuned.args
dry_run ${z2kTunedRuntime} z2k-tuned.args >/dev/null
test "$(grep -cx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" z2k-tuned.args)" = 1
# Nothing but ps_syn follows the learning profile, so no profile after it can lose
# to it: ps_syn takes only what has no protocol yet, which the TLS learner never does.
test "$(sed -n '/^--hostlist-auto=/,$p' z2k-tuned.args | grep -c -- '^--new$')" = 1
test "$(sed -n '/^--hostlist-auto=/,$p' z2k-tuned.args | grep -c -- '^--lua-desync=')" = 1
tail -n1 z2k-tuned.args | grep -q -- '^--lua-desync=ps_syn:'
touch "$out"
'';
+236
View File
@@ -0,0 +1,236 @@
-- detect.lua against stubs of the nfqws2 API it uses: timers fire when the test says.
-- $DETECT: the module; $WORK: a writable directory; $PROXY_SUITE_ZAPRET2_VERDICTS in it.
local work = os.getenv("WORK")
local verdict_file = os.getenv("PROXY_SUITE_ZAPRET2_VERDICTS")
local timers = {}
function timer_set(name, func, _, _, data) timers[name] = { func = func, data = data } end
local function fire(prefix)
for name, t in pairs(timers) do
if name:sub(1, #prefix) == prefix then
timers[name] = nil
t.func(name, t.data)
end
end
end
TH_FIN, TH_SYN, TH_RST, TH_ACK = 1, 2, 4, 16
function ntop(ip) return ip end
function dis_ipdst(dis) return dis.dst end
function deepcopy(t) return t end
function dis_reverse() end
local resets = 0
function rawsend_dissect() resets = resets + 1 end
function is_retransmission(desync) return desync.retrans end
function standard_failure_detector() return "standard" end
function standard_hostkey(desync) return desync.track.hostname:gsub("^www%.", "") end
function automate_failure_check(_, _, crec)
crec.nocheck = true
return false
end
function bitand(a, b)
local r, bit = 0, 1
while a > 0 and b > 0 do
if a % 2 == 1 and b % 2 == 1 then r = r + bit end
a, b, bit = math.floor(a / 2), math.floor(b / 2), bit * 2
end
return r
end
function pos_get(desync, mode) return desync.pos[mode] end
function dis_timer_name(dis) return dis.flow end
-- rotation: what circular and z2k leave in place
local counted = {}
function automate_failure_counter(hrec, crec, fails)
crec.failure = true
hrec.failure_counter = (hrec.failure_counter or 0) + 1
counted[#counted + 1] = hrec.failure_counter
if hrec.failure_counter < fails then return false end
hrec.failure_counter = nil
return true
end
local hrec = { nstrategy = 1, ctstrategy = 50 }
function automate_host_record() return hrec end
function z2k_fail_tls_alert() return "z2k" end
dofile(os.getenv("DETECT"))
local auto = work .. "/auto.txt"
local excl = work .. "/exclude.txt"
local f = io.open(excl, "w")
f:write("bank.example\n")
f:close()
io.open(auto, "w"):close()
local arg = { auto = auto, exclude = excl, fails = "3", time = "300", inseq = "4096", win = "32", exclude_domains = "skip.example" }
local flows = 0
local function flow(host)
flows = flows + 1
return { hostname = host, lua_state = {}, flow = "f" .. flows, pos = { reverse = { tcp = { winsize = 64 } } } }
end
local function packet(track, outgoing, opts)
return {
track = track,
outgoing = outgoing,
arg = arg,
l7payload = opts.l7,
pos = { n = opts.n or 1, s = opts.s or 1 },
dis = { flow = track.flow, tcp = { th_flags = opts.flags or 16 }, payload = opts.payload or "" },
}
end
local function hello(track) ps_learn(nil, packet(track, true, { l7 = "tls_client_hello", payload = "hello" })) end
local function reply(track, s, data, n) ps_learn(nil, packet(track, false, { s = s, payload = data, n = n })) end
local function record(len) return string.char(23, 3, 3, math.floor(len / 256), len % 256) end
local function learned()
local t = {}
for line in io.lines(auto) do t[line] = true end
return t
end
-- A site blocked some of the time: a working connection between failures no longer
-- clears them, and the third no-reply learns it.
for i = 1, 3 do
local t = flow("www.notion.so")
hello(t)
fire("psln_")
if i == 2 then
local ok = flow("www.notion.so")
hello(ok)
reply(ok, 1, record(3) .. "abc")
fire("psln_")
fire("psls_")
end
end
assert(learned()["www.notion.so"], "flaky site learned")
-- The 16 KB cutoff: a record announced longer than what arrived, then silence.
for _ = 1, 3 do
local t = flow("signal.org")
hello(t)
reply(t, 1, record(16000) .. string.rep("x", 8000), 6)
reply(t, 8006, string.rep("x", 4000), 9)
fire("psln_")
fire("psls_")
end
assert(learned()["signal.org"], "stalled site learned")
do
local found = false
for line in io.lines(verdict_file) do
if line:match("^stalls\tsignal%.org\tcutoff\t") then found = true end
end
assert(found, "learned from a cut transfer: it keeps the proxy's route")
end
-- A whole record and silence is a finished reply; out of order bytes are put in order.
for _ = 1, 3 do
local t = flow("fine.example")
hello(t)
reply(t, 9, string.rep("y", 4), 3)
reply(t, 1, record(7) .. "yyy", 2)
fire("psln_")
fire("psls_")
end
assert(not learned()["fine.example"], "finished transfers are no failure")
-- Past the queue window nothing more is seen: no verdict.
for _ = 1, 3 do
local t = flow("big.example")
hello(t)
reply(t, 1, record(60000) .. "z", 32)
fire("psls_")
end
assert(not learned()["big.example"], "blind past the window")
-- A reset early in the reply counts; excluded sites never.
for _ = 1, 3 do
local t = flow("reset.example")
hello(t)
ps_learn(nil, packet(t, false, { flags = TH_RST, s = 1 }))
for _, host in ipairs({ "www.bank.example", "skip.example" }) do
local x = flow(host)
hello(x)
fire("psln_")
end
end
local got = learned()
assert(got["reset.example"] and not got["www.bank.example"] and not got["skip.example"])
-- A client that hangs up before the answer (a cancelled page) says nothing of the site.
for _ = 1, 3 do
local t = flow("cancelled.example")
hello(t)
ps_learn(nil, packet(t, true, { flags = TH_FIN + 16 }))
fire("psln_")
end
assert(not learned()["cancelled.example"], "cancelled connections are no failure")
-- Rotation: a ClientHello with no reply counts a failure; three switch the strategy.
-- A reply, or the detector's own verdict, in time leaves it be.
local function tls(outgoing, payload, crec, flags)
return z2k_fail_tls_alert({
outgoing = outgoing,
l7payload = outgoing and payload ~= "" and "tls_client_hello" or nil,
track = {},
arg = { fails = "3", time = "60" },
dis = { flow = "r" .. tostring(crec), tcp = { th_flags = flags }, payload = payload },
}, crec)
end
for _ = 1, 3 do
local crec = {}
assert(tls(true, "hello", crec) == "z2k")
fire("psnr_")
end
assert(hrec.nstrategy == 2 and #counted == 3, "rotated after three silent ClientHellos")
local answered, judged, cancelled = {}, { nocheck = true }, {}
tls(true, "hello", answered)
tls(false, "server hello", answered)
tls(true, "hello", judged)
tls(true, "hello", cancelled)
tls(true, "", cancelled, TH_RST)
fire("psnr_")
assert(#counted == 3, "answered, judged or cancelled flows are no failure")
assert(standard_failure_detector({ arg = {}, dis = { tcp = {} } }, {}) == "standard", "nfqws2's detector is wrapped too")
local function verdicts()
local t = {}
for line in io.lines(verdict_file) do
local kind, name, proto = line:match("^(%w+)\t([^\t]+)\t([^\t]*)")
t[name .. " " .. proto] = kind
end
return t
end
-- Fast fail: a ClientHello retransmitted into silence gets the client a reset, and counts.
local t = flow("slow.example")
hello(t)
for _ = 1, 3 do ps_learn(nil, { track = t, outgoing = true, arg = arg, retrans = true, pos = {}, dis = { flow = t.flow, tcp = { th_flags = 16 }, payload = "hello" } }) end
assert(resets == 1 and t.lua_state.ps_learn.counted, "reset after three retransmissions")
-- works: a connection that got through, by the site key, with its protocol.
local wrec = { ps_cycle = 4 }
automate_failure_check({ arg = { key = "rkn_tcp" }, track = { hostname = "www.notion.so" }, dis = { tcp = {} } }, wrec, {})
assert(verdicts()["notion.so tcp"] == "works" and wrec.ps_cycle == 0, "works recorded, the cycle count reset")
-- unfixable: a whole cycle of strategies without one success stops the rotation.
local qrec = { nstrategy = 2, ctstrategy = 2 }
autostate = { rkn_quic = { ["discord.com"] = qrec } }
automate_failure_counter(qrec, {}, 1)
assert(not qrec.final)
automate_failure_counter(qrec, {}, 1)
assert(qrec.final == 2 and verdicts()["discord.com udp"] == "unfixable", "unfixable after a full cycle, QUIC only")
-- Addresses: unanswered connections make one blocked, an answer clears it; local ones never.
local function syn(ip, answered)
local s = flow("")
s.hostname = nil
local pkt = function(outgoing, flags) return { track = s, outgoing = outgoing, arg = arg, pos = {}, dis = { flow = s.flow, dst = ip, tcp = { th_flags = flags } } } end
ps_syn(nil, pkt(true, TH_SYN))
if answered then ps_syn(nil, pkt(false, TH_SYN + TH_ACK)) end
fire("pssy_")
end
for _ = 1, 3 do
syn("149.154.167.99")
syn("192.168.1.1")
end
assert(verdicts()["149.154.167.99 ip"] == "blocked" and not verdicts()["192.168.1.1 ip"], "blocked by address")
syn("149.154.167.99", true)
assert(verdicts()["149.154.167.99 ip"] == "reachable", "an answer clears it")
print("detect.lua ok")
+2
View File
@@ -57,6 +57,7 @@ in
failTime = 120;
retransThreshold = 4;
debugLog = true;
extendedDetection = false;
};
};
};
@@ -78,6 +79,7 @@ in
ports.extraTcp = [ 8444 ];
strategyLog = false;
debug = true;
autoHostlist.extendedDetection = false;
};
};
+100 -9
View File
@@ -115,6 +115,7 @@ Changes and secrets need root or the userControl group.
zapret auto add|forget|exclude <domain>
treat a site as blocked, forget it, or never touch it
zapret auto unpin|include <domain> undo add or exclude
zapret auto retry <domain|ip> give zapret2 another try where it sent the proxy
zapret auto clear forget learned sites and strategies
zapret cutoff [status] networks cut off at 16 KB, and names that pass
zapret cutoff probe probe again now
@@ -795,9 +796,11 @@ COMPLETE = {
"exclude": "never touch or learn a host",
"unpin": "undo add",
"include": "undo exclude",
"retry": "give zapret2 another try where it sent the proxy",
"clear": "forget learned hosts and strategies",
}
},
"zapret auto retry": {"args": lambda: _names(name for name, _ in _zapret_proxied())},
"zapret auto forget": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-auto.txt"))))},
"zapret auto exclude": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-auto.txt"))))},
"zapret auto unpin": {"args": lambda: _names(lines(read_text(_zapret_auto_file("zapret-hosts-user.txt"))))},
@@ -3732,6 +3735,82 @@ def _zapret_strategy_summary(domain, rows=None, strategies=None):
return "; ".join(_zapret_strategy_text(r, strategies) for r in _zapret_strategies_for(domain, rows))
# detect.lua's verdicts (zapret2/detect.lua): "kind<TAB>name<TAB>proto<TAB>note<TAB>time",
# the last per name and proto standing. What the proxy carries in zapret2's stead, and
# whether a learned site is seen working, which decides whether directSync sends it direct.
ZAPRET_PROXIED = {"tcp": "no strategy gets through", "udp": "its QUIC: no strategy gets through", "ip": "blocked by address"}
def _zapret_verdicts():
"""{(name, proto): kind}, the last verdict of each."""
out = {}
for fields in _tsv(_zapret_auto_file("verdicts.tsv")):
if len(fields) >= 3 and fields[0] and fields[1]:
out[(fields[1], fields[2])] = fields[0]
return out
def _zapret_covers(host, name):
"""A host and a site key, either way round: www.notion.so and notion.so."""
return host == name or host.endswith(f".{name}") or name.endswith(f".{host}")
def _zapret_status(host, verdicts=None):
"""What zapret2 made of host, "" before it decided anything."""
verdicts = _zapret_verdicts() if verdicts is None else verdicts
kinds = {}
for (name, proto), kind in verdicts.items():
if _zapret_covers(host, name):
kinds[proto] = kind
parts = []
if kinds.get("tcp") == "unfixable":
parts.append("via the proxy: no strategy gets through")
elif kinds.get("cutoff") == "stalls":
parts.append("cut off after 16 KB: keeps the proxy's route")
elif kinds.get("tcp") == "works":
parts.append("works")
if kinds.get("udp") == "unfixable":
parts.append("QUIC via the proxy")
return ", ".join(parts)
def _zapret_proxied(verdicts=None):
"""[(name, why)] the proxy carries because zapret2 cannot fix them."""
verdicts = _zapret_verdicts() if verdicts is None else verdicts
return [
(name, ZAPRET_PROXIED[proto])
for (name, proto), kind in sorted(verdicts.items())
if (kind, proto) in (("unfixable", "tcp"), ("unfixable", "udp"), ("blocked", "ip"))
]
def _zapret_verdicts_drop(host):
"""Forgets every verdict about host, so zapret2 judges it afresh."""
path = _zapret_auto_file("verdicts.tsv")
if not os.path.isfile(path):
return
def keep(line):
fields = line.split("\t")
return len(fields) < 2 or not _zapret_covers(host, fields[1])
_replace_lines(path, keep)
def _zapret_retry(name):
"""The proxy carries name no longer: zapret2 tries it again, rotation unfrozen."""
path = _zapret_auto_file("verdicts.tsv")
retried = [proto for (n, proto), kind in _zapret_verdicts().items() if n == name and kind in ("unfixable", "blocked")]
if not retried:
die(f"zapret2 sends nothing for {name} through the proxy: proxy-ctl zapret auto lists what it does.")
now = int(time.time())
_replace_lines(path, lambda _: True, [f"retry\t{name}\t{proto}\tproxy-ctl\t{now}" for proto in retried])
# nfqws2 keeps a site's rotation stopped, and its verdicts, until it restarts.
if svc_active("proxy-suite-zapret"):
cmd_zapret("restart")
print(f"zapret2 tries {name} again; the proxy carries it no longer.")
def _truncate(path):
_replace_lines(path, lambda _: False)
@@ -3754,27 +3833,39 @@ def cmd_zapret_auto(verb="list", domain="", *_):
user = _zapret_auto_file("zapret-hosts-user.txt")
exclude = _zapret_auto_file("zapret-hosts-user-exclude.txt")
if verb in ("add", "forget", "exclude", "unpin", "include") and not _zapret_auto_host(domain):
if verb in ("add", "forget", "exclude", "unpin", "include", "retry") and not _zapret_auto_host(domain):
usage(f"zapret auto {verb} <domain>")
if verb == "list":
hosts = [h for h in lines(read_text(auto)) if h] if os.path.isfile(auto) else []
if not hosts:
print("No hostnames learned yet.")
rows, strategies = _zapret_strategy_rows(), _zapret_strategy_map()
rows, strategies, verdicts = _zapret_strategy_rows(), _zapret_strategy_map(), _zapret_verdicts()
width = max(map(len, hosts), default=0)
for host in hosts:
summary = _zapret_strategy_summary(host, rows, strategies)
print(f"{host:<{width}} {summary}" if summary else host)
notes = [n for n in (_zapret_strategy_summary(host, rows, strategies), _zapret_status(host, verdicts)) if n]
print(f"{host:<{width}} {'; '.join(notes)}" if notes else host)
proxied = _zapret_proxied(verdicts)
if proxied:
print("\nThrough the proxy, as zapret2 cannot fix them:")
width = max(len(name) for name, _ in proxied)
for name, why in proxied:
print(f" {name:<{width}} {why}")
sys.stdout.flush()
print("Give one another try: proxy-ctl zapret auto retry <name>", file=sys.stderr)
elif verb == "retry":
_zapret_retry(domain)
elif verb == "add":
_zapret_auto_edit(user, domain, "add")
print(f"Pinned {domain}: zapret treats it as blocked.")
elif verb == "forget":
_zapret_auto_edit(auto, domain, "drop")
_zapret_strategy_drop(domain)
_zapret_verdicts_drop(domain)
print(f"Forgot {domain}. It is learned again if it keeps failing; 'exclude' prevents that.")
elif verb == "exclude":
_zapret_auto_edit(auto, domain, "drop")
_zapret_strategy_drop(domain)
_zapret_verdicts_drop(domain)
_zapret_auto_edit(exclude, domain, "add")
print(f"Excluded {domain}. It is no longer touched or learned.")
elif verb == "unpin":
@@ -3785,12 +3876,12 @@ def cmd_zapret_auto(verb="list", domain="", *_):
print(f"Included {domain}. It can be learned again.")
elif verb == "clear":
_truncate(auto)
state = _zapret_auto_file("circular/state.tsv")
if os.path.exists(state):
_truncate(state)
print("Cleared learned hosts and remembered strategies.")
for path in (_zapret_auto_file("circular/state.tsv"), _zapret_auto_file("verdicts.tsv")):
if os.path.exists(path):
_truncate(path)
print("Cleared learned hosts, remembered strategies and what zapret2 sent the proxy.")
else:
usage("zapret auto [list|add|forget|exclude|unpin|include|clear]")
usage("zapret auto [list|add|forget|exclude|unpin|include|retry|clear]")
# --- zapret cutoff ------------------------------------------------------------
+16 -4
View File
@@ -418,11 +418,20 @@ def zapret_rows(_):
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
return []
rows = {}
strategy_rows, strategies = ctl._zapret_strategy_rows(), ctl._zapret_strategy_map()
strategy_rows, strategies, verdicts = ctl._zapret_strategy_rows(), ctl._zapret_strategy_map(), ctl._zapret_verdicts()
for kind, name in ZAPRET_LISTS:
for host in _lines(name):
strategy = "" if kind == "excluded" else ctl._zapret_strategy_summary(host, strategy_rows, strategies)
rows.setdefault(f"{kind}:{host}", {"key": f"{kind}:{host}", "host": host, "kind": kind, "strategy": strategy})
excluded = kind == "excluded"
rows.setdefault(f"{kind}:{host}", {
"key": f"{kind}:{host}",
"host": host,
"kind": kind,
"strategy": "" if excluded else ctl._zapret_strategy_summary(host, strategy_rows, strategies),
"status": "" if excluded else ctl._zapret_status(host, verdicts),
})
# What zapret2 cannot fix, the proxy carries: sites no strategy got through, blocked addresses.
for name, why in ctl._zapret_proxied(verdicts):
rows.setdefault(f"proxied:{name}", {"key": f"proxied:{name}", "host": name, "kind": "proxied", "strategy": "", "status": why})
return list(rows.values())
@@ -430,6 +439,8 @@ def zapret_summary():
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
return 'Learned hostlists need zapret.engine = "zapret2".'
text = " ".join(f"{len(_lines(name))} {kind}" for kind, name in ZAPRET_LISTS)
if proxied := ctl._zapret_proxied():
text += f" {len(proxied)} via the proxy (zapret2 cannot fix them)"
if ctl.env("ZAPRET_CUTOFF_ENABLED") == "1":
text += "\n" + " ".join(line.strip() for line in _cutoff_status().splitlines()[:2])
return text
@@ -892,10 +903,11 @@ TABS = [
"zapret",
"zapret",
lambda s: "proxy-suite-zapret" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1",
[("host", "Host"), ("kind", "List"), ("strategy", "Strategy")],
[("host", "Host"), ("kind", "List"), ("strategy", "Strategy"), ("status", "Status")],
zapret_rows,
summary=zapret_summary,
actions=[
Action("t", "give zapret2 another try", lambda r, *_: ["zapret", "auto", "retry", r["host"]], when=_kind("proxied")),
Action("f", "forget it", lambda r, *_: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")),
Action("p", "pin it", lambda r, *_: ["zapret", "auto", "add", r["host"]], when=_kind("learned")),
Action("p", "unpin it", lambda r, *_: ["zapret", "auto", "unpin", r["host"]], when=_kind("pinned")),
+35
View File
@@ -1382,6 +1382,41 @@ class ZapretAutoTest(EnvTest):
self.assertIn("rkn_tcp #3, frozen", run(ctl.cmd_zapret_auto, "list")[1])
self.assertEqual(ctl._zapret_strategy_summary("notblocked.example"), "")
def test_verdicts(self):
"""What detect.lua decided: the last verdict per name and protocol stands."""
os.environ.update(ZAPRET_AUTO_ENABLED="1", ZAPRET_STATE_DIR=self.dir)
self.write("zapret-hosts-auto.txt", "www.notion.so\nchat.example\nsignal.org\n")
verdicts = self.write(
"verdicts.tsv",
"works\tnotion.so\ttcp\trkn_tcp\t1\n"
"stalls\tsignal.org\tcutoff\t\t1\n"
"works\tsignal.org\ttcp\trkn_tcp\t2\n"
"unfixable\tdiscord.com\tudp\trkn_quic\t2\n"
"unfixable\tchat.example\ttcp\trkn_tcp\t3\n"
"blocked\t149.154.167.99\tip\tno answer\t4\n"
"blocked\t203.0.113.9\tip\tno answer\t5\n"
"reachable\t203.0.113.9\tip\t\t6\n",
)
status, out, err = run(ctl.cmd_zapret_auto, "list")
self.assertEqual(status, 0)
self.assertIn("www.notion.so works", out)
self.assertIn("chat.example via the proxy: no strategy gets through", out)
self.assertIn("signal.org cut off after 16 KB: keeps the proxy's route", out)
self.assertRegex(out, r"(?m)^ discord\.com +its QUIC: no strategy gets through$")
self.assertRegex(out, r"(?m)^ 149\.154\.167\.99 +blocked by address$")
self.assertNotIn("203.0.113.9", out)
self.assertIn("zapret auto retry", err)
# retry clears it, and restarts zapret2 to unfreeze the rotation, when it runs.
self.patch("svc_active", lambda unit: False)
ok(ctl.cmd_zapret_auto, "retry", "149.154.167.99")
self.assertNotIn("149.154.167.99", [name for name, _ in ctl._zapret_proxied()])
self.assertTrue(ctl.read_text(verdicts).endswith("\n"))
self.assertIn("sends nothing", run(ctl.cmd_zapret_auto, "retry", "nothing.example")[2])
# forget drops its verdicts with it: zapret2 judges it afresh.
ok(ctl.cmd_zapret_auto, "forget", "chat.example")
self.assertNotIn("chat.example", ctl.read_text(verdicts))
self.assertIn("discord.com", ctl.read_text(verdicts))
class InboundsTest(EnvTest):
def test_stats(self):