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 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 07:37:29 +03:00
1 parent 88c8b88a49
commit fb6c5962d0
14 files changed
+776 -24

No files matched your search

+36 -7
View File
@@ -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 <release dir> <lists dir> <preset> <game filter>`, paths as
//! Windows sees them (with a trailing separator).
//! per line. `zapret_args <release dir> <release dir as Windows sees it> <lists dir as Windows
//! sees it> <preset> <game filter> [<hostlistRules JSON> <lists dir>]`, 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<String> = 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<String> = 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<Vec<String>, 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<HostlistRule> = 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}");
}
}
+17 -4
View File
@@ -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-<name>.txt and ipset-<name>.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");
}
+352 -1
View File
@@ -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<String> {
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<String>,
pub ips: Vec<String>,
/// 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<String>,
pub nfqws_args: Vec<String>,
}
/// 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<Rule, String> {
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<String>| {
let mut seen = BTreeSet::new();
v.into_iter().filter(|x| !x.is_empty() && seen.insert(x.clone())).collect::<Vec<_>>()
};
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<String>, Vec<Vec<String>>) {
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<String> {
let other = if option == "--hostlist=" { "--ipset=" } else { "--hostlist=" };
let mut out: Vec<String> = 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<String>,
rules: &[Rule],
lists: &str,
source: &dyn Fn(&str) -> Result<Vec<String>, String>,
expand: &dyn Fn(&[String]) -> Vec<String>,
) -> Result<Vec<String>, String> {
if rules.is_empty() {
return Ok(args);
}
let (mut global, own) = profiles(&args);
let excludes: Vec<String> = [
("--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<String>> = Vec::new();
// What WinDivert has to let through for them: their filters' ports, another preset's own.
let (mut tcp, mut udp): (Vec<String>, Vec<String>) = (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<String>> = 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<String>> = 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<String>> = 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<String> = 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<String> {
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<Vec<String>, 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<String> {
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::<String>::new());
}
+1 -1
View File
@@ -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(',') {
+108
View File
@@ -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<PathBuf> {
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::<Vec<_>>().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);
}
+1
View File
@@ -12,6 +12,7 @@ mod install;
mod job;
mod paths;
mod service;
mod ssh;
mod store;
mod tg;
mod units;
+19 -1
View File
@@ -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<()> {
+179
View File
@@ -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<PathBuf> {
#[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<Option<PathBuf>> {
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<String>) -> Vec<String> {
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::<Vec<_>>().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<PathBuf> {
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<String> {
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<String> = [
"-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<UnitSpec> {
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"]);
}
}
+25 -5
View File
@@ -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::<Result<Vec<_>, _>>().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<Vec<String>, 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()
};