windows: zapret2's verdicts route the proxy; options kept to what they are
As upstream's direct-sync: from zapret2's lists and the detector's verdicts, two rule-sets sing-box reloads, rebuilt every ten seconds and before it starts: what zapret2 cannot fix (every strategy failed for a site, or an address leaves connections unanswered) through the proxy (zapret2.proxyFallback), after the explicit rules and autoProxy's; what it fixes direct, so it sees it (directSync), unless learned from transfers cut short. all-bypass and all-proxy as upstream. The options file winws2 reads (one a line) refuses an option holding a control character, which would read as more options than it is; and zapret2.ports.extraTcp/extraUdp, which join its options as written, are ports or ranges within 1-65535 (validated, and filtered again). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9eed225ccc
commit
514ffb97ca
10 files changed
+305
-27
No files matched your search
@@ -137,13 +137,8 @@ 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 {
|
||||
if z.zapret2.proxy_fallback {
|
||||
v.warn("zapret.zapret2.proxyFallback", "the proxy carrying what zapret2 cannot fix is not on Windows yet: such sites stay direct");
|
||||
}
|
||||
if z.zapret2.cutoff.enable {
|
||||
v.warn("zapret.zapret2.cutoff.enable", "the 16 KB cutoff probe is not on Windows yet");
|
||||
}
|
||||
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");
|
||||
@@ -504,6 +499,26 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
|
||||
|
||||
fn zapret(cfg: &Config, v: &mut Issues) {
|
||||
let z = &cfg.zapret;
|
||||
// They join winws2's options as written.
|
||||
let p = &z.zapret2.ports;
|
||||
for (path, values) in [("zapret.zapret2.ports.extraTcp", &p.extra_tcp), ("zapret.zapret2.ports.extraUdp", &p.extra_udp)] {
|
||||
for value in values {
|
||||
let text = match value {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
if !crate::zapret2::port_spec_ok(text.trim()) {
|
||||
v.error(path, format!("'{text}' is not a port or a range (N, or N-M, within 1-65535)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (path, list) in [("zapret.zapret2.ports.tcp", &p.tcp), ("zapret.zapret2.ports.udp", &p.udp)] {
|
||||
if let Some(list) = list
|
||||
&& !list.split(',').all(|x| crate::zapret2::port_spec_ok(x.trim().replace(':', "-").as_str()))
|
||||
{
|
||||
v.error(path, "ports and ranges, comma-separated (N, or N-M, within 1-65535)");
|
||||
}
|
||||
}
|
||||
if !z.enable {
|
||||
return;
|
||||
}
|
||||
@@ -773,6 +788,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zapret2_extra_ports_are_ports() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.zapret.zapret2.ports.extra_tcp = vec![serde_json::json!(8443), serde_json::json!("50000-50099"), serde_json::json!("443\n--lua-init=@x.lua")];
|
||||
cfg.zapret.zapret2.ports.udp = Some("443,590:600".into());
|
||||
let errs = errors(&cfg);
|
||||
assert_eq!(errs.iter().filter(|e| e.starts_with("zapret.zapret2.ports")).count(), 1, "{errs:?}");
|
||||
assert!(crate::zapret2::port_spec_ok("1-65535") && !crate::zapret2::port_spec_ok("0") && !crate::zapret2::port_spec_ok("9-1") && !crate::zapret2::port_spec_ok("443 x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitelist_bypass_names_are_checked_while_it_is_off() {
|
||||
let mut cfg = Config::default();
|
||||
|
||||
@@ -105,6 +105,10 @@ pub struct Env {
|
||||
pub windows: bool,
|
||||
/// Where autoProxy's learned rule-sets are (one file per exit), when it runs.
|
||||
pub autoproxy_rules_dir: Option<String>,
|
||||
/// zapret2's rule-sets (ps_core::zapret2::routing): what it fixes, sent direct
|
||||
/// (`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>,
|
||||
}
|
||||
|
||||
pub struct Input<'a> {
|
||||
|
||||
@@ -146,6 +146,21 @@ pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], w
|
||||
let mut rule_sets = route.rule_set;
|
||||
let mut dns_rules = route.dns_rules;
|
||||
autoproxy::apply(input, probe_exits, &mut inbounds, &mut rules, route.pin_at, &mut rule_sets, &mut dns_rules, route.mode);
|
||||
// zapret2's: what it cannot fix through the proxy, after the explicit rules and autoProxy's,
|
||||
// ahead of the hosts it does fix, which go direct so it sees them. all-bypass sends
|
||||
// everything direct, and all-proxy keeps no direct lists.
|
||||
if let Some(path) = &env.zapret2_proxy_rule_set
|
||||
&& route.mode != super::RouteMode::AllBypass
|
||||
{
|
||||
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-unfixable", "path": path }));
|
||||
rules.push(json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
||||
}
|
||||
if let Some(path) = &env.zapret2_direct_rule_set
|
||||
&& !matches!(route.mode, super::RouteMode::AllBypass | super::RouteMode::AllProxy)
|
||||
{
|
||||
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-hosts", "path": path }));
|
||||
rules.push(json!({ "rule_set": ["zapret-hosts"], "outbound": "direct" }));
|
||||
}
|
||||
let after_sniff = rules.iter().position(|r| r["action"] == "sniff").map_or(0, |i| i + 1);
|
||||
rules.insert(after_sniff, json!({ "inbound": ["proxy-suite-test-in"], "outbound": "proxy-suite-test" }));
|
||||
if hybrid {
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
//! zapret2 on Windows: winws2 (WinDivert) with the strategies upstream's module gives nfqws2
|
||||
//! (NFQUEUE). The strategy source is nfqws2-keenetic, read and patched as upstream's
|
||||
//! `zapret2/sources.nix` does; the profiles, markers, circular defaults and ports follow
|
||||
//! upstream's `zapret2/runtime.nix` and zapret2's own `common/list.sh`.
|
||||
//! (NFQUEUE): nfqws2-keenetic's, read and patched as upstream's `zapret2/sources.nix` does, or
|
||||
//! z2k's, made by its own generator (tools/build-zapret2-extras.sh); the profiles, markers,
|
||||
//! circular defaults, ports and Lua layers follow upstream's `zapret2/runtime.nix`, and the
|
||||
//! routing by the detector's verdicts its `direct-sync.template.sh`.
|
||||
//!
|
||||
//! What differs on Windows: WinDivert's port filters (`--wf-tcp-out`, `--wf-udp-out`) take
|
||||
//! the place of the queue's rules, and there are no marks. winws2 drops to Low integrity once
|
||||
//! it runs, so the learned list lives in a directory the service labels Low for it (winws2's
|
||||
//! own `--writable` insists on making the directory, which must already hold the list).
|
||||
//! Learning is nfqws2's own autohostlist; upstream's detector (`detect.lua`,
|
||||
//! `extendedDetection`) and z2k come later.
|
||||
//! the place of the queue's rules, a filter part hands the detectors the server's TLS
|
||||
//! records in place of the queue's packet windows, and there are no marks. winws2 drops to
|
||||
//! Low integrity once it runs, so what it writes lives in a directory the service labels Low
|
||||
//! for it (winws2's own `--writable` insists on making the directory).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::config::{StrategySource, Zapret2};
|
||||
|
||||
@@ -297,13 +299,25 @@ fn circular_fill(z: &Zapret2, token: &str) -> String {
|
||||
t
|
||||
}
|
||||
|
||||
/// A port or a range as winws2 takes one: `N` or `N-M`, within 1-65535.
|
||||
pub fn port_spec_ok(spec: &str) -> bool {
|
||||
let num = |s: &str| !s.is_empty() && s.len() <= 5 && s.chars().all(|c| c.is_ascii_digit()) && s.parse::<u32>().is_ok_and(|n| (1..=65535).contains(&n));
|
||||
match spec.split_once('-') {
|
||||
Some((a, b)) => num(a) && num(b) && a.parse::<u32>().ok() <= b.parse::<u32>().ok(),
|
||||
None => num(spec),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ports.extraTcp`/`extraUdp` as winws2's list: numbers and ranges alone (validated already;
|
||||
/// anything else dropped here too, as it joins winws2's options).
|
||||
fn port_list(values: &[serde_json::Value]) -> String {
|
||||
values
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
serde_json::Value::String(s) => s.trim().to_owned(),
|
||||
other => other.to_string(),
|
||||
})
|
||||
.filter(|s| port_spec_ok(s))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
@@ -504,6 +518,119 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
|
||||
Ok(opt)
|
||||
}
|
||||
|
||||
// --- 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
|
||||
/// (a bare "com" would send the whole TLD past the proxy). The zapret scope writes the lists.
|
||||
fn host_valid(h: &str) -> bool {
|
||||
if let Ok(ip) = h.parse::<std::net::IpAddr>() {
|
||||
return ip.is_ipv4() || !h.contains('%');
|
||||
}
|
||||
let label_ok = |l: &str| {
|
||||
!l.is_empty()
|
||||
&& l.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
|
||||
&& !l.starts_with('-')
|
||||
&& !l.ends_with('-')
|
||||
};
|
||||
h.len() <= 253 && h.contains('.') && h.split('.').all(label_ok) && !h.chars().all(|c| c.is_ascii_digit() || c == '.')
|
||||
}
|
||||
|
||||
/// nfqws hostlists: one host a line, `#` comments, `^` for the name alone.
|
||||
fn hosts(text: &str) -> Vec<String> {
|
||||
text.lines()
|
||||
.map(|l| l.trim().to_ascii_lowercase())
|
||||
.map(|l| l.trim_start_matches('^').to_owned())
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#') && host_valid(l))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// detect.lua's verdicts ("kind<TAB>name<TAB>proto<TAB>..."), the last per name and proto:
|
||||
/// (name, proto) -> kind.
|
||||
fn verdicts(text: &str) -> BTreeMap<(String, String), String> {
|
||||
let mut out = BTreeMap::new();
|
||||
for line in text.lines() {
|
||||
let f: Vec<&str> = line.split('\t').collect();
|
||||
if f.len() < 3 || !host_valid(f[1]) {
|
||||
continue;
|
||||
}
|
||||
out.insert((f[1].to_owned(), f[2].to_owned()), f[0].to_owned());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn named(v: &BTreeMap<(String, String), String>, kind: &str, proto: &str) -> Vec<String> {
|
||||
v.iter().filter(|((_, p), k)| k.as_str() == kind && p == proto).map(|((n, _), _)| n.clone()).collect()
|
||||
}
|
||||
|
||||
/// A name and a site key cover each other either way round: www.notion.so and notion.so.
|
||||
fn covers(a: &str, b: &str) -> bool {
|
||||
a == b || a.ends_with(&format!(".{b}")) || b.ends_with(&format!(".{a}"))
|
||||
}
|
||||
|
||||
fn is_ip(h: &str) -> bool {
|
||||
h.parse::<std::net::IpAddr>().is_ok()
|
||||
}
|
||||
|
||||
fn cidr(ips: &[String]) -> Vec<String> {
|
||||
ips.iter().map(|ip| if ip.contains(':') { format!("{ip}/128") } else { format!("{ip}/32") }).collect()
|
||||
}
|
||||
|
||||
/// The two rule-sets the proxy routes by, from zapret2's lists and its detector's verdicts:
|
||||
/// `direct`, the hosts zapret2 handles, sent direct so it sees them (the pinned ones, and the
|
||||
/// learned ones once a strategy got through for them, unless learned from transfers cut short);
|
||||
/// `proxy`, what it cannot fix, for the proxy to carry (sites every strategy failed for, all
|
||||
/// of a site's TCP or only its QUIC, and addresses that leave connections unanswered).
|
||||
/// `auto` is the learned list, none when learning is off.
|
||||
pub fn routing(user: &str, auto: Option<&str>, excluded: &str, verdicts_text: &str) -> (serde_json::Value, serde_json::Value) {
|
||||
use serde_json::json;
|
||||
let v = verdicts(verdicts_text);
|
||||
let works = named(&v, "works", "tcp");
|
||||
// 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.
|
||||
let stalls = named(&v, "stalls", "cutoff");
|
||||
let excluded = hosts(excluded);
|
||||
let mut direct: Vec<String> = hosts(user);
|
||||
direct.extend(
|
||||
hosts(auto.unwrap_or(""))
|
||||
.into_iter()
|
||||
.filter(|h| works.iter().any(|w| covers(h, w)) && !stalls.iter().any(|s| covers(h, s))),
|
||||
);
|
||||
direct.sort();
|
||||
direct.dedup();
|
||||
direct.retain(|h| !excluded.contains(h));
|
||||
let (ips, names): (Vec<String>, Vec<String>) = direct.into_iter().partition(|h| is_ip(h));
|
||||
let mut rules = Vec::new();
|
||||
if !names.is_empty() {
|
||||
rules.push(json!({ "domain_suffix": names }));
|
||||
}
|
||||
if !ips.is_empty() {
|
||||
rules.push(json!({ "ip_cidr": cidr(&ips) }));
|
||||
}
|
||||
let direct = json!({ "version": 1, "rules": rules });
|
||||
|
||||
// A site keyed by its address (no name seen) goes by address.
|
||||
let tcp = named(&v, "unfixable", "tcp");
|
||||
let udp = named(&v, "unfixable", "udp");
|
||||
let (tcp_ips, tcp_names): (Vec<String>, Vec<String>) = tcp.into_iter().partition(|h| is_ip(h));
|
||||
let (udp_ips, udp_names): (Vec<String>, Vec<String>) = udp.into_iter().partition(|h| is_ip(h));
|
||||
let mut blocked = named(&v, "blocked", "ip");
|
||||
blocked.extend(tcp_ips);
|
||||
let mut rules = Vec::new();
|
||||
if !tcp_names.is_empty() {
|
||||
rules.push(json!({ "domain_suffix": tcp_names }));
|
||||
}
|
||||
if !udp_names.is_empty() {
|
||||
rules.push(json!({ "network": ["udp"], "port": [443], "domain_suffix": udp_names }));
|
||||
}
|
||||
if !udp_ips.is_empty() {
|
||||
rules.push(json!({ "network": ["udp"], "port": [443], "ip_cidr": cidr(&udp_ips) }));
|
||||
}
|
||||
if !blocked.is_empty() {
|
||||
rules.push(json!({ "ip_cidr": cidr(&blocked) }));
|
||||
}
|
||||
(direct, json!({ "version": 1, "rules": rules }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -555,6 +682,24 @@ UDP_PORTS=443,590:600
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verdicts_route_what_zapret2_fixes_direct_and_the_rest_by_the_proxy() {
|
||||
let user = "^pinned.example\n# a comment\ncom\n203.0.113.5\nbad entry\n";
|
||||
let auto = "learned.example\nnotyet.example\ncut.example\nleft.example\n";
|
||||
let verdicts = "works\tlearned.example\ttcp\t\t1\nworks\tcut.example\ttcp\t\t1\nstalls\tcut.example\tcutoff\t\t2\n\
|
||||
works\tleft.example\ttcp\t\t1\nunfixable\tdead.example\ttcp\t\t3\nunfixable\tquic.example\tudp\t\t3\n\
|
||||
blocked\t198.51.100.7\tip\t\t4\nunfixable\tgone.example\ttcp\t\t3\nretry\tgone.example\ttcp\t\t5\n";
|
||||
let (direct, proxy) = routing(user, Some(auto), "left.example\n", verdicts);
|
||||
assert_eq!(direct["rules"][0]["domain_suffix"], serde_json::json!(["learned.example", "pinned.example"]));
|
||||
assert_eq!(direct["rules"][1]["ip_cidr"], serde_json::json!(["203.0.113.5/32"]));
|
||||
assert_eq!(proxy["rules"][0]["domain_suffix"], serde_json::json!(["dead.example"]), "gone.example's last verdict clears it");
|
||||
assert_eq!(proxy["rules"][1], serde_json::json!({ "network": ["udp"], "port": [443], "domain_suffix": ["quic.example"] }));
|
||||
assert_eq!(proxy["rules"][2]["ip_cidr"], serde_json::json!(["198.51.100.7/32"]));
|
||||
// Learning off: the pinned ones alone.
|
||||
let (direct, _) = routing(user, None, "", verdicts);
|
||||
assert_eq!(direct["rules"][0]["domain_suffix"], serde_json::json!(["pinned.example"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extended_detector_learns_in_place_of_nfqws2() {
|
||||
let z = Zapret2 { strategy_log: true, ..Default::default() };
|
||||
|
||||
Reference in new issue
Block a user