feat: zapret2 lists domain for learned to proxy ips

This commit is contained in:
FUFSoB committed 2026-10-06 20:42:00 +05:00
1 parent 57fdbf3e08
commit 91f2397ac5
7 files changed
+87 -8

No files matched your search

+2 -1
View File
@@ -34,7 +34,8 @@ 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).
(TUN, TProxy, per-app routing). `proxy-ctl zapret auto` names such an address by the sites
looked up to it, when systemd-resolved still had them cached as it was blocked.
```nix
services.proxy-suite = {
+1
View File
@@ -152,6 +152,7 @@ in
ZAPRET_STRATEGIES_FILE = constants.zapret2StrategiesFile;
ZAPRET_CUTOFF_ENABLED = flag zapretCutoffEnabled;
ZAPRET_CUTOFF_DIR = constants.zapret2CutoffDir;
ZAPRET_DIRECT_DIR = constants.zapret2DirectDir;
OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile;
RUNTIME_OUTBOUNDS_DIR = constants.runtimeOutboundsDir;
RUNTIME_SUBS_DIR = constants.runtimeSubscriptionsDir;
+5 -2
View File
@@ -1,8 +1,9 @@
# 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.
# fix, for the proxy to carry (zapret2.proxyFallback); and names.tsv, the names the
# addresses blocked outright were looked up by, for proxy-ctl. Rebuilt whenever a host
# list or a verdict changes; sing-box reloads them on the rename.
{
lib,
pkgs,
@@ -21,6 +22,8 @@ let
pkgs.coreutils
pkgs.diffutils
pkgs.jq
# resolvectl: the names of the addresses blocked outright.
pkgs.systemd
];
}
);
@@ -1,4 +1,5 @@
# $1: zapret2's state directory, $2: the directory to write the two rule-sets to.
# $1: zapret2's state directory, $2: the directory to write the two rule-sets to; $3, the
# checks': a dump to read in place of systemd-resolved's cache.
# 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
@@ -6,12 +7,17 @@
# 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").
# names.tsv: "address<TAB>names" of each address blocked outright, for proxy-ctl: no
# connection to it got far enough to name its site, but the lookups before them did. The
# names systemd-resolved's cache has it under, a CNAME followed back to the name asked
# for; read once, as its verdict lands, while the cache still holds them ("" for none).
# 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
out=$2
cache=${3:-}
# The zapret scope's group writes these: never through a symlink it left (to a file only
# root may read, which would land in the world-readable rule-sets), nor into a FIFO.
@@ -93,3 +99,38 @@ jq -n -c --rawfile verdicts <(lists "$dir/verdicts.tsv") "$hosts"'
+ [($v | named("blocked"; "ip")) + ($tcp | map(select(ip))) | select(length > 0) | {ip_cidr: cidr}])}
' >"$out/proxy.json.tmp"
write "$out/proxy.json"
names='def blocked: verdicts | named("blocked"; "ip") | unique;
def known: split("\n") | map(split("\t") | select(length == 2) | {key: .[0], value: .[1]}) | from_entries;
# resolvectl show-cache: "name IN A address", "alias IN CNAME name".
def records: split("\n")
| map(capture("^\\s*(?<name>\\S+)\\s+IN\\s+(?<type>A|AAAA|CNAME)\\s+(?<data>\\S+)\\s*$")
| .name |= (ascii_downcase | rtrimstr(".")) | .data |= (ascii_downcase | rtrimstr(".")));
def aliased($aliases): . as $s | ($s + [$aliases[] | select(.data | IN($s[])) | .name] | unique)
| if . == $s then . else aliased($aliases) end;
# The names asked for: those no other name of the chain is an alias for.
def asked($aliases): . as $all | map(select(. as $n | any($aliases[]; .data == $n and (.name | IN($all[]))) | not));'
# The resolver is asked only for an address it has not been asked about yet.
missing=$(jq -n -r --rawfile verdicts <(lists "$dir/verdicts.tsv") --rawfile known <(lists "$out/names.tsv") \
"$hosts$names"'($verdicts | blocked) - ($known | known | keys) | .[]')
dump() {
if [ -z "$missing" ]; then
true
elif [ -n "$cache" ]; then
lists "$cache"
else
timeout 2 resolvectl show-cache 2>/dev/null || true
fi
}
jq -n -r --rawfile verdicts <(lists "$dir/verdicts.tsv") --rawfile known <(lists "$out/names.tsv") \
--rawfile cache <(dump) "$hosts$names"'
($known | known) as $known
| ($cache | records) as $records
| ($records | map(select(.type == "CNAME"))) as $aliases
| $verdicts | blocked | .[] as $ip
| "\($ip)\t\($known[$ip] // ([$records[] | select(.type != "CNAME" and .data == $ip) | .name] | unique
| aliased($aliases) | asked($aliases) | map(select(hostname)) | .[:4] | join(",")))"
' >"$out/names.tsv.tmp"
write "$out/names.tsv"
+10 -2
View File
@@ -493,14 +493,22 @@ in
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
# systemd-resolved's cache, as resolvectl show-cache prints it.
printf 'Scope protocol=dns family=AF_INET ifindex=2 ifname=eth0\n%s\n%s\n%s\n%s\n' \
'www.example.com IN CNAME edge.cdn.example.net.' 'edge.cdn.example.net IN A 149.154.167.99' \
'Other.Example IN A 149.154.167.99' 'gone.example IN A 198.51.100.1' >dns-cache
${directSync} direct-lists out dns-cache
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"]}]}'
# A blocked address by the names asked for, a CNAME followed back; looked up once.
test "$(cat out/names.tsv)" = "$(printf '149.154.167.99\tother.example,www.example.com')"
# Unchanged, the files stay as they were: sing-box reloads on every rename.
inode=$(stat -c %i out/direct.json)
${directSync} direct-lists out
: >dns-cache
${directSync} direct-lists out dns-cache
test "$(stat -c %i out/direct.json)" = "$inode"
test "$(cat out/names.tsv)" = "$(printf '149.154.167.99\tother.example,www.example.com')"
${directSync} empty-lists empty-out
test "$(cat empty-out/direct.json)" = '{"version":1,"rules":[]}'
test "$(cat empty-out/proxy.json)" = '{"version":1,"rules":[]}'
+21 -1
View File
@@ -3898,6 +3898,11 @@ def _zapret_cutoff_dir():
return env("ZAPRET_CUTOFF_DIR", f"{state_dir()}/zapret2-cutoff")
def _zapret_direct_dir():
"""Root's rule-sets from zapret2's state (zapret2/direct-sync.template.sh)."""
return env("ZAPRET_DIRECT_DIR", f"{state_dir()}/zapret2-direct")
def _zapret_auto_file(name):
return os.path.join(_zapret_state_dir(), name)
@@ -4112,11 +4117,26 @@ def _zapret_status(host, verdicts=None):
return ", ".join(parts)
def _zapret_looked_up():
"""{address: [names]}: what the addresses blocked outright were looked up by."""
return {
fields[0]: [name for name in fields[1].split(",") if name]
for fields in _tsv(os.path.join(_zapret_direct_dir(), "names.tsv"))
if len(fields) == 2
}
def _zapret_proxied(verdicts=None):
"""[(name, why)] the proxy carries because zapret2 cannot fix them."""
verdicts = _zapret_verdicts() if verdicts is None else verdicts
looked_up = _zapret_looked_up()
def why(name, proto):
names = looked_up.get(name) if proto == "ip" else None
return f"{ZAPRET_PROXIED[proto]} ({', '.join(names)})" if names else ZAPRET_PROXIED[proto]
return [
(name, ZAPRET_PROXIED[proto])
(name, why(name, proto))
for (name, proto), kind in sorted(verdicts.items())
if (kind, proto) in (("unfixable", "tcp"), ("unfixable", "udp"), ("blocked", "ip"))
]
+6 -1
View File
@@ -1636,8 +1636,12 @@ class ZapretAutoTest(EnvTest):
"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",
"reachable\t203.0.113.9\tip\t\t6\n"
"blocked\t198.51.100.4\tip\tno answer\t7\n",
)
# The names an address was looked up by, from root's direct-sync; none for some.
os.environ["ZAPRET_DIRECT_DIR"] = self.path("direct")
self.write("direct/names.tsv", "149.154.167.99\t\n198.51.100.4\tapi.example,cdn.example\n")
status, out, err = run(ctl.cmd_zapret_auto, "list")
self.assertEqual(status, 0)
self.assertIn("www.notion.so works", out)
@@ -1645,6 +1649,7 @@ class ZapretAutoTest(EnvTest):
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.assertRegex(out, r"(?m)^ 198\.51\.100\.4 +blocked by address \(api\.example, cdn\.example\)$")
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.