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
@@ -140,6 +140,7 @@ fn scope_of(req: &Request) -> Option<Scope> {
|
||||
Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy),
|
||||
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
|
||||
Request::AwgLog { .. } => Some(Scope::Secrets),
|
||||
Request::ZapretCutoff { .. } => Some(Scope::Zapret),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -674,6 +675,17 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
||||
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
|
||||
}
|
||||
|
||||
Request::ZapretCutoff { probe } => {
|
||||
let s = shared.lock().await;
|
||||
if probe {
|
||||
if !crate::cutoff::enabled(s.cfg()) {
|
||||
return Response::err("the cutoff probe needs zapret.engine = \"zapret2\" with zapret2.cutoff.enable");
|
||||
}
|
||||
crate::cutoff::request_probe();
|
||||
}
|
||||
Response::ok(crate::cutoff::status(s.cfg(), s.paths()))
|
||||
}
|
||||
|
||||
Request::UpdateCheck => {
|
||||
let routes = shared.lock().await.fetch_routes(true);
|
||||
match crate::update::check(&routes).await {
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
//! The 16 KB cutoff probe (upstream's zapret2/cutoff.nix and cutoff-probe.template.sh). Some
|
||||
//! lines let TLS to certain hosting networks shake hands and then kill the connection at
|
||||
//! 12-34 KB, which no strategy fixes. z2k-detect finds which networks (AS) this line cuts and,
|
||||
//! for z2k's own strategies, a whitelisted name per network that z2k's tcp16 Lua puts into a
|
||||
//! fake ClientHello; the networks no name fixes go to a rule-set the proxy carries.
|
||||
//!
|
||||
//! The probe measures the line itself: its connections leave from
|
||||
//! ps_core::zapret2::CUTOFF_PORTS, which winws2 leaves alone, and directly under the TUN.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use ps_core::config::{Config, StrategySource, ZapretEngine};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use crate::fetch::{self, Route};
|
||||
use crate::paths::Paths;
|
||||
|
||||
/// A day, as upstream's: the maps belong to the line, probed again when its network changes.
|
||||
const MAX_AGE: u64 = 86400;
|
||||
|
||||
static FORCE: Notify = Notify::const_new();
|
||||
|
||||
/// What the probe is doing, and what the last round said.
|
||||
static NOTE: Mutex<(bool, String)> = Mutex::new((false, String::new()));
|
||||
|
||||
fn note(probing: bool, text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
if !text.is_empty() {
|
||||
tracing::info!("cutoff: {text}");
|
||||
}
|
||||
*NOTE.lock().unwrap_or_else(|e| e.into_inner()) = (probing, text);
|
||||
}
|
||||
|
||||
pub fn dir(paths: &Paths) -> PathBuf {
|
||||
paths.root.join("zapret2-cutoff")
|
||||
}
|
||||
|
||||
pub fn enabled(cfg: &Config) -> bool {
|
||||
cfg.enable && cfg.zapret.enable && cfg.zapret.engine == ZapretEngine::Zapret2 && cfg.zapret.zapret2.cutoff.enable
|
||||
}
|
||||
|
||||
/// Whether a name found fixes anything: only z2k's own profiles put it in (z2k-tcp16.lua).
|
||||
/// Elsewhere every cut-off network goes to the proxy, and no name is searched for.
|
||||
pub fn names_apply(cfg: &Config) -> bool {
|
||||
enabled(cfg) && cfg.zapret.zapret2.strategy_source == StrategySource::Z2k && cfg.zapret.zapret2.profiles.is_none()
|
||||
}
|
||||
|
||||
fn extras(paths: &Paths) -> PathBuf {
|
||||
paths.bin().join("zapret2-extras")
|
||||
}
|
||||
|
||||
pub fn program(paths: &Paths) -> Option<PathBuf> {
|
||||
let p = extras(paths).join(if cfg!(windows) { "z2k-detect.exe" } else { "z2k-detect" });
|
||||
p.is_file().then_some(p)
|
||||
}
|
||||
|
||||
fn lists(paths: &Paths) -> PathBuf {
|
||||
extras(paths).join("z2k").join("files").join("lists")
|
||||
}
|
||||
|
||||
/// The rule-set the proxy carries, when it is to (`cutoff.proxyFallback`).
|
||||
pub fn rule_set_path(cfg: &Config, paths: &Paths) -> Option<String> {
|
||||
(enabled(cfg) && cfg.zapret.zapret2.cutoff.proxy_fallback).then(|| dir(paths).join("proxy.json").to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
std::fs::read_to_string(path).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What z2k's tcp16 Lua reads inside winws2 (upstream's runtime.nix), with `lua_path` giving
|
||||
/// paths as winws2 opens them; and a digest of the maps, so a new one restarts winws2 (it
|
||||
/// reads them once).
|
||||
pub fn lua_env(cfg: &Config, paths: &Paths, lua_path: impl Fn(&Path) -> String) -> Vec<(String, String)> {
|
||||
if !names_apply(cfg) {
|
||||
return Vec::new();
|
||||
}
|
||||
let d = dir(paths);
|
||||
let digest = {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut h = Sha256::new();
|
||||
h.update(read(&d.join("asn.txt")));
|
||||
h.update(b"\0");
|
||||
h.update(read(&d.join("sni.txt")));
|
||||
h.finalize().iter().take(8).map(|b| format!("{b:02x}")).collect::<String>()
|
||||
};
|
||||
vec![
|
||||
("Z2K_TCP16_ASN".into(), lua_path(&d.join("asn.txt"))),
|
||||
("Z2K_TCP16_SNI".into(), lua_path(&d.join("sni.txt"))),
|
||||
("Z2K_SNI_PIN".into(), lua_path(&d.join("pin.txt"))),
|
||||
("Z2K_TCP16_NETS".into(), lua_path(&lists(paths).join("tcp16_nets.txt"))),
|
||||
("PROXY_SUITE_CUTOFF_MAPS".into(), digest),
|
||||
]
|
||||
}
|
||||
|
||||
/// The rule-set from the maps as they stand, written only when it changed (sing-box reloads a
|
||||
/// rule-set file replaced). Whether it did.
|
||||
pub fn write_rules(cfg: &Config, paths: &Paths) -> Result<bool> {
|
||||
let Some(path) = rule_set_path(cfg, paths) else { return Ok(false) };
|
||||
let d = dir(paths);
|
||||
std::fs::create_dir_all(&d)?;
|
||||
// Names no profile puts in fix nothing: every cut-off network goes to the proxy.
|
||||
let sni = if names_apply(cfg) { read(&d.join("sni.txt")) } else { String::new() };
|
||||
let rules = ps_core::zapret2::cutoff_rules(&read(&d.join("asn.txt")), &sni, &read(&lists(paths).join("tcp16_nets.txt")));
|
||||
let text = serde_json::to_vec(&rules)?;
|
||||
if std::fs::read(&path).is_ok_and(|old| old == text) {
|
||||
return Ok(false);
|
||||
}
|
||||
crate::paths::write_atomic(Path::new(&path), &text).with_context(|| format!("writing {path}"))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The probe's maps and when it ran, for `proxy-ctl zapret cutoff` and the app.
|
||||
pub fn status(cfg: &Config, paths: &Paths) -> Value {
|
||||
let d = dir(paths);
|
||||
let names = ps_core::zapret2::network_names(&read(&d.join("sni.txt")));
|
||||
let networks: Vec<Value> = ps_core::zapret2::cut_networks(&read(&d.join("asn.txt")))
|
||||
.into_iter()
|
||||
.map(|asn| {
|
||||
let name = names.get(&asn).filter(|n| !n.is_empty() && names_apply(cfg));
|
||||
json!({ "asn": asn, "name": name })
|
||||
})
|
||||
.collect();
|
||||
let (probing, note) = NOTE.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
json!({
|
||||
"enabled": enabled(cfg),
|
||||
"installed": program(paths).is_some(),
|
||||
"namesApply": names_apply(cfg),
|
||||
"proxyFallback": cfg.zapret.zapret2.cutoff.proxy_fallback,
|
||||
"probing": probing,
|
||||
"note": note,
|
||||
"probed": read(&d.join("ts")).trim().parse::<u64>().ok(),
|
||||
"egress": Some(read(&d.join("egress")).trim().to_owned()).filter(|e| !e.is_empty()),
|
||||
"networks": networks,
|
||||
})
|
||||
}
|
||||
|
||||
/// Probe now, whatever the line and the last probe's age. Under way from now on, for whoever
|
||||
/// follows it: every forced round ends with a note that it is not.
|
||||
pub fn request_probe() {
|
||||
note(true, "about to probe the line");
|
||||
FORCE.notify_one();
|
||||
}
|
||||
|
||||
/// Rounds as upstream's timer runs them: 5 minutes after start, then every 10 (cheap unless
|
||||
/// the line's network changed or a day passed), and at once when asked.
|
||||
pub async fn runner(shared: crate::service::Shared) {
|
||||
let mut wait = Duration::from_secs(300);
|
||||
loop {
|
||||
let force = tokio::select! {
|
||||
_ = tokio::time::sleep(wait) => false,
|
||||
_ = FORCE.notified() => true,
|
||||
};
|
||||
wait = Duration::from_secs(600);
|
||||
if let Err(e) = round(&shared, force).await {
|
||||
note(false, format!("{e:#}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The line's network (`AS…`) as one service names it, or none.
|
||||
async fn asn_from(url: &str, pick: impl Fn(&Value) -> Option<String>) -> Option<String> {
|
||||
let body = tokio::time::timeout(Duration::from_secs(10), fetch::get(url, &Route::Direct, 64 * 1024)).await.ok()?.ok()?;
|
||||
let v: Value = serde_json::from_slice(&body).ok()?;
|
||||
pick(&v).filter(|a| a.len() > 2 && a.starts_with("AS") && a[2..].bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// This line's network: two services must agree, as one alone now and then names another
|
||||
/// (each flip cost a full probe). One answer alone counts for the network already known, or
|
||||
/// when none is. Err with why not to probe.
|
||||
async fn egress(known: &str) -> Result<String, String> {
|
||||
let (ipinfo, ifconfig) = tokio::join!(
|
||||
asn_from("https://ipinfo.io/json", |v| v["org"].as_str().and_then(|o| o.split(' ').next()).map(str::to_owned)),
|
||||
asn_from("https://ifconfig.co/json", |v| v["asn"].as_str().map(str::to_owned)),
|
||||
);
|
||||
match (ipinfo, ifconfig) {
|
||||
(Some(a), Some(b)) if a != b => Err(format!("ipinfo.io says {a}, ifconfig.co says {b}; keeping the last probe")),
|
||||
(Some(a), Some(_)) => Ok(a),
|
||||
(None, None) => Err("no answer about this line's network; not probing".into()),
|
||||
(Some(a), None) | (None, Some(a)) => {
|
||||
if !known.is_empty() && a != known {
|
||||
Err(format!("only one service answered, with {a} for this line's {known}; keeping the last probe"))
|
||||
} else {
|
||||
Ok(a)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// z2k-detect with `args`, from the probe's ports, its output appended to the probe's log:
|
||||
/// its exit code.
|
||||
async fn detect(program: &Path, args: &[&str], dir: &Path) -> Result<i32> {
|
||||
let log = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("probe.log"))?;
|
||||
let (lo, hi) = ps_core::zapret2::CUTOFF_PORTS;
|
||||
let mut cmd = tokio::process::Command::new(program);
|
||||
cmd.args(args)
|
||||
.env("Z2K_TCP16_LOCAL_PORTS", format!("{lo}-{hi}"))
|
||||
.current_dir(dir)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(log.try_clone()?)
|
||||
.stderr(log)
|
||||
.kill_on_drop(true);
|
||||
#[cfg(windows)]
|
||||
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
let status = cmd.status().await.with_context(|| format!("running {}", program.display()))?;
|
||||
Ok(status.code().unwrap_or(-1))
|
||||
}
|
||||
|
||||
async fn round(shared: &crate::service::Shared, force: bool) -> Result<()> {
|
||||
let (cfg, paths) = {
|
||||
let s = shared.lock().await;
|
||||
(s.cfg().clone(), s.paths().clone())
|
||||
};
|
||||
if !enabled(&cfg) {
|
||||
if force {
|
||||
note(false, "the cutoff probe is off (zapret.zapret2.cutoff.enable, with the zapret2 engine)");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(program) = program(&paths) else {
|
||||
note(false, "z2k-detect is not installed (the zapret2-extras component)");
|
||||
return Ok(());
|
||||
};
|
||||
let d = dir(&paths);
|
||||
std::fs::create_dir_all(&d)?;
|
||||
let names = names_apply(&cfg);
|
||||
// Names no profile puts in fix nothing: none kept from when one did.
|
||||
if !names && !read(&d.join("sni.txt")).is_empty() {
|
||||
std::fs::write(d.join("sni.txt"), b"")?;
|
||||
}
|
||||
if write_rules(&cfg, &paths)? {
|
||||
tracing::info!("cutoff: the proxy's rule-set follows the maps");
|
||||
}
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
|
||||
let last: u64 = read(&d.join("ts")).trim().parse().unwrap_or(0);
|
||||
let known = read(&d.join("egress")).trim().to_owned();
|
||||
let egress = match egress(&known).await {
|
||||
Ok(e) => e,
|
||||
Err(why) => {
|
||||
note(false, why);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
if !force && egress == known && now.saturating_sub(last) < MAX_AGE {
|
||||
return Ok(());
|
||||
}
|
||||
let targets = lists(&paths).join("tcp16_targets.txt");
|
||||
let candidates = lists(&paths).join("sni_wl_candidates.txt");
|
||||
// z2k-detect exits 1 for "cut" and for a file it cannot read alike.
|
||||
if !targets.is_file() || !candidates.is_file() {
|
||||
note(false, "z2k's target lists are missing (the zapret2-extras component)");
|
||||
return Ok(());
|
||||
}
|
||||
note(true, format!("probing the line from {egress}"));
|
||||
let _ = std::fs::write(d.join("probe.log"), b"");
|
||||
let (asn_new, sni_new) = (d.join("asn.new"), d.join("sni.new"));
|
||||
let _ = std::fs::remove_file(&asn_new);
|
||||
let _ = std::fs::remove_file(&sni_new);
|
||||
let t = targets.to_string_lossy().into_owned();
|
||||
match detect(&program, &["tcp16", "-targets", &t, "-parallel", "50", "-asn-out", "asn.new"], &d).await? {
|
||||
1 => {
|
||||
if names {
|
||||
let c = candidates.to_string_lossy().into_owned();
|
||||
let rc = detect(&program, &["tcp16", "-targets", &t, "-scan", &c, "-per-asn", "-batch", "5", "-parallel", "50", "-sni-out", "sni.new"], &d).await?;
|
||||
// 2: no network took any name; the cut-off networks still stand.
|
||||
if rc != 0 && rc != 2 {
|
||||
let _ = std::fs::remove_file(&asn_new);
|
||||
note(false, format!("the name search failed ({rc}); keeping the previous maps (its log: {})", d.join("probe.log").display()));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if !sni_new.exists() {
|
||||
std::fs::write(&sni_new, b"")?;
|
||||
}
|
||||
}
|
||||
0 => {
|
||||
std::fs::write(&asn_new, b"")?;
|
||||
std::fs::write(&sni_new, b"")?;
|
||||
}
|
||||
rc => {
|
||||
let _ = std::fs::remove_file(&asn_new);
|
||||
note(false, format!("the probe did not run ({rc}); keeping the previous maps (its log: {})", d.join("probe.log").display()));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let changed = read(&asn_new) != read(&d.join("asn.txt")) || read(&sni_new) != read(&d.join("sni.txt"));
|
||||
std::fs::rename(&asn_new, d.join("asn.txt"))?;
|
||||
std::fs::rename(&sni_new, d.join("sni.txt"))?;
|
||||
write_rules(&cfg, &paths)?;
|
||||
std::fs::write(d.join("egress"), format!("{egress}\n"))?;
|
||||
std::fs::write(d.join("ts"), format!("{now}\n"))?;
|
||||
let cut = ps_core::zapret2::cut_networks(&read(&d.join("asn.txt"))).len();
|
||||
let named = ps_core::zapret2::network_names(&read(&d.join("sni.txt"))).len();
|
||||
note(false, format!("probed from {egress}: {cut} network(s) cut off, {named} with a name"));
|
||||
// winws2 reads the maps once: a new one restarts it (the Lua's environment carries their
|
||||
// digest); what it learned stays on disk.
|
||||
if changed && names {
|
||||
if let Err(e) = shared.lock().await.apply().await {
|
||||
tracing::warn!("cutoff: applying the new maps: {e:#}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -9,6 +9,7 @@ mod awg;
|
||||
mod awgvpn;
|
||||
mod clash;
|
||||
mod components;
|
||||
mod cutoff;
|
||||
mod fetch;
|
||||
mod install;
|
||||
#[cfg(windows)]
|
||||
@@ -124,6 +125,7 @@ pub async fn run(
|
||||
tokio::spawn(autoproxy::sample(shared.clone()));
|
||||
tokio::spawn(autoproxy::sample_slow(shared.clone()));
|
||||
tokio::spawn(zapret::sync_loop(shared.clone()));
|
||||
tokio::spawn(cutoff::runner(shared.clone()));
|
||||
// First fetches: what the configuration needs and has not got yet.
|
||||
{
|
||||
let shared = shared.clone();
|
||||
|
||||
@@ -127,6 +127,16 @@ impl Service {
|
||||
{
|
||||
direct.push(p.to_string_lossy().into_owned());
|
||||
}
|
||||
// The cutoff probe measures the line: its connections, and the service's own lookup of
|
||||
// the line's network, leave directly.
|
||||
if crate::cutoff::enabled(cfg) {
|
||||
if let Some(p) = crate::cutoff::program(paths) {
|
||||
direct.push(p.to_string_lossy().into_owned());
|
||||
}
|
||||
if let Ok(me) = std::env::current_exe() {
|
||||
direct.push(me.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
let (zd, zi) = crate::zapret::direct_sync(cfg, &paths.bin());
|
||||
Env {
|
||||
zapret_direct: ps_core::config::RouteMatch { domains: zd, ips: zi, ..Default::default() },
|
||||
@@ -146,6 +156,7 @@ impl Service {
|
||||
autoproxy_rules_dir: cfg.proxy.auto_proxy.enable.then(|| crate::autoproxy::rules_dir(paths).to_string_lossy().into_owned()),
|
||||
zapret2_direct_rule_set: crate::zapret::rule_set_paths(cfg, paths).0,
|
||||
zapret2_proxy_rule_set: crate::zapret::rule_set_paths(cfg, paths).1,
|
||||
zapret2_cutoff_rule_set: crate::cutoff::rule_set_path(cfg, paths),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,6 +403,7 @@ impl Service {
|
||||
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
|
||||
}
|
||||
crate::zapret::sync_rule_sets(self.cfg(), self.paths())?;
|
||||
crate::cutoff::write_rules(self.cfg(), self.paths())?;
|
||||
|
||||
let backend = self.cfg().proxy.backend;
|
||||
let main_program = match backend {
|
||||
|
||||
@@ -223,6 +223,10 @@ pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<Uni
|
||||
env.push(("Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE".to_owned(), lua_path(&fallback)));
|
||||
env.push(("PROXY_SUITE_ZAPRET2_VERDICTS".to_owned(), lua_path(&learned.join("verdicts.tsv"))));
|
||||
env.push(("PROXY_SUITE_PUBLIC_SUFFIXES".to_owned(), lua_path(&extras_dir.join("public_suffixes.txt"))));
|
||||
// The 16 KB cutoff probe's maps, for z2k's tcp16 name step (z2k's own strategies).
|
||||
if source.z2k {
|
||||
env.extend(crate::cutoff::lua_env(cfg, paths, lua_path));
|
||||
}
|
||||
}
|
||||
let generation = {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
Reference in new issue
Block a user