windows: zapret2's 16 KB cutoff probe
Upstream's cutoff.nix and cutoff-probe.template.sh: z2k-detect (built from z2k's pinned source for Windows, in zapret2-extras) finds the networks this line cuts after ~16 KB, and with z2k's own strategies a whitelisted name per network; z2k-tcp16.lua inside winws2 reads the maps (Z2K_TCP16_*, their digest in the environment so a new map restarts winws2); what no name fixes goes to the zapret-cutoff rule-set for the proxy (cutoff.proxyFallback). Upstream keeps zapret2 off the probe with an nft cgroup rule. Here z2k-detect is patched to dial from a local port range (Z2K_TCP16_LOCAL_PORTS, 44000-47999, below Windows' dynamic range) and winws2 gets --wf-raw-filter leaving that range alone; under the TUN the probe and the service's own lookups of the line's network go direct. Rounds as upstream's timer: 5 min after start, every 10 min, probing when the line's network (ipinfo.io and ifconfig.co agreeing) changed or a day passed. Request::ZapretCutoff, proxy-ctl zapret cutoff [probe], a card on the DPI page. Verified live on a line that cuts (25 networks, a name for each), the Windows z2k-detect under Wine, winws2 --dry-run and --wf-save with the filter. gui-shot's scroll takes a count. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d33f05c62c
commit
803e18db9d
19 files changed
+721
-18
No files matched your search
@@ -137,9 +137,6 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
|
||||
if z.enable && z.engine == ZapretEngine::DiscordYoutube && z.discord_youtube.include_extra_upstream_lists {
|
||||
v.warn("zapret.zapret-discord-youtube.includeExtraUpstreamLists", "Flowseal's Windows release has no instagram, soundcloud or twitter list: ignored");
|
||||
}
|
||||
if z.enable && z.engine == ZapretEngine::Zapret2 && z.zapret2.cutoff.enable {
|
||||
v.warn("zapret.zapret2.cutoff.enable", "the 16 KB cutoff probe is not on Windows yet");
|
||||
}
|
||||
if z.enable && cfg.proxy.tun.enable {
|
||||
v.warn("proxy.tun.enable", "TUN and zapret together: zapret's packets are not kept off the TUN on Windows yet; use one or the other");
|
||||
}
|
||||
|
||||
@@ -109,6 +109,9 @@ pub struct Env {
|
||||
/// (`zapret.directSync`), and what it cannot, for the proxy (`zapret2.proxyFallback`).
|
||||
pub zapret2_direct_rule_set: Option<String>,
|
||||
pub zapret2_proxy_rule_set: Option<String>,
|
||||
/// The networks the 16 KB cutoff probe found cut and no name fixes, for the proxy
|
||||
/// (`zapret2.cutoff.proxyFallback`, ps_core::zapret2::cutoff_rules).
|
||||
pub zapret2_cutoff_rule_set: Option<String>,
|
||||
}
|
||||
|
||||
pub struct Input<'a> {
|
||||
|
||||
@@ -155,6 +155,14 @@ pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], w
|
||||
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-unfixable", "path": path }));
|
||||
rules.push(json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
||||
}
|
||||
// The networks that cut TLS after 16 KB, which no name fixes: by address, so only for
|
||||
// what the proxy sees by address (the TUN, per-app routing), as upstream's.
|
||||
if let Some(path) = &env.zapret2_cutoff_rule_set
|
||||
&& route.mode != super::RouteMode::AllBypass
|
||||
{
|
||||
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-cutoff", "path": path }));
|
||||
rules.push(json!({ "rule_set": ["zapret-cutoff"], "outbound": "proxy" }));
|
||||
}
|
||||
if let Some(path) = &env.zapret2_direct_rule_set
|
||||
&& !matches!(route.mode, super::RouteMode::AllBypass | super::RouteMode::AllProxy)
|
||||
{
|
||||
|
||||
@@ -514,10 +514,78 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
|
||||
if !z.ipv6 {
|
||||
opt.push("--wf-l3=ipv4".into());
|
||||
}
|
||||
// The cutoff probe measures the line itself: its connections pass winws2 untouched. (One
|
||||
// such filter only: a profile's own goes first.)
|
||||
if z.cutoff.enable && !body.iter().any(|a| a.starts_with("--wf-raw-filter")) {
|
||||
opt.push(format!("--wf-raw-filter={}", cutoff_filter()));
|
||||
}
|
||||
opt.extend(body);
|
||||
Ok(opt)
|
||||
}
|
||||
|
||||
// --- the 16 KB cutoff probe (upstream's zapret2/cutoff.nix) ---------------------------------
|
||||
|
||||
/// The local ports the cutoff probe (z2k-detect) connects from, which winws2 leaves alone, as
|
||||
/// upstream's nft rule keeps zapret2 off the probe's cgroup. Below Windows' dynamic range
|
||||
/// (49152-65535), so no other program's connection is given one of them unasked.
|
||||
pub const CUTOFF_PORTS: (u16, u16) = (44000, 47999);
|
||||
|
||||
/// winws2's filter part (`--wf-raw-filter`, ANDed with the rest) that leaves out the probe's
|
||||
/// connections: TCP from or to a local port in [`CUTOFF_PORTS`].
|
||||
pub fn cutoff_filter() -> String {
|
||||
let (lo, hi) = CUTOFF_PORTS;
|
||||
format!("not tcp or (outbound and (tcp.SrcPort < {lo} or tcp.SrcPort > {hi})) or (inbound and (tcp.DstPort < {lo} or tcp.DstPort > {hi}))")
|
||||
}
|
||||
|
||||
/// The networks (AS numbers) a probe found cut off, from its `asn.txt`: a row is one when its
|
||||
/// first field is all digits (upstream's awk; `#` lines are comments).
|
||||
pub fn cut_networks(asn: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = asn.lines().filter_map(|l| l.split('\t').next()).map(str::trim).filter(|a| is_asn(a)).map(str::to_owned).collect();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// The name that gets through, by network, from its `sni.txt` (`asn<TAB>name`).
|
||||
pub fn network_names(sni: &str) -> BTreeMap<String, String> {
|
||||
sni.lines()
|
||||
.filter_map(|l| {
|
||||
let mut f = l.split('\t');
|
||||
let (a, n) = (f.next()?.trim(), f.next().unwrap_or("").trim());
|
||||
is_asn(a).then(|| (a.to_owned(), n.to_owned()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn is_asn(a: &str) -> bool {
|
||||
!a.is_empty() && a.len() <= 10 && a.bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
fn cidr_ok(p: &str) -> bool {
|
||||
let Some((ip, len)) = p.split_once('/') else { return false };
|
||||
match (ip.parse::<std::net::IpAddr>(), len.parse::<u8>()) {
|
||||
(Ok(std::net::IpAddr::V4(_)), Ok(l)) => l <= 32,
|
||||
(Ok(std::net::IpAddr::V6(_)), Ok(l)) => l <= 128,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule-set for the proxy (`cutoff.proxyFallback`, upstream's `proxyRules`): the prefixes,
|
||||
/// from z2k's `tcp16_nets.txt` (`asn<TAB>prefix`), of every cut-off network no name fixes.
|
||||
pub fn cutoff_rules(asn: &str, sni: &str, nets: &str) -> serde_json::Value {
|
||||
let cut: std::collections::BTreeSet<String> = cut_networks(asn).into_iter().collect();
|
||||
let named = network_names(sni);
|
||||
let cidrs: Vec<&str> = nets
|
||||
.lines()
|
||||
.filter_map(|l| {
|
||||
let mut f = l.split('\t');
|
||||
let (a, p) = (f.next()?.trim(), f.next()?.trim());
|
||||
(cut.contains(a) && !named.contains_key(a) && cidr_ok(p)).then_some(p)
|
||||
})
|
||||
.collect();
|
||||
let rules = if cidrs.is_empty() { serde_json::json!([]) } else { serde_json::json!([{ "ip_cidr": cidrs }]) };
|
||||
serde_json::json!({ "version": 1, "rules": rules })
|
||||
}
|
||||
|
||||
// --- what the proxy does with zapret2's verdicts (upstream's direct-sync.template.sh) -------
|
||||
|
||||
/// An entry a rule-set can take: an IPv4 or IPv6 address, or a name of two labels at least
|
||||
@@ -631,6 +699,31 @@ pub fn routing(user: &str, auto: Option<&str>, excluded: &str, verdicts_text: &s
|
||||
(direct, json!({ "version": 1, "rules": rules }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cutoff_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_probes_maps_read_as_upstreams_awk_reads_them() {
|
||||
let asn = "# cut off on this line\n24940\n16509\n\nAS13335\n";
|
||||
assert_eq!(cut_networks(asn), ["24940", "16509"]);
|
||||
let sni = "# names\n# per network\n24940\t300.ya.ru\nx\ty\n";
|
||||
assert_eq!(network_names(sni), BTreeMap::from([("24940".to_owned(), "300.ya.ru".to_owned())]));
|
||||
let nets = "24940\t91.98.0.0/16\n16509\t3.5.0.0/16\n16509\t2600:1f00::/32\n16509\tnot-a-prefix\n13335\t104.16.0.0/16\n";
|
||||
// Hetzner has a name (z2k puts it in); Amazon none: its prefixes go to the proxy.
|
||||
assert_eq!(cutoff_rules(asn, sni, nets), serde_json::json!({ "version": 1, "rules": [{ "ip_cidr": ["3.5.0.0/16", "2600:1f00::/32"] }] }));
|
||||
assert_eq!(cutoff_rules("", sni, nets), serde_json::json!({ "version": 1, "rules": [] }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_probes_ports_are_left_out_of_winws2s_filter() {
|
||||
let f = cutoff_filter();
|
||||
assert!(f.contains("tcp.SrcPort < 44000 or tcp.SrcPort > 47999"), "{f}");
|
||||
assert!(f.starts_with("not tcp or "));
|
||||
assert!(CUTOFF_PORTS.1 < 49152, "inside Windows' dynamic port range");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -293,25 +293,29 @@ fn auto_proxy_never_routes_what_it_excludes() {
|
||||
#[test]
|
||||
fn zapret2s_rule_sets_follow_autoproxy_and_the_mode() {
|
||||
let dir = scratch("zapret2-sync");
|
||||
let (direct, proxy) = (dir.join("direct.json"), dir.join("proxy.json"));
|
||||
let (direct, proxy, cutoff) = (dir.join("direct.json"), dir.join("proxy.json"), dir.join("cutoff.json"));
|
||||
std::fs::write(&direct, r#"{"version":1,"rules":[{"domain_suffix":["fixed.example"]}]}"#).unwrap();
|
||||
std::fs::write(&proxy, r#"{"version":1,"rules":[{"domain_suffix":["unfixable.example"]}]}"#).unwrap();
|
||||
let cut = ps_core::zapret2::cutoff_rules("16509\n", "", "16509\t3.5.0.0/16\n16509\t2600:1f00::/32\n");
|
||||
std::fs::write(&cutoff, serde_json::to_vec(&cut).unwrap()).unwrap();
|
||||
let cfg = base();
|
||||
let mut e = env(&dir);
|
||||
e.windows = false;
|
||||
e.zapret2_direct_rule_set = Some(direct.to_string_lossy().into());
|
||||
e.zapret2_proxy_rule_set = Some(proxy.to_string_lossy().into());
|
||||
e.zapret2_cutoff_rule_set = Some(cutoff.to_string_lossy().into());
|
||||
let render_with = |state: &State| render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap().sing_box.unwrap();
|
||||
let sb = render_with(&State::default());
|
||||
let rules = sb["route"]["rules"].as_array().unwrap();
|
||||
let n = rules.len();
|
||||
assert_eq!(rules[n - 2], json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
||||
assert_eq!(rules[n - 3], json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
||||
assert_eq!(rules[n - 2], json!({ "rule_set": ["zapret-cutoff"], "outbound": "proxy" }));
|
||||
assert_eq!(rules[n - 1], json!({ "rule_set": ["zapret-hosts"], "outbound": "direct" }));
|
||||
check_sing_box(&sb, &dir);
|
||||
// all-proxy keeps no direct lists; all-bypass sends everything direct.
|
||||
let mut state = State { route_mode: Some(RouteMode::AllProxy), ..Default::default() };
|
||||
let tags = |sb: &Value| sb["route"]["rules"].as_array().unwrap().iter().filter_map(|r| r["rule_set"][0].as_str().map(str::to_owned)).collect::<Vec<_>>();
|
||||
assert_eq!(tags(&render_with(&state)), ["zapret-unfixable"]);
|
||||
assert_eq!(tags(&render_with(&state)), ["zapret-unfixable", "zapret-cutoff"]);
|
||||
state.route_mode = Some(RouteMode::AllBypass);
|
||||
assert!(tags(&render_with(&state)).is_empty());
|
||||
}
|
||||
Reference in new issue
Block a user