From fb6c5962d06caa521435251f2d4e5d39ff865e57 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 27 Oct 2026 07:37:29 +0300 Subject: [PATCH] windows: zapret's hostlistRules, and the SSH tunnel - hostlistRules (zapret-discord-youtube): a group of sites with its own strategy, as upstream's patch-zapret-config.py makes them: the preset's profiles for the rule's family (or another preset's, with configName; Discord's voice profile with it), pointed at the rule's own list with the standard excludes, or the rule's nfqwsArgs; ahead of the preset's own. WinDivert's filter takes the ports they add. Rules with enableDirectSync join the direct list. Names of zapret's own lists, and the instagram/soundcloud/twitter families (not in Flowseal's Windows release), are refused. Every preset with sample rules checked by winws.exe --dry-run (tools/winws-dry-run.sh); one without the profile a rule copies is refused, as upstream refuses it. - The SSH tunnel (sshProxy): Windows' own OpenSSH (System32) as ssh -N -D, with upstream's options and only the configured key offered (IdentitiesOnly: an agent's keys used up the server's tries); the key copied below the protected state root, as Windows' OpenSSH wants it and sing-box's SSH outbound reads it; the server's keys from hostKey, hostKeyFile or knownHostsFile. End to end on Linux against an sshd of the test's own: a page through each, two logins with the copied key. - The dev shell has OpenSSH, for that test. Co-Authored-By: Claude Opus 5.5 --- windows/README.md | 12 +- .../crates/ps-core/examples/zapret_args.rs | 43 ++- windows/crates/ps-core/src/config/validate.rs | 21 +- windows/crates/ps-core/src/zapret.rs | 353 +++++++++++++++++- windows/crates/ps-core/src/zapret2.rs | 2 +- windows/crates/ps-ctl/tests/e2e.rs | 108 ++++++ windows/crates/ps-service/src/main.rs | 1 + windows/crates/ps-service/src/service.rs | 20 +- windows/crates/ps-service/src/ssh.rs | 179 +++++++++ windows/crates/ps-service/src/zapret.rs | 30 +- windows/flake.nix | 2 + windows/release-notes/0.2.0-pre.1.md | 5 +- windows/tools/winws-dry-run.sh | 18 + windows/tools/zapret-rules-sample.json | 6 + 14 files changed, 776 insertions(+), 24 deletions(-) create mode 100644 windows/crates/ps-service/src/ssh.rs create mode 100644 windows/tools/zapret-rules-sample.json diff --git a/windows/README.md b/windows/README.md index 85b14ac..7e2fec4 100644 --- a/windows/README.md +++ b/windows/README.md @@ -20,15 +20,17 @@ tray icon) or with `proxy-ctl`, as upstream's is. |---|---| | Local proxy | SOCKS5/HTTP on `127.0.0.1:1080` through sing-box (or the hybrid sing-box + XRay backend) | | Outbounds | links (vless/REALITY/TLS, vmess, trojan, shadowsocks, hysteria2, tuic, anytls, naive, socks, http), raw JSON, subscriptions, groups (failover, urltest, selector), chains, pins, route modes, routing rules by site, address, geodata, rule set or **program** | -| zapret | Flowseal's [zapret-discord-youtube](https://github.com/Flowseal/zapret-discord-youtube) release: `winws.exe` with any of its `general*.bat` presets, your lists, the game filter | +| zapret | Flowseal's [zapret-discord-youtube](https://github.com/Flowseal/zapret-discord-youtube) release: `winws.exe` with any of its `general*.bat` presets, your lists, the game filter, and `hostlistRules` (a strategy of its own for a group of sites, copied from a preset or given) | | zapret2 | `winws2.exe` from bol-van's [zapret-win-bundle](https://github.com/bol-van/zapret-win-bundle) with [nfqws2-keenetic](https://github.com/nfqws/nfqws2-keenetic)'s strategies and nfqws2's own learning of blocked sites | | tg-ws-proxy | Flowseal's [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy), the headless proxy, on a bundled Python | +| SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) | | TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** | | The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy | -Not in this release, still to come: AmneziaWG, WARP, Tor, the SSH tunnel, whitelist-bypass, -the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and z2k -strategies. +Not in this release, still to come: AmneziaWG, WARP, Tor, whitelist-bypass, +the kill switch, server inbounds, the XRay-only backend, autoProxy, zapret2's extended +detection and z2k strategies. Their options are accepted (they are upstream's), but the +service says, in its status and in the app, that it does not run them yet. Needs 64-bit Windows 10 (1903 or later) or 11. @@ -43,6 +45,8 @@ Needs 64-bit Windows 10 (1903 or later) or 11. | zapret arguments | **every** preset of the release, both game filters, checked by the release's own `winws.exe --dry-run` under Wine (`tools/winws-dry-run.sh`) | | zapret2 arguments | checked by `winws2.exe --dry-run` under Wine | | tg-ws-proxy | runs and listens under Wine | +| SSH tunnel | end to end on Linux: an sshd of the test's own, a page through the `ssh -D` listener and through sing-box's SSH outbound, each logging in with the service's copy of the key (`an_ssh_tunnel`) | +| zapret's hostlist rules | every preset with sample rules, checked by `winws.exe --dry-run` (a preset without the profile a rule copies is refused, as upstream refuses it) | | The app | every page against the service running on Linux, in a window on a virtual display (Xvfb, Mesa's software Vulkan), clicked and typed into by a script, screenshots looked at, and the service's configuration checked after each change (`tools/gui-shot.sh`) | | The app's Windows build | built by the release workflow; its shaders by Microsoft's own `fxc.exe` (under Wine) with GPUI's own arguments; under Wine it starts and gets as far as drawing text | diff --git a/windows/crates/ps-core/examples/zapret_args.rs b/windows/crates/ps-core/examples/zapret_args.rs index c4531d7..caf836d 100644 --- a/windows/crates/ps-core/examples/zapret_args.rs +++ b/windows/crates/ps-core/examples/zapret_args.rs @@ -1,18 +1,47 @@ //! For tools/winws-dry-run.sh: a preset's winws arguments as the service builds them, one -//! per line. `zapret_args `, paths as -//! Windows sees them (with a trailing separator). +//! per line. `zapret_args [ ]`, Windows paths with a +//! trailing separator. With rules, their lists are written into the lists dir. -use ps_core::config::GameFilter; -use ps_core::zapret::{expand, find_preset, preset_args}; +use ps_core::config::{GameFilter, HostlistRule}; +use ps_core::zapret::{ReleaseLists, expand, find_preset, preset_args, rule, rule_lists, with_rules}; fn main() { let a: Vec = std::env::args().collect(); let (release, win_root, win_lists, preset, game) = (&a[1], &a[2], &a[3], &a[4], &a[5]); + let release = std::path::Path::new(release); let files: Vec = std::fs::read_dir(release).unwrap().filter_map(|e| e.ok()?.file_name().into_string().ok()).collect(); - let file = find_preset(&files, preset).unwrap(); - let text = std::fs::read_to_string(std::path::Path::new(release).join(file)).unwrap(); let game: GameFilter = serde_json::from_value(serde_json::json!(game)).unwrap(); - for arg in expand(&preset_args(&text).unwrap(), &format!("{win_root}bin\\"), win_lists, win_root, game) { + let bin = format!("{win_root}bin\\"); + let ex = |args: &[String]| expand(args, &bin, win_lists, win_root, game); + let args_of = |name: &str| -> Result, String> { + let file = find_preset(&files, name)?; + Ok(ex(&preset_args(&std::fs::read_to_string(release.join(file)).unwrap())?)) + }; + let mut args = args_of(preset).unwrap(); + if let (Some(json), Some(lists)) = (a.get(6), a.get(7)) { + let read = |f: &str| std::fs::read_to_string(release.join("lists").join(f)).unwrap_or_default(); + let (general, google, ipset_all) = (read("list-general.txt"), read("list-google.txt"), read("ipset-all.txt")); + let release_lists = ReleaseLists { general: &general, google: &google, ipset_all: &ipset_all }; + let raw: Vec = serde_json::from_str(&std::fs::read_to_string(json).unwrap()).unwrap(); + let rules: Vec<_> = raw.iter().map(|r| rule(r, &release_lists).unwrap()).collect(); + for r in &rules { + let (list, ipset) = rule_lists(r); + for (file, entries) in [(list, &r.domains), (ipset, &r.ips)] { + if !entries.is_empty() { + std::fs::write(std::path::Path::new(lists).join(file), format!("{}\n", entries.join("\n"))).unwrap(); + } + } + } + args = match with_rules(args, &rules, win_lists, &args_of, &ex) { + Ok(a) => a, + Err(e) => { + eprintln!("{e}"); + std::process::exit(2); + } + }; + } + for arg in args { println!("{arg}"); } } diff --git a/windows/crates/ps-core/src/config/validate.rs b/windows/crates/ps-core/src/config/validate.rs index 1f565aa..4fd12b8 100644 --- a/windows/crates/ps-core/src/config/validate.rs +++ b/windows/crates/ps-core/src/config/validate.rs @@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use super::{Backend, Config, GroupStrategy, Selection, StrategySource, ZapretEngine}; +use super::{Backend, Config, GroupStrategy, Selection, StrategySource, ZapretDefaultDomains, ZapretEngine, ZapretPreset}; use crate::derived::{self, BUILTIN_TAGS}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -102,7 +102,6 @@ fn not_ported(cfg: &Config, v: &mut Issues) { (cfg.amnezia_wg.enable, "amneziaWg.enable", "AmneziaWG"), (cfg.warp.enable, "warp.enable", "WARP"), (cfg.tor.enable, "tor.enable", "Tor"), - (cfg.ssh_proxy.enable, "sshProxy.enable", "The SSH tunnel"), (cfg.whitelist_bypass.enable, "whitelistBypass.enable", "whitelist-bypass"), (cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"), (cfg.proxy.auto_proxy.enable, "proxy.autoProxy.enable", "autoProxy"), @@ -115,8 +114,8 @@ fn not_ported(cfg: &Config, v: &mut Issues) { v.warn("proxy.backend", "the xray backend is not on Windows yet: the proxy does not start with it (sing-box or hybrid do)"); } let z = &cfg.zapret; - if z.enable && z.engine == ZapretEngine::DiscordYoutube && !z.discord_youtube.hostlist_rules.is_empty() { - v.warn("zapret.zapret-discord-youtube.hostlistRules", "hostlistRules are not on Windows yet: the preset applies to every site"); + 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.strategy_source == StrategySource::Z2k && z.zapret2.profiles.is_none() { @@ -469,6 +468,20 @@ fn zapret(cfg: &Config, v: &mut Issues) { } else if !names.insert(rule.name.as_str()) { v.error(format!("{path}.name"), format!("list '{}' is defined twice", rule.name)); } + // Its lists are list-.txt and ipset-.txt beside the release's own. + const RELEASE_LISTS: [&str; 9] = ["general", "general-user", "google", "exclude", "exclude-user", "all", "instagram", "soundcloud", "twitter"]; + if RELEASE_LISTS.contains(&rule.name.as_str()) { + v.error(format!("{path}.name"), format!("'{}' is the name of one of zapret's own lists", rule.name)); + } + if rule.default_domains.iter().any(|d| matches!(d, ZapretDefaultDomains::Instagram | ZapretDefaultDomains::Soundcloud | ZapretDefaultDomains::Twitter)) { + v.error(format!("{path}.defaultDomains"), "Flowseal's Windows release has no instagram, soundcloud or twitter list"); + } + if matches!(rule.preset, Some(ZapretPreset::Instagram | ZapretPreset::Soundcloud | ZapretPreset::Twitter)) { + v.error(format!("{path}.preset"), "Flowseal's Windows release has no instagram, soundcloud or twitter profiles"); + } + if !rule.domains.is_empty() && rule.preset.is_none() && rule.default_domains.is_empty() && rule.nfqws_args.is_empty() { + v.error(&path, "a list with domains needs preset, defaultDomains or nfqwsArgs, for its strategy"); + } if rule.config_name.is_some() && !rule.nfqws_args.is_empty() { v.error(&path, "configName cannot be used with nfqwsArgs"); } diff --git a/windows/crates/ps-core/src/zapret.rs b/windows/crates/ps-core/src/zapret.rs index 0f63143..2a82cc6 100644 --- a/windows/crates/ps-core/src/zapret.rs +++ b/windows/crates/ps-core/src/zapret.rs @@ -9,7 +9,7 @@ use std::collections::BTreeSet; -use crate::config::{DiscordYoutube, GameFilter, Zapret}; +use crate::config::{DiscordYoutube, GameFilter, HostlistRule, Zapret, ZapretDefaultDomains, ZapretDefaultIps, ZapretPreset}; /// What a preset's name is compared by: its letters, digits and brackets, any case. fn name_key(name: &str) -> String { @@ -152,6 +152,249 @@ pub fn expand(args: &[String], bin: &str, lists: &str, root: &str, game: GameFil .collect() } +/// A list file's entries: trimmed, without comments and blanks, each once. +fn list_entries(text: &str) -> Vec { + let mut seen = BTreeSet::new(); + text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#') && seen.insert(*l)).map(str::to_owned).collect() +} + +/// The release's lists a rule's `defaultDomains` and `defaultIps` name, as text. +pub struct ReleaseLists<'a> { + pub general: &'a str, + pub google: &'a str, + pub ipset_all: &'a str, +} + +/// A hostlist rule, worked out as upstream's zapret-domain-groups.nix does: its sites, and what +/// of which preset its strategy is copied from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Rule { + pub name: String, + pub domains: Vec, + pub ips: Vec, + /// The preset profiles copied for its domains: "general", "google". + pub families: Vec<&'static str>, + /// Discord's voice profile copied too (a rule taking another preset, for Discord's sites). + pub discord_voice: bool, + pub config_name: Option, + pub nfqws_args: Vec, +} + +/// Instagram's, SoundCloud's and Twitter's lists come with the Linux port upstream uses, not +/// with Flowseal's Windows release. +fn not_in_release(rule: &str, list: &str) -> String { + format!("hostlist rule '{rule}': Flowseal's Windows release has no {list} list") +} + +pub fn rule(r: &HostlistRule, lists: &ReleaseLists) -> Result { + use ZapretDefaultDomains as D; + let mut domains = Vec::new(); + let mut families: Vec<&'static str> = Vec::new(); + for group in &r.default_domains { + let (list, family) = match group { + D::General | D::Discord => (lists.general, "general"), + D::Google | D::Youtube => (lists.google, "google"), + D::Instagram => return Err(not_in_release(&r.name, "instagram")), + D::Soundcloud => return Err(not_in_release(&r.name, "soundcloud")), + D::Twitter => return Err(not_in_release(&r.name, "twitter")), + }; + domains.extend(list_entries(list)); + if !families.contains(&family) { + families.push(family); + } + } + domains.extend(r.domains.iter().map(|d| d.trim().to_owned())); + let mut ips = Vec::new(); + for group in &r.default_ips { + match group { + ZapretDefaultIps::All => ips.extend(list_entries(lists.ipset_all)), + } + } + ips.extend(r.ips.iter().map(|i| i.trim().to_owned())); + if let Some(preset) = r.preset { + families = vec![match preset { + ZapretPreset::General => "general", + ZapretPreset::Google => "google", + ZapretPreset::Instagram => return Err(not_in_release(&r.name, "instagram")), + ZapretPreset::Soundcloud => return Err(not_in_release(&r.name, "soundcloud")), + ZapretPreset::Twitter => return Err(not_in_release(&r.name, "twitter")), + }]; + } + let once = |v: Vec| { + let mut seen = BTreeSet::new(); + v.into_iter().filter(|x| !x.is_empty() && seen.insert(x.clone())).collect::>() + }; + Ok(Rule { + name: r.name.clone(), + domains: once(domains), + ips: once(ips), + families, + discord_voice: r.config_name.is_some() && r.default_domains.iter().any(|g| matches!(g, D::General | D::Discord)), + config_name: r.config_name.clone(), + nfqws_args: r.nfqws_args.clone(), + }) +} + +/// A rule's own lists, in the lists directory. +pub fn rule_lists(rule: &Rule) -> (String, String) { + (format!("list-{}.txt", rule.name), format!("ipset-{}.txt", rule.name)) +} + +/// A preset's arguments cut into the global ones (the WinDivert filter, `--wf-*`, ahead of the +/// first profile) and its profiles (between `--new`). +fn profiles(args: &[String]) -> (Vec, Vec>) { + let mut global = Vec::new(); + let mut out = vec![Vec::new()]; + for a in args { + if a == "--new" { + out.push(Vec::new()); + } else if out.len() == 1 && out[0].is_empty() && a.starts_with("--wf-") { + global.push(a.clone()); + } else { + out.last_mut().unwrap().push(a.clone()); + } + } + out.retain(|p| !p.is_empty()); + (global, out) +} + +/// `--hostlist=…list-general.txt` and the like: `option` naming one of `files`. +fn names_list(arg: &str, option: &str, files: &[&str]) -> bool { + arg.strip_prefix(option).is_some_and(|path| files.contains(&path.rsplit(['\\', '/']).next().unwrap_or(path))) +} + +fn family_files(family: &str) -> &'static [&'static str] { + match family { + "general" => &["list-general.txt", "list-general-user.txt"], + _ => &["list-google.txt"], + } +} + +/// A profile pointed at one list of the rule's: its own list arguments (those `drop` says) +/// gone, the other kind's gone too, the list put in, and the standard excludes there. +fn retarget(profile: &[String], option: &str, list: &str, drop: impl Fn(&str) -> bool, excludes: &[String]) -> Vec { + let other = if option == "--hostlist=" { "--ipset=" } else { "--hostlist=" }; + let mut out: Vec = profile.iter().filter(|a| !drop(a) && !a.starts_with(other)).cloned().collect(); + out.push(format!("{option}{list}")); + for e in excludes { + if !out.contains(e) { + out.push(e.clone()); + } + } + out +} + +/// The ports a profile filters on, by protocol. +fn filter_ports<'a>(profile: &'a [String], proto: &str) -> Vec<&'a str> { + let option = format!("--filter-{proto}="); + profile.iter().filter_map(|a| a.strip_prefix(option.as_str())).collect() +} + +/// The preset's arguments (expanded) with the rules' profiles ahead of its own. `source` gives +/// another preset's arguments, expanded, for a rule's `configName`; `expand` fills in a rule's +/// own `nfqwsArgs` as a preset's are. `lists` ends with a separator. +pub fn with_rules( + args: Vec, + rules: &[Rule], + lists: &str, + source: &dyn Fn(&str) -> Result, String>, + expand: &dyn Fn(&[String]) -> Vec, +) -> Result, String> { + if rules.is_empty() { + return Ok(args); + } + let (mut global, own) = profiles(&args); + let excludes: Vec = [ + ("--hostlist-exclude=", "list-exclude.txt"), + ("--hostlist-exclude=", "list-exclude-user.txt"), + ("--ipset-exclude=", "ipset-exclude.txt"), + ("--ipset-exclude=", "ipset-exclude-user.txt"), + ] + .iter() + .map(|(o, f)| format!("{o}{lists}{f}")) + .collect(); + let mut generated: Vec> = Vec::new(); + // What WinDivert has to let through for them: their filters' ports, another preset's own. + let (mut tcp, mut udp): (Vec, Vec) = (Vec::new(), Vec::new()); + for rule in rules { + let (src_global, src) = match &rule.config_name { + Some(name) => profiles(&source(name).map_err(|e| format!("hostlist rule '{}': {e}", rule.name))?), + None => (Vec::new(), own.clone()), + }; + for a in &src_global { + if let Some(p) = a.strip_prefix("--wf-tcp=") { + tcp.push(p.to_owned()); + } else if let Some(p) = a.strip_prefix("--wf-udp=") { + udp.push(p.to_owned()); + } + } + let (list, ipset) = rule_lists(rule); + let (list, ipset) = (format!("{lists}{list}"), format!("{lists}{ipset}")); + let missing = |what: &str| format!("hostlist rule '{}': the preset has no {what} profile to copy", rule.name); + if !rule.domains.is_empty() { + for family in &rule.families { + let files = family_files(family); + let matching: Vec<&Vec> = src.iter().filter(|p| p.iter().any(|a| names_list(a, "--hostlist=", files))).collect(); + if matching.is_empty() { + return Err(missing(family)); + } + for p in matching { + generated.push(retarget(p, "--hostlist=", &list, |a| names_list(a, "--hostlist=", files), &excludes)); + } + } + } + if !rule.ips.is_empty() { + let matching: Vec<&Vec> = src.iter().filter(|p| p.iter().any(|a| names_list(a, "--ipset=", &["ipset-all.txt"]))).collect(); + if matching.is_empty() { + return Err(missing("ipset-all")); + } + for p in matching { + generated.push(retarget(p, "--ipset=", &ipset, |a| names_list(a, "--ipset=", &["ipset-all.txt"]), &excludes)); + } + } + if rule.discord_voice { + let voice: Vec<&Vec> = src.iter().filter(|p| p.iter().any(|a| a == "--filter-l7=discord,stun")).collect(); + if voice.is_empty() { + return Err(missing("Discord voice")); + } + generated.extend(voice.into_iter().cloned()); + } + for fragment in &rule.nfqws_args { + let args = expand(&cmd_tokens(fragment)); + tcp.extend(filter_ports(&args, "tcp").into_iter().map(str::to_owned)); + udp.extend(filter_ports(&args, "udp").into_iter().map(str::to_owned)); + if !rule.domains.is_empty() { + generated.push(retarget(&args, "--hostlist=", &list, |a| a.starts_with("--hostlist="), &excludes)); + } + if !rule.ips.is_empty() { + generated.push(retarget(&args, "--ipset=", &ipset, |a| a.starts_with("--ipset="), &excludes)); + } + } + } + for (option, extra) in [("--wf-tcp=", &tcp), ("--wf-udp=", &udp)] { + if extra.is_empty() { + continue; + } + let mut all: Vec<&str> = extra.iter().map(String::as_str).collect(); + match global.iter_mut().find(|a| a.starts_with(option)) { + Some(a) => { + let have = a[option.len()..].to_owned(); + all.push(&have); + *a = format!("{option}{}", crate::zapret2::merge_ports(&all)); + } + None => global.push(format!("{option}{}", crate::zapret2::merge_ports(&all))), + } + } + let mut out = global; + for (i, p) in generated.into_iter().chain(own).enumerate() { + if i > 0 { + out.push("--new".into()); + } + out.extend(p); + } + Ok(out) +} + /// What the user's lists hold, as files beside the release's: Flowseal's `load_user_lists` /// placeholders where a list would be empty (winws refuses an empty one). #[derive(Debug, Clone, PartialEq, Eq)] @@ -212,6 +455,18 @@ pub fn direct_sync(z: &Zapret, list_general: &str, list_google: &str, list_exclu domains.extend(parse(list_general)); domains.extend(parse(list_google)); domains.extend(y.domains.iter().map(|d| d.trim_start_matches('^').to_owned())); + // The hostlist rules that ask for it, as upstream's: their sites, their addresses. + let release = ReleaseLists { general: list_general, google: list_google, ipset_all }; + for r in y.hostlist_rules.iter().filter(|r| r.enable_direct_sync) { + let Ok(rule) = rule(r, &release) else { continue }; + domains.extend(rule.domains.iter().map(|d| d.trim_start_matches('^').to_owned())); + if ds.user_ips { + ips.extend(r.ips.iter().cloned()); + } + if ds.upstream_ips && r.default_ips.contains(&ZapretDefaultIps::All) { + ips.extend(parse(ipset_all).into_iter().filter(|i| i != "203.0.113.113/32")); + } + } let mut excluded: BTreeSet = parse(list_exclude).into_iter().collect(); excluded.extend(y.exclude_domains.iter().map(|d| d.trim_start_matches('^').to_owned())); domains.retain(|d| !excluded.contains(d)); @@ -273,6 +528,95 @@ start "zapret: %~n0" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf- assert_eq!(all[0], "--wf-tcp=80,443,1024-65535"); } + const FULL: &str = r#"start "zapret" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf-udp=443,19294-19344,%GameFilterUDP% ^ +--filter-udp=443 --hostlist="%LISTS%list-general.txt" --hostlist="%LISTS%list-general-user.txt" --hostlist-exclude="%LISTS%list-exclude.txt" --dpi-desync=fake --new ^ +--filter-udp=19294-19344 --filter-l7=discord,stun --dpi-desync=fake --new ^ +--filter-tcp=443 --hostlist="%LISTS%list-google.txt" --dpi-desync=multisplit --new ^ +--filter-tcp=80,443 --ipset="%LISTS%ipset-all.txt" --hostlist-exclude="%LISTS%list-exclude.txt" --dpi-desync=fake +"#; + const OTHER: &str = r#""%BIN%winws.exe" --wf-tcp=443,2053 --wf-udp=443 --filter-tcp=443,2053 --hostlist="%LISTS%list-general.txt" --dpi-desync=hostfakesplit --new --filter-udp=19294-19344 --filter-l7=discord,stun --dpi-desync=fake"#; + + fn ex(args: &[String]) -> Vec { + expand(args, "B\\", "L\\", "R\\", GameFilter::Null) + } + + fn lists() -> ReleaseLists<'static> { + ReleaseLists { general: "discord.com\n# c\n", google: "youtube.com\ngooglevideo.com\n", ipset_all: "203.0.113.0/24\n" } + } + + fn rules(json: serde_json::Value) -> Result, String> { + let r: HostlistRule = serde_json::from_value(json).unwrap(); + let rule = rule(&r, &lists())?; + let source = |name: &str| if name == "other" { Ok(ex(&preset_args(OTHER).unwrap())) } else { Err(format!("no preset {name}")) }; + with_rules(ex(&preset_args(FULL).unwrap()), &[rule], "L\\", &source, &ex) + } + + fn profile_of(args: &[String], i: usize) -> Vec { + let (_, p) = profiles(args); + p[i].clone() + } + + #[test] + fn a_rule_copies_its_family_ahead_of_the_preset() { + let out = rules(serde_json::json!({ "name": "mine", "domains": ["example.com"], "preset": "general" })).unwrap(); + let first = profile_of(&out, 0); + assert_eq!( + first, + [ + "--filter-udp=443", + "--hostlist-exclude=L\\list-exclude.txt", + "--dpi-desync=fake", + "--hostlist=L\\list-mine.txt", + "--hostlist-exclude=L\\list-exclude-user.txt", + "--ipset-exclude=L\\ipset-exclude.txt", + "--ipset-exclude=L\\ipset-exclude-user.txt", + ] + ); + // The preset's own follow, untouched; the filter as it was. + let (global, p) = profiles(&out); + assert_eq!(p.len(), 5); + assert_eq!(p[1], profile_of(&ex(&preset_args(FULL).unwrap()), 0)); + assert_eq!(global, ["--wf-tcp=80,443,12", "--wf-udp=443,19294-19344,12"]); + } + + #[test] + fn default_domains_pick_the_list_and_the_family() { + let r: HostlistRule = serde_json::from_value(serde_json::json!({ "name": "yt", "defaultDomains": ["youtube"], "domains": ["extra.example"] })).unwrap(); + let rule = rule(&r, &lists()).unwrap(); + assert_eq!(rule.domains, ["youtube.com", "googlevideo.com", "extra.example"]); + assert_eq!(rule.families, ["google"]); + let out = rules(serde_json::json!({ "name": "yt", "defaultDomains": ["youtube"] })).unwrap(); + assert!(profile_of(&out, 0).contains(&"--dpi-desync=multisplit".to_owned())); + assert!(profile_of(&out, 0).contains(&"--hostlist=L\\list-yt.txt".to_owned())); + } + + #[test] + fn another_preset_brings_its_ports_and_discord_voice() { + let out = rules(serde_json::json!({ "name": "d", "defaultDomains": ["discord"], "configName": "other" })).unwrap(); + let (global, p) = profiles(&out); + assert_eq!(global, ["--wf-tcp=12,80,443,2053", "--wf-udp=12,443,19294-19344"]); + assert!(p[0].contains(&"--dpi-desync=hostfakesplit".to_owned())); + assert!(p[1].contains(&"--filter-l7=discord,stun".to_owned())); + } + + #[test] + fn own_args_and_ips() { + let out = rules(serde_json::json!({ "name": "c", "domains": ["a.example"], "ips": ["198.51.100.0/24"], "nfqwsArgs": ["--filter-tcp=8080 --hostlist=x.txt --dpi-desync=fake"] })).unwrap(); + let (global, p) = profiles(&out); + assert_eq!(global[0], "--wf-tcp=12,80,443,8080"); + // The ipset-all profile, pointed at the rule's addresses; then its own args, twice. + assert!(p[0].contains(&"--ipset=L\\ipset-c.txt".to_owned()) && p[0].contains(&"--filter-tcp=80,443".to_owned())); + assert_eq!(&p[1][..3], ["--filter-tcp=8080", "--dpi-desync=fake", "--hostlist=L\\list-c.txt"]); + assert!(p[2].contains(&"--ipset=L\\ipset-c.txt".to_owned()) && !p[2].iter().any(|a| a.starts_with("--hostlist="))); + } + + #[test] + fn what_the_windows_release_lacks_is_an_error() { + assert!(rules(serde_json::json!({ "name": "i", "defaultDomains": ["instagram"] })).unwrap_err().contains("instagram")); + let err = rules(serde_json::json!({ "name": "g", "domains": ["a.example"], "preset": "google", "configName": "other" })).unwrap_err(); + assert!(err.contains("no google profile"), "{err}"); + } + #[test] fn carets_escape_as_cmd_has_them() { let args = preset_args("\"%BIN%winws.exe\" --dpi-desync-fake-tls=^! --x=\"a^b\" ^\n--y=^^z").unwrap(); @@ -312,6 +656,13 @@ start "zapret: %~n0" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf- let (d, i) = direct_sync(&z, "discord.com\n^dns.google\n# c\nyoutube.com\n", "googlevideo.com\n", "", "203.0.113.113/32\n", ""); assert_eq!(d, ["discord.com", "dns.google", "googlevideo.com", "mine.example"]); assert!(i.is_empty()); + z.discord_youtube.hostlist_rules = vec![ + serde_json::from_value(serde_json::json!({ "name": "s", "domains": ["synced.example"], "ips": ["198.51.100.1"], "preset": "general", "enableDirectSync": true })).unwrap(), + serde_json::from_value(serde_json::json!({ "name": "n", "domains": ["unsynced.example"], "preset": "general", "enableDirectSync": false })).unwrap(), + ]; + let (d, i) = direct_sync(&z, "discord.com\n", "", "", "", ""); + assert_eq!(d, ["discord.com", "mine.example", "synced.example"]); + assert_eq!(i, ["198.51.100.1"]); z.direct_sync.enable = false; assert_eq!(direct_sync(&z, "x.com", "", "", "", "").0, Vec::::new()); } diff --git a/windows/crates/ps-core/src/zapret2.rs b/windows/crates/ps-core/src/zapret2.rs index d79f872..9b8fc78 100644 --- a/windows/crates/ps-core/src/zapret2.rs +++ b/windows/crates/ps-core/src/zapret2.rs @@ -196,7 +196,7 @@ fn port_list(values: &[serde_json::Value]) -> String { } /// Ports as ranges, merged: upstream's ports.awk. -fn merge_ports(lists: &[&str]) -> String { +pub(crate) fn merge_ports(lists: &[&str]) -> String { let mut on = vec![false; 65537]; for list in lists { for p in list.split(',') { diff --git a/windows/crates/ps-ctl/tests/e2e.rs b/windows/crates/ps-ctl/tests/e2e.rs index 4179768..78db83d 100644 --- a/windows/crates/ps-ctl/tests/e2e.rs +++ b/windows/crates/ps-ctl/tests/e2e.rs @@ -187,3 +187,111 @@ fn a_page_through_the_whole_stack() { assert!(ctl(&socket, &["proxy", "rules"]).1.contains("process:Telegram.exe")); let _ = std::fs::remove_dir_all(&dir); } + +/// A program on PATH, by its full path (sshd will not run by a bare name). +fn on_path(name: &str) -> Option { + std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join(name)).find(|f| f.is_file())) +} + +/// The SSH tunnel, offline: an sshd of the test's own on loopback, the service running +/// OpenSSH's `-D` listener to it and sing-box's SSH outbound, a page fetched through each. +#[test] +fn an_ssh_tunnel() { + let (Some(sshd), Some(keygen), true) = (on_path("sshd"), on_path("ssh-keygen"), Command::new("sing-box").arg("version").output().is_ok()) else { + eprintln!("sshd, ssh-keygen or sing-box is not on PATH: skipping"); + return; + }; + let dir = std::env::temp_dir().join(format!("ps-e2e-ssh-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (ssh_port, web_port, socks_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port(), free_port()); + + // On every address: sing-box's outbound is reached by this machine's name (below). + let web = TcpListener::bind(("0.0.0.0", web_port)).unwrap(); + std::thread::spawn(move || { + for mut s in web.incoming().flatten() { + let mut buf = [0u8; 1024]; + let _ = s.read(&mut buf); + let _ = s.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 15\r\n\r\nhello-over-ssh!"); + } + }); + + for key in ["hostkey", "id"] { + assert!(Command::new(&keygen).args(["-q", "-t", "ed25519", "-N", "", "-f"]).arg(dir.join(key)).status().unwrap().success()); + } + std::fs::copy(dir.join("id.pub"), dir.join("authorized_keys")).unwrap(); + let host_key = std::fs::read_to_string(dir.join("hostkey.pub")).unwrap().split_whitespace().take(2).collect::>().join(" "); + std::fs::write( + dir.join("sshd_config"), + format!( + "Port {ssh_port}\nListenAddress 127.0.0.1\nHostKey {d}/hostkey\nPidFile {d}/sshd.pid\nAuthorizedKeysFile {d}/authorized_keys\n\ + UsePAM no\nStrictModes no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nAllowTcpForwarding yes\n", + d = dir.display() + ), + ) + .unwrap(); + let _sshd = Kill(Command::new(&sshd).args(["-D", "-e", "-f"]).arg(dir.join("sshd_config")).stderr(std::fs::File::create(dir.join("sshd.log")).unwrap()).spawn().unwrap()); + + let state = dir.join("state"); + std::fs::create_dir_all(&state).unwrap(); + let user = std::env::var("USER").unwrap_or_else(|_| "root".into()); + let config = serde_json::json!({ + "proxy": { + "enable": true, + "listener": { "port": proxy_port }, + "singBox": { "clashApiPort": clash_port, "testPort": test_port }, + "routing": { "directRu": false }, + }, + "sshProxy": { + "enable": true, + "server": { "host": "127.0.0.1", "port": ssh_port, "user": user }, + "identityFile": dir.join("id").to_string_lossy(), + "hostKey": [host_key], + "listener": { "port": socks_port }, + "asOutbound": true, + }, + }); + std::fs::write(state.join("config.json"), config.to_string()).unwrap(); + let socket = dir.join("api.sock"); + let _service = Kill( + Command::new(service_binary()) + .args(["--console", "--state-dir"]) + .arg(&state) + .arg("--socket") + .arg(&socket) + .stderr(std::fs::File::create(dir.join("service.log")).unwrap()) + .spawn() + .unwrap(), + ); + wait_for("the service's API", Duration::from_secs(10), || ctl(&socket, &["status"]).0); + let diagnose = || { + format!( + "status:\n{}\nlogs:\n{}\nsshd:\n{}\nrendered:\n{}", + ctl(&socket, &["status"]).1, + ctl(&socket, &["logs", "-n", "40"]).1, + std::fs::read_to_string(dir.join("sshd.log")).unwrap_or_default(), + ctl(&socket, &["proxy", "config"]).1 + ) + }; + + // OpenSSH's listener, as other programs use it. + let body = (0..40).find_map(|_| { + std::thread::sleep(Duration::from_millis(250)); + socks_get(socks_port, "127.0.0.1", web_port).ok() + }); + assert!(body.as_deref().is_some_and(|b| b.ends_with("hello-over-ssh!")), "no page through ssh -D\n{}", diagnose()); + + // sing-box's own SSH outbound. The proxy refuses loopback destinations (a guard), so the + // page is asked for by this machine's name, which the SSH server resolves for itself. + let host = std::fs::read_to_string("/proc/sys/kernel/hostname").unwrap_or_default().trim().to_owned(); + assert!(ctl(&socket, &["proxy", "pin", "ssh-proxy"]).0, "{}", diagnose()); + let body = (0..40).find_map(|_| { + std::thread::sleep(Duration::from_millis(250)); + socks_get(proxy_port, &host, web_port).ok().filter(|b| b.ends_with("hello-over-ssh!")) + }); + assert!(body.is_some(), "no page through sing-box's SSH outbound\n{}", diagnose()); + // Two logins with the copied key: OpenSSH's, then sing-box's. + let logins = std::fs::read_to_string(dir.join("sshd.log")).unwrap_or_default().matches("Accepted publickey").count(); + assert_eq!(logins, 2, "{}", diagnose()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/windows/crates/ps-service/src/main.rs b/windows/crates/ps-service/src/main.rs index e523012..33f6cd1 100644 --- a/windows/crates/ps-service/src/main.rs +++ b/windows/crates/ps-service/src/main.rs @@ -12,6 +12,7 @@ mod install; mod job; mod paths; mod service; +mod ssh; mod store; mod tg; mod units; diff --git a/windows/crates/ps-service/src/service.rs b/windows/crates/ps-service/src/service.rs index 32e97ae..c8f4fa4 100644 --- a/windows/crates/ps-service/src/service.rs +++ b/windows/crates/ps-service/src/service.rs @@ -104,6 +104,8 @@ impl Service { direct_processes: direct, groups_watched: false, sidecar_secret: self.sidecar_secret.clone(), + ssh_identity_path: cfg.ssh_proxy.identity_file.as_ref().map(|_| crate::ssh::identity_path(paths).to_string_lossy().into_owned()), + ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() }, windows: cfg!(windows), ..Default::default() } @@ -134,8 +136,24 @@ impl Service { if let Err(e) = &tg { self.sup.note(crate::tg::UNIT, format!("proxy-suite: tg-ws-proxy: {e:#}")); } + // Before the proxy: it copies the key sing-box's SSH outbound reads. + let ssh = self.apply_ssh().await; + if let Err(e) = &ssh { + self.sup.note(crate::ssh::UNIT, format!("proxy-suite: the SSH tunnel: {e:#}")); + } let proxy = self.apply_proxy().await; - zapret.and(tg).and(proxy) + zapret.and(tg).and(ssh).and(proxy) + } + + async fn apply_ssh(&mut self) -> Result<()> { + let cfg = self.cfg().clone(); + if !cfg.enable || !cfg.ssh_proxy.enable { + self.sup.stop(crate::ssh::UNIT).await; + return Ok(()); + } + let spec = crate::ssh::unit(&cfg, self.paths(), crate::ssh::program()?)?; + self.sup.ensure(spec); + Ok(()) } async fn apply_tg(&mut self) -> Result<()> { diff --git a/windows/crates/ps-service/src/ssh.rs b/windows/crates/ps-service/src/ssh.rs new file mode 100644 index 0000000..c2358f6 --- /dev/null +++ b/windows/crates/ps-service/src/ssh.rs @@ -0,0 +1,179 @@ +//! The SSH tunnel: OpenSSH's dynamic SOCKS listener (`ssh -N -D`), run as upstream's +//! ssh-proxy.nix runs it, with Windows' own client (System32\OpenSSH, there since Windows 10 +//! 1803). With the sing-box backend the proxy's `ssh-proxy` outbound is sing-box's own SSH +//! client; this listener is for other programs, and the outbound of the other backends. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use ps_core::config::Config; + +use crate::paths::{Paths, write_atomic}; +use crate::units::UnitSpec; + +pub const UNIT: &str = "proxy-suite-ssh-proxy"; + +/// The OpenSSH client. +pub fn program() -> Result { + #[cfg(windows)] + { + let root = std::env::var_os("SystemRoot").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Windows")); + let ssh = root.join(r"System32\OpenSSH\ssh.exe"); + if !ssh.is_file() { + anyhow::bail!("Windows' OpenSSH client is not installed (Settings → System → Optional features → OpenSSH Client)"); + } + Ok(ssh) + } + #[cfg(not(windows))] + Ok(PathBuf::from("ssh")) +} + +/// Where the key is copied: below the state root, which only SYSTEM and administrators reach. +/// Windows' OpenSSH refuses a key others can read, and to a service running as SYSTEM the +/// user's own copy is someone else's; upstream copies it for its service too (systemd's +/// credentials). +pub fn identity_path(paths: &Paths) -> PathBuf { + paths.root.join("ssh").join("identity") +} + +fn copy_identity(cfg: &Config, paths: &Paths) -> Result> { + let Some(src) = &cfg.ssh_proxy.identity_file else { return Ok(None) }; + let data = std::fs::read(src).with_context(|| format!("reading sshProxy.identityFile {src}"))?; + let dst = identity_path(paths); + std::fs::create_dir_all(dst.parent().unwrap())?; + write_atomic(&dst, &data)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o600))?; + } + Ok(Some(dst)) +} + +/// The server's keys as sing-box takes them (`ssh-ed25519 AAAA…`): `hostKey`, else the lines +/// of `hostKeyFile` or `knownHostsFile`, a known-hosts line's host names left off. +pub fn host_keys(cfg: &Config, read: impl Fn(&str) -> Option) -> Vec { + let s = &cfg.ssh_proxy; + if !s.host_key.is_empty() { + return s.host_key.clone(); + } + let Some(text) = s.host_key_file.as_deref().or(s.known_hosts_file.as_deref()).and_then(read) else { + return Vec::new(); + }; + text.lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(|l| { + let fields: Vec<&str> = l.split_whitespace().collect(); + // A key type comes first in a key line; in a known-hosts line, the hosts do. + let is_type = |f: &str| f.starts_with("ssh-") || f.starts_with("ecdsa-") || f.starts_with("sk-"); + match fields.iter().position(|f| is_type(f)) { + Some(at) => fields[at..].iter().take(2).copied().collect::>().join(" "), + None => l.to_owned(), + } + }) + .collect() +} + +/// The known-hosts file ssh is given: `knownHostsFile`, or one written from the server's keys, +/// or one of the service's own, where `accept-new` keeps what it accepts. +fn known_hosts(cfg: &Config, paths: &Paths, keys: &[String]) -> Result { + let s = &cfg.ssh_proxy; + if let Some(f) = &s.known_hosts_file { + return Ok(PathBuf::from(f)); + } + let dir = paths.root.join("ssh"); + std::fs::create_dir_all(&dir)?; + if keys.is_empty() { + return Ok(dir.join("known_hosts")); + } + let host = s.server.host.as_deref().unwrap_or(""); + let name = if s.server.port == 22 { host.to_owned() } else { format!("[{host}]:{}", s.server.port) }; + let text: String = keys.iter().map(|k| format!("{name} {k}\n")).collect(); + let file = dir.join("known_hosts.given"); + write_atomic(&file, text.as_bytes())?; + Ok(file) +} + +pub fn args(cfg: &Config, known_hosts: &Path, identity: Option<&Path>) -> Vec { + let s = &cfg.ssh_proxy; + // ssh reads "::1:1091" as a bad forwarding: an IPv6 address goes in brackets. + let listen = if s.listener.address.contains(':') { format!("[{}]", s.listener.address) } else { s.listener.address.clone() }; + let mut a: Vec = [ + "-N", + "-o", + "BatchMode=yes", + "-o", + "ExitOnForwardFailure=yes", + "-o", + "ServerAliveInterval=15", + "-o", + "ServerAliveCountMax=3", + "-o", + "ConnectTimeout=10", + ] + .map(String::from) + .to_vec(); + a.extend(["-o".into(), format!("StrictHostKeyChecking={}", s.strict_host_key_checking.as_str())]); + a.extend(["-o".into(), format!("UserKnownHostsFile={}", known_hosts.display())]); + a.extend(["-D".into(), format!("{listen}:{}", s.listener.port)]); + if s.server.port != 22 { + a.extend(["-p".into(), s.server.port.to_string()]); + } + if let Some(identity) = identity { + // That key alone: not an agent's or ~/.ssh's first, which can use up the server's + // MaxAuthTries before it. + a.extend(["-i".into(), identity.display().to_string(), "-o".into(), "IdentitiesOnly=yes".into()]); + } + a.extend(s.extra_args.iter().cloned()); + let host = s.server.host.clone().unwrap_or_default(); + a.push(match &s.server.user { + Some(u) => format!("{u}@{host}"), + None => host, + }); + a +} + +pub fn unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result { + let keys = host_keys(cfg, |f| std::fs::read_to_string(f).ok()); + let known = known_hosts(cfg, paths, &keys)?; + let identity = copy_identity(cfg, paths)?; + let args = args(cfg, &known, identity.as_deref()); + Ok(UnitSpec { name: UNIT.into(), program, generation: args.join("\n"), args, env: Vec::new(), cwd: None }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cfg() -> Config { + let mut c = Config::default(); + c.ssh_proxy.enable = true; + c.ssh_proxy.server.host = Some("vps.example".into()); + c.ssh_proxy.server.user = Some("me".into()); + c + } + + #[test] + fn upstreams_flags() { + let mut c = cfg(); + c.ssh_proxy.server.port = 2222; + let a = args(&c, Path::new("kh"), Some(Path::new(r"C:\keys\id_ed25519"))); + assert_eq!(&a[..2], ["-N", "-o"]); + assert!(a.windows(2).any(|w| w == ["-D", "127.0.0.1:1091"]), "{a:?}"); + assert!(a.windows(2).any(|w| w == ["-p", "2222"])); + assert!(a.windows(2).any(|w| w == ["-i", r"C:\keys\id_ed25519"])); + assert!(a.contains(&"UserKnownHostsFile=kh".to_owned())); + assert_eq!(a.last().unwrap(), "me@vps.example"); + } + + #[test] + fn host_keys_from_lines_of_either_kind() { + let mut c = cfg(); + c.ssh_proxy.host_key_file = Some("f".into()); + let keys = host_keys(&c, |_| Some("# c\nvps.example ssh-ed25519 AAAA1\nssh-rsa BBBB2 comment\n".into())); + assert_eq!(keys, ["ssh-ed25519 AAAA1", "ssh-rsa BBBB2"]); + c.ssh_proxy.host_key = vec!["ssh-ed25519 CCCC".into()]; + assert_eq!(host_keys(&c, |_| None), ["ssh-ed25519 CCCC"]); + } +} diff --git a/windows/crates/ps-service/src/zapret.rs b/windows/crates/ps-service/src/zapret.rs index e4079da..e85a05a 100644 --- a/windows/crates/ps-service/src/zapret.rs +++ b/windows/crates/ps-service/src/zapret.rs @@ -84,12 +84,32 @@ pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Re all.push_str(&user.ipset_all_extra); write_atomic(&lists.join("ipset-all.txt"), all.as_bytes())?; } - if !y.hostlist_rules.is_empty() { - tracing::warn!("zapret.zapret-discord-youtube.hostlistRules are not applied on Windows yet"); + + // The hostlist rules: their sites in their own lists, their profiles ahead of the preset's. + let read = |f: &str| std::fs::read_to_string(release.join(f)).unwrap_or_default(); + let (general, google, ipset_all) = (read("list-general.txt"), read("list-google.txt"), read("ipset-all.txt")); + let release_lists = zapret::ReleaseLists { general: &general, google: &google, ipset_all: &ipset_all }; + let rules = y.hostlist_rules.iter().map(|r| zapret::rule(r, &release_lists)).collect::, _>>().map_err(anyhow::Error::msg)?; + let mut rule_files = Vec::new(); + for rule in &rules { + let (list, ipset) = zapret::rule_lists(rule); + for (file, entries) in [(list, &rule.domains), (ipset, &rule.ips)] { + if !entries.is_empty() { + write_atomic(&lists.join(&file), format!("{}\n", entries.join("\n")).as_bytes())?; + rule_files.push(file); + } + } } let bin_dir = component.join("bin"); - let mut argv = zapret::expand(&args, &with_sep(&bin_dir), &with_sep(&lists), &with_sep(&component), y.game_filter); + let (bin_s, lists_s, root_s) = (with_sep(&bin_dir), with_sep(&lists), with_sep(&component)); + let expand = |a: &[String]| zapret::expand(a, &bin_s, &lists_s, &root_s, y.game_filter); + let source = |name: &str| -> Result, String> { + let file = zapret::find_preset(&bats, name)?; + let bat = std::fs::read(component.join(&file)).map_err(|e| format!("{file}: {e}"))?; + Ok(expand(&zapret::preset_args(&String::from_utf8_lossy(&bat))?)) + }; + let mut argv = zapret::with_rules(expand(&args), &rules, &lists_s, &source, &expand).map_err(anyhow::Error::msg)?; if cfg.debug.log_level != ps_core::config::LogLevel::Warn { argv.insert(0, "--debug=1".into()); } @@ -101,8 +121,8 @@ pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Re h.update(a.as_bytes()); h.update(b"\n"); } - for f in ["list-general-user.txt", "list-exclude-user.txt", "ipset-exclude-user.txt", "ipset-all.txt"] { - h.update(std::fs::read(lists.join(f)).unwrap_or_default()); + for f in ["list-general-user.txt", "list-exclude-user.txt", "ipset-exclude-user.txt", "ipset-all.txt"].iter().map(|f| f.to_string()).chain(rule_files) { + h.update(std::fs::read(lists.join(&f)).unwrap_or_default()); } h.finalize().iter().map(|b| format!("{b:02x}")).collect() }; diff --git a/windows/flake.nix b/windows/flake.nix index 131e050..cc5ab06 100644 --- a/windows/flake.nix +++ b/windows/flake.nix @@ -52,6 +52,8 @@ curl git python3Packages.pip + # The SSH tunnel's end-to-end test runs an sshd of its own. + openssh ]; buildInputs = guiLibs; LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath guiLibs; diff --git a/windows/release-notes/0.2.0-pre.1.md b/windows/release-notes/0.2.0-pre.1.md index e2f310f..a920cc6 100644 --- a/windows/release-notes/0.2.0-pre.1.md +++ b/windows/release-notes/0.2.0-pre.1.md @@ -16,6 +16,9 @@ The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ct `install.cmd` puts it in the Start Menu and starts it at every sign-in, in the tray. ### Also +- zapret's `hostlistRules`: a group of sites with its own strategy, copied from a preset (or another one, `configName`) or given as `nfqwsArgs`, ahead of the preset's own; every preset with them checked by Flowseal's `winws.exe`. +- The SSH tunnel (`sshProxy`): Windows' own OpenSSH as a SOCKS listener for other programs, and, with `asOutbound`, an outbound of the proxy. Needs Windows' "OpenSSH Client" (there by default since Windows 10 1809). +- What is not on Windows yet (the kill switch, AmneziaWG, WARP, Tor, the SSH tunnel, …) is no longer accepted silently: the service warns while it is configured, and the app shows it. - The service names zapret's presets and gives tg-ws-proxy's links (`proxy-ctl zapret presets`, `proxy-ctl tg link`). - Built and published by Gitea Actions. @@ -23,7 +26,7 @@ The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ct Download `ProxySuite-0.2.0-pre.1-windows-x64.zip`; its SHA-256 is in the `.sha256` file next to it. Unzip, run `install.cmd` as administrator, then open **Proxy Suite** from the Start Menu. Needs 64-bit Windows 10 (1903 or later) or 11. ### Not yet -AmneziaWG, WARP, Tor, the SSH tunnel, whitelist-bypass, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies. +AmneziaWG, WARP, Tor, whitelist-bypass, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies. ### Note Unlike upstream, the signed-in user may change every setting by default (`userControl`), except the ones that could run programs or read files as SYSTEM: those always need an administrator. On a shared computer, restrict `userControl.scopes`. diff --git a/windows/tools/winws-dry-run.sh b/windows/tools/winws-dry-run.sh index 6f29434..fd538aa 100755 --- a/windows/tools/winws-dry-run.sh +++ b/windows/tools/winws-dry-run.sh @@ -32,6 +32,24 @@ while IFS= read -r preset; do done < <(ls "$REL"/*.bat | xargs -n1 -d '\n' basename | grep -vi '^service' | sed 's/\.bat$//') echo "$((n - fail))/$n preset runs verified by winws.exe" +# The same presets with hostlistRules (tools/zapret-rules-sample.json): their profiles ahead. +r=0 na=0 +while IFS= read -r preset; do + built=$(target/debug/examples/zapret_args "$REL" "$(win "$REL")" "$(win "$WORK/lists")" "$preset" null tools/zapret-rules-sample.json "$WORK/lists" 2>&1) || { + # A preset without a profile a rule's family needs: refused, as upstream refuses it. + if grep -q "the preset has no .* profile to copy" <<<"$built"; then na=$((na + 1)); echo " $preset: $built"; continue; fi + fail=$((fail + 1)); echo "FAIL: $preset with rules: $built"; continue + } + mapfile -t args <<<"$built" + r=$((r + 1)) + if out=$(cd "$REL/bin" && wine ./winws.exe --dry-run "${args[@]}" 2>&1) && grep -q "parameters verified" <<<"$out"; then + : + else + fail=$((fail + 1)); echo "FAIL: $preset with rules"; grep -v Cygwin <<<"$out" | tail -4 + fi +done < <(ls "$REL"/*.bat | xargs -n1 -d '\n' basename | grep -vi '^service' | sed 's/\.bat$//') +echo "$r presets with hostlist rules verified by winws.exe; $na refused, lacking a profile a rule copies" + # zapret2: nfqws2-keenetic's strategies as the service renders them, its lists in place. Z2="$STAGE/zapret2" mkdir -p "$WORK/z2/learned" && : > "$WORK/z2/zapret-hosts-user.txt" && : > "$WORK/z2/zapret-hosts-user-exclude.txt" && : > "$WORK/z2/learned/zapret-hosts-auto.txt" diff --git a/windows/tools/zapret-rules-sample.json b/windows/tools/zapret-rules-sample.json new file mode 100644 index 0000000..7dd31d4 --- /dev/null +++ b/windows/tools/zapret-rules-sample.json @@ -0,0 +1,6 @@ +[ + { "name": "mine", "domains": ["example.com"], "preset": "general" }, + { "name": "yt", "defaultDomains": ["youtube"], "domains": ["extra.example"] }, + { "name": "voice", "defaultDomains": ["discord"], "configName": "general (ALT9)" }, + { "name": "own", "domains": ["own.example"], "ips": ["198.51.100.0/24"], "nfqwsArgs": ["--filter-tcp=8443 --dpi-desync=fake --dpi-desync-repeats=6"] } +]