feat: zapret2 shows strategies applied
This commit is contained in:
8 files changed
+168
-14
No files matched your search
@@ -606,6 +606,8 @@ let
|
|||||||
];
|
];
|
||||||
|
|
||||||
zapret2StateDir = "${stateDir}/zapret2";
|
zapret2StateDir = "${stateDir}/zapret2";
|
||||||
|
# The running global instance's strategy map, which proxy-ctl names state.tsv's rows by.
|
||||||
|
zapret2StrategiesFile = "${runtimeDir}/proxy-suite-zapret/strategies.json";
|
||||||
# Not under zapret2/, which the zapret scope's group writes to: root works here by
|
# Not under zapret2/, which the zapret scope's group writes to: root works here by
|
||||||
# fixed names (the group asks for probes in requests/).
|
# fixed names (the group asks for probes in requests/).
|
||||||
zapret2CutoffDir = "${stateDir}/zapret2-cutoff";
|
zapret2CutoffDir = "${stateDir}/zapret2-cutoff";
|
||||||
|
|||||||
@@ -130,6 +130,7 @@ in
|
|||||||
# Only the system-wide instance reads the site lists; per-app zapret handles all traffic.
|
# Only the system-wide instance reads the site lists; per-app zapret handles all traffic.
|
||||||
ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2" && zapretGlobalEnabled);
|
ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2" && zapretGlobalEnabled);
|
||||||
ZAPRET_STATE_DIR = constants.zapret2StateDir;
|
ZAPRET_STATE_DIR = constants.zapret2StateDir;
|
||||||
|
ZAPRET_STRATEGIES_FILE = constants.zapret2StrategiesFile;
|
||||||
ZAPRET_CUTOFF_ENABLED = flag zapretCutoffEnabled;
|
ZAPRET_CUTOFF_ENABLED = flag zapretCutoffEnabled;
|
||||||
ZAPRET_CUTOFF_DIR = constants.zapret2CutoffDir;
|
ZAPRET_CUTOFF_DIR = constants.zapret2CutoffDir;
|
||||||
OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile;
|
OUTBOUND_INVENTORY_FILE = constants.outboundInventoryFile;
|
||||||
|
|||||||
@@ -149,7 +149,9 @@ in
|
|||||||
wants = [ "network-online.target" ];
|
wants = [ "network-online.target" ];
|
||||||
conflicts = awgServiceNames;
|
conflicts = awgServiceNames;
|
||||||
wantedBy = [ "multi-user.target" ];
|
wantedBy = [ "multi-user.target" ];
|
||||||
preStart = mkPreStart;
|
preStart = mkPreStart + ''
|
||||||
|
ln -sfn ${globalRuntime}/strategies.json ${constants.zapret2StrategiesFile}
|
||||||
|
'';
|
||||||
runtimeDirectory = "proxy-suite-zapret";
|
runtimeDirectory = "proxy-suite-zapret";
|
||||||
stateDirectory = "proxy-suite/zapret2";
|
stateDirectory = "proxy-suite/zapret2";
|
||||||
execStart = "${runtime.daemonScript}";
|
execStart = "${runtime.daemonScript}";
|
||||||
|
|||||||
@@ -220,6 +220,57 @@ let
|
|||||||
{ cat ${header}; printf "NFQWS2_OPT='%s'\n" "$opt"; } >"$out"
|
{ cat ${header}; printf "NFQWS2_OPT='%s'\n" "$opt"; } >"$out"
|
||||||
'';
|
'';
|
||||||
|
|
||||||
|
# {circular key: {strategy: [its desync instances]}}, for proxy-ctl to name the
|
||||||
|
# strategy state.tsv remembers. A circular without key= is keyed by its instance,
|
||||||
|
# <func>_<profile>_<nth desync of the profile>, counting profiles from 1 and
|
||||||
|
# templates apart; a profile that imports a template rotates over its strategies.
|
||||||
|
mkStrategies =
|
||||||
|
config:
|
||||||
|
pkgs.runCommand "proxy-suite-zapret2-strategies.json" { nativeBuildInputs = [ pkgs.gawk ]; } ''
|
||||||
|
. ${config}
|
||||||
|
set -f
|
||||||
|
printf '%s\n' $NFQWS2_OPT | awk '
|
||||||
|
function js(s) { gsub(/\\/, "\\\\", s); gsub(/"/, "\\\"", s); return "\"" s "\"" }
|
||||||
|
# Numeric from the start: an unset s indexes the first section as "", not 0.
|
||||||
|
BEGIN { s = 0 }
|
||||||
|
$0 == "--new" { s++; next }
|
||||||
|
/^--template=/ { tpl[substr($0, 12)] = s; istpl[s] = 1; next }
|
||||||
|
/^--import=/ { imp[s] = substr($0, 10); next }
|
||||||
|
/^--lua-desync=/ {
|
||||||
|
fn[s]++
|
||||||
|
spec = substr($0, 14)
|
||||||
|
if (spec ~ /^circular(:|$)/) {
|
||||||
|
circ[s] = fn[s]
|
||||||
|
if (match(spec, /:key=[^:]+/)) key[s] = substr(spec, RSTART + 5, RLENGTH - 5)
|
||||||
|
} else if (match(spec, /:strategy=[0-9]+/)) {
|
||||||
|
n = substr(spec, RSTART + 10, RLENGTH - 10)
|
||||||
|
spec = substr(spec, 1, RSTART - 1) substr(spec, RSTART + RLENGTH)
|
||||||
|
if (!((s, n) in strat)) order[s] = order[s] " " n
|
||||||
|
strat[s, n] = ((s, n) in strat ? strat[s, n] "," : "") js(spec)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
END {
|
||||||
|
printf "{"
|
||||||
|
for (i = 0; i <= s; i++) {
|
||||||
|
if (istpl[i]) continue
|
||||||
|
p++
|
||||||
|
if (!(i in circ)) continue
|
||||||
|
k = (i in key) ? key[i] : "circular_" p "_" circ[i]
|
||||||
|
src = (i in imp && imp[i] in tpl) ? tpl[imp[i]] : ""
|
||||||
|
printf "%s%s:{", (out++ ? "," : ""), js(k)
|
||||||
|
m = 0
|
||||||
|
for (pass = 0; pass < 2; pass++) {
|
||||||
|
j = pass ? src : i
|
||||||
|
if (j == "") continue
|
||||||
|
c = split(order[j], ns, " ")
|
||||||
|
for (x = 1; x <= c; x++) printf "%s%s:[%s]", (m++ ? "," : ""), js(ns[x]), strat[j, ns[x]]
|
||||||
|
}
|
||||||
|
printf "}"
|
||||||
|
}
|
||||||
|
print "}"
|
||||||
|
}' >"$out"
|
||||||
|
'';
|
||||||
|
|
||||||
# Keep desync off TUN interfaces (it breaks proxied handshakes), off per-app
|
# Keep desync off TUN interfaces (it breaks proxied handshakes), off per-app
|
||||||
# traffic, and off exempted subnets (e.g. NATed VMs whose traffic it would break).
|
# traffic, and off exempted subnets (e.g. NATed VMs whose traffic it would break).
|
||||||
mkCustomScript =
|
mkCustomScript =
|
||||||
@@ -291,16 +342,18 @@ let
|
|||||||
customScript ? null,
|
customScript ? null,
|
||||||
...
|
...
|
||||||
}@args:
|
}@args:
|
||||||
|
let
|
||||||
|
config = mkConfig (
|
||||||
|
builtins.removeAttrs args [
|
||||||
|
"name"
|
||||||
|
"customScript"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
in
|
||||||
pkgs.runCommand name { } ''
|
pkgs.runCommand name { } ''
|
||||||
mkdir -p "$out/init.d/sysv/custom.d"
|
mkdir -p "$out/init.d/sysv/custom.d"
|
||||||
cp ${
|
cp ${config} "$out/config"
|
||||||
mkConfig (
|
cp ${mkStrategies config} "$out/strategies.json"
|
||||||
builtins.removeAttrs args [
|
|
||||||
"name"
|
|
||||||
"customScript"
|
|
||||||
]
|
|
||||||
)
|
|
||||||
} "$out/config"
|
|
||||||
${lib.optionalString (customScript != null) ''
|
${lib.optionalString (customScript != null) ''
|
||||||
cp ${customScript} "$out/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
|
cp ${customScript} "$out/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
|
||||||
''}
|
''}
|
||||||
|
|||||||
@@ -142,6 +142,7 @@ in
|
|||||||
{
|
{
|
||||||
nativeBuildInputs = [
|
nativeBuildInputs = [
|
||||||
pkgs.gnugrep
|
pkgs.gnugrep
|
||||||
|
pkgs.jq
|
||||||
pkgs.lua
|
pkgs.lua
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -216,6 +217,15 @@ in
|
|||||||
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"
|
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"
|
||||||
grep -qF -- '/lists/whitelist.txt --hostlist-exclude=/var/lib/proxy-suite/zapret2/zapret-hosts-user-exclude.txt' "${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
|
||||||
|
# others by instance, a template's strategies under the profile importing it.
|
||||||
|
jq -e '.rkn_tcp["1"] | map(split(":")[0]) == ["tls_client_hello_clone", "fake", "multisplit"]' "${z2kRuntime}/strategies.json"
|
||||||
|
jq -e '.cf_extra == .rkn_tcp' "${z2kRuntime}/strategies.json"
|
||||||
|
jq -e '.http_rkn["1"] == ["http_methodeol:payload=http_req:dir=out"]' "${z2kRuntime}/strategies.json"
|
||||||
|
jq -e 'has("yt_tcp") and has("gv_tcp") and has("yt_quic")' "${z2kRuntime}/strategies.json"
|
||||||
|
jq -e 'keys == ["circular_1_1", "circular_3_1"]' "${globalRuntime}/strategies.json"
|
||||||
|
if grep -qF 'strategy=' "${z2kRuntime}/strategies.json"; then exit 1; fi
|
||||||
|
|
||||||
# z2k's Lua in its own order: ranges (repeats=6-10) resolve before its strategies fire.
|
# z2k's Lua in its own order: ranges (repeats=6-10) resolve before its strategies fire.
|
||||||
grep -qE -- 'z2k-fooling-ext\.lua --lua-init=@[^ ]+/z2k-range-rand\.lua --lua-init=@[^ ]+/z2k-modern-core\.lua' "${z2kRuntime}/config"
|
grep -qE -- 'z2k-fooling-ext\.lua --lua-init=@[^ ]+/z2k-range-rand\.lua --lua-init=@[^ ]+/z2k-modern-core\.lua' "${z2kRuntime}/config"
|
||||||
|
|
||||||
|
|||||||
@@ -3618,6 +3618,54 @@ def _zapret_strategy_drop(domain):
|
|||||||
_replace_lines(path, keep)
|
_replace_lines(path, keep)
|
||||||
|
|
||||||
|
|
||||||
|
def _zapret_strategy_rows():
|
||||||
|
"""state.tsv as (key, host, strategy, mode, sni): the strategy each profile's rotation
|
||||||
|
settled on per domain. The host may carry a |4 or |6 address family."""
|
||||||
|
rows = []
|
||||||
|
for fields in _tsv(_zapret_auto_file("circular/state.tsv")):
|
||||||
|
if len(fields) < 3 or fields[0].startswith("#") or not fields[2].isdigit():
|
||||||
|
continue
|
||||||
|
fields += [""] * (6 - len(fields))
|
||||||
|
rows.append((fields[0], fields[1].split("|", 1)[0], fields[2], fields[4], fields[5]))
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def _zapret_strategies_for(domain, rows=None):
|
||||||
|
"""The rows for domain: circular keys them by the domain it rotates on, usually the apex."""
|
||||||
|
return [r for r in (_zapret_strategy_rows() if rows is None else rows) if r[1] and (domain == r[1] or domain.endswith(f".{r[1]}"))]
|
||||||
|
|
||||||
|
|
||||||
|
def _zapret_strategy_map():
|
||||||
|
"""{key: {strategy: [desync instances]}} of the running global instance, or {}."""
|
||||||
|
return read_json_or(env("ZAPRET_STRATEGIES_FILE"), {})
|
||||||
|
|
||||||
|
|
||||||
|
def _zapret_strategy_specs(row, strategies):
|
||||||
|
specs = strategies.get(row[0])
|
||||||
|
specs = specs.get(row[2]) if isinstance(specs, dict) else None
|
||||||
|
return [s for s in specs if isinstance(s, str)] if isinstance(specs, list) else []
|
||||||
|
|
||||||
|
|
||||||
|
def _zapret_strategy_text(row, strategies):
|
||||||
|
""""rkn_tcp #3 (fake + multisplit)": the profile's key, the strategy number, what it does."""
|
||||||
|
key, _, n, mode, sni = row
|
||||||
|
text = f"{key} #{n}"
|
||||||
|
names = " + ".join(dict.fromkeys(s.split(":", 1)[0] for s in _zapret_strategy_specs(row, strategies)))
|
||||||
|
if names:
|
||||||
|
text += f" ({names})"
|
||||||
|
if mode == "frozen":
|
||||||
|
text += ", frozen"
|
||||||
|
if sni:
|
||||||
|
text += f", fake SNI {sni}"
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def _zapret_strategy_summary(domain, rows=None, strategies=None):
|
||||||
|
"""Every strategy remembered for domain, "; "-joined, or ""."""
|
||||||
|
strategies = _zapret_strategy_map() if strategies is None else strategies
|
||||||
|
return "; ".join(_zapret_strategy_text(r, strategies) for r in _zapret_strategies_for(domain, rows))
|
||||||
|
|
||||||
|
|
||||||
def _truncate(path):
|
def _truncate(path):
|
||||||
_replace_lines(path, lambda _: False)
|
_replace_lines(path, lambda _: False)
|
||||||
|
|
||||||
@@ -3643,10 +3691,14 @@ def cmd_zapret_auto(verb="list", domain="", *_):
|
|||||||
if verb in ("add", "forget", "exclude", "unpin", "include") and not _zapret_auto_host(domain):
|
if verb in ("add", "forget", "exclude", "unpin", "include") and not _zapret_auto_host(domain):
|
||||||
usage(f"zapret auto {verb} <domain>")
|
usage(f"zapret auto {verb} <domain>")
|
||||||
if verb == "list":
|
if verb == "list":
|
||||||
if os.path.isfile(auto) and os.path.getsize(auto) > 0:
|
hosts = [h for h in lines(read_text(auto)) if h] if os.path.isfile(auto) else []
|
||||||
sys.stdout.write(read_text(auto))
|
if not hosts:
|
||||||
else:
|
|
||||||
print("No hostnames learned yet.")
|
print("No hostnames learned yet.")
|
||||||
|
rows, strategies = _zapret_strategy_rows(), _zapret_strategy_map()
|
||||||
|
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)
|
||||||
elif verb == "add":
|
elif verb == "add":
|
||||||
_zapret_auto_edit(user, domain, "add")
|
_zapret_auto_edit(user, domain, "add")
|
||||||
print(f"Pinned {domain}: zapret treats it as blocked.")
|
print(f"Pinned {domain}: zapret treats it as blocked.")
|
||||||
@@ -3924,6 +3976,12 @@ def cmd_where(domain="", *_):
|
|||||||
verdict = verdict or "direct, with the zapret bypass"
|
verdict = verdict or "direct, with the zapret bypass"
|
||||||
else:
|
else:
|
||||||
_where_row("zapret", "not learned, not pinned, not excluded")
|
_where_row("zapret", "not learned, not pinned, not excluded")
|
||||||
|
# Remembered for hosts a source's own lists cover too, learned or not.
|
||||||
|
strategies = _zapret_strategy_map()
|
||||||
|
for row in _zapret_strategies_for(domain):
|
||||||
|
_where_row("strategy", _zapret_strategy_text(row, strategies))
|
||||||
|
for spec in _zapret_strategy_specs(row, strategies):
|
||||||
|
_where_row("", f" --lua-desync={spec}")
|
||||||
|
|
||||||
if local:
|
if local:
|
||||||
zapret = verdict == "direct, with the zapret bypass"
|
zapret = verdict == "direct, with the zapret bypass"
|
||||||
|
|||||||
@@ -394,9 +394,11 @@ def zapret_rows(_):
|
|||||||
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
|
if ctl.env("ZAPRET_AUTO_ENABLED") != "1":
|
||||||
return []
|
return []
|
||||||
rows = {}
|
rows = {}
|
||||||
|
strategy_rows, strategies = ctl._zapret_strategy_rows(), ctl._zapret_strategy_map()
|
||||||
for kind, name in ZAPRET_LISTS:
|
for kind, name in ZAPRET_LISTS:
|
||||||
for host in _lines(name):
|
for host in _lines(name):
|
||||||
rows.setdefault(f"{kind}:{host}", {"key": f"{kind}:{host}", "host": host, "kind": kind})
|
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})
|
||||||
return list(rows.values())
|
return list(rows.values())
|
||||||
|
|
||||||
|
|
||||||
@@ -840,7 +842,7 @@ TABS = [
|
|||||||
"zapret",
|
"zapret",
|
||||||
"zapret",
|
"zapret",
|
||||||
lambda s: "proxy-suite-zapret" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1",
|
lambda s: "proxy-suite-zapret" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1",
|
||||||
[("host", "Host"), ("kind", "List")],
|
[("host", "Host"), ("kind", "List"), ("strategy", "Strategy")],
|
||||||
zapret_rows,
|
zapret_rows,
|
||||||
summary=zapret_summary,
|
summary=zapret_summary,
|
||||||
actions=[
|
actions=[
|
||||||
|
|||||||
@@ -1222,6 +1222,32 @@ class ZapretAutoTest(EnvTest):
|
|||||||
ok(ctl.cmd_zapret_auto, "forget", "2001:db8::1")
|
ok(ctl.cmd_zapret_auto, "forget", "2001:db8::1")
|
||||||
self.assertIn("zapret auto add <domain>", run(ctl.cmd_zapret_auto, "add", "1.2.3")[2])
|
self.assertIn("zapret auto add <domain>", run(ctl.cmd_zapret_auto, "add", "1.2.3")[2])
|
||||||
|
|
||||||
|
def test_list_names_the_strategy_remembered_for_the_apex(self):
|
||||||
|
os.environ.update(ZAPRET_AUTO_ENABLED="1", ZAPRET_STATE_DIR=self.dir)
|
||||||
|
self.write("zapret-hosts-auto.txt", "www.blocked.example\nnew.example\n")
|
||||||
|
self.write(
|
||||||
|
"circular/state.tsv",
|
||||||
|
"# key\thost\tstrategy\tts\tmode\tsni\n"
|
||||||
|
"rkn_tcp\tblocked.example\t3\t1\tfrozen\t\n"
|
||||||
|
"http_rkn\tblocked.example|4\t2\t1\tauto\thcaptcha.com\n",
|
||||||
|
)
|
||||||
|
os.environ["ZAPRET_STRATEGIES_FILE"] = self.write(
|
||||||
|
"strategies.json",
|
||||||
|
{"rkn_tcp": {"3": ["fake:blob=x:repeats=6", "multisplit:pos=1", "fake:blob=y"]}},
|
||||||
|
)
|
||||||
|
out = run(ctl.cmd_zapret_auto, "list")[1].splitlines()
|
||||||
|
self.assertEqual(
|
||||||
|
out,
|
||||||
|
[
|
||||||
|
"www.blocked.example rkn_tcp #3 (fake + multisplit), frozen; http_rkn #2, fake SNI hcaptcha.com",
|
||||||
|
"new.example",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
# A missing or unreadable map still names the profile and the number.
|
||||||
|
os.environ["ZAPRET_STRATEGIES_FILE"] = self.path("gone.json")
|
||||||
|
self.assertIn("rkn_tcp #3, frozen", run(ctl.cmd_zapret_auto, "list")[1])
|
||||||
|
self.assertEqual(ctl._zapret_strategy_summary("notblocked.example"), "")
|
||||||
|
|
||||||
|
|
||||||
class InboundsTest(EnvTest):
|
class InboundsTest(EnvTest):
|
||||||
def test_stats(self):
|
def test_stats(self):
|
||||||
|
|||||||
Reference in new issue
Block a user