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

+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(',') {