//! zapret on Windows: the unit that runs winws.exe (zapret-discord-youtube) with the //! configured preset, and the lists it reads. use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; use ps_core::config::{Config, ZapretEngine}; use ps_core::zapret; use crate::paths::{Paths, write_atomic}; use crate::units::UnitSpec; pub const UNIT: &str = "proxy-suite-zapret"; /// The release's list files, as `zapret::direct_sync` reads them. pub struct ReleaseLists { pub general: String, pub google: String, pub exclude: String, pub ipset_all: String, pub ipset_exclude: String, } pub fn release_lists(component: &Path) -> ReleaseLists { let read = |f: &str| std::fs::read_to_string(component.join("lists").join(f)).unwrap_or_default(); ReleaseLists { general: read("list-general.txt"), google: read("list-google.txt"), exclude: read("list-exclude.txt"), ipset_all: read("ipset-all.txt"), ipset_exclude: read("ipset-exclude.txt"), } } /// The domains and addresses `zapret.directSync` sends direct. pub fn direct_sync(cfg: &Config, bin: &Path) -> (Vec, Vec) { if !cfg.enable || !cfg.zapret.enable || cfg.zapret.engine != ZapretEngine::DiscordYoutube { return zapret::direct_sync(&cfg.zapret, "", "", "", "", ""); } let l = release_lists(&bin.join("zapret")); zapret::direct_sync(&cfg.zapret, &l.general, &l.google, &l.exclude, &l.ipset_all, &l.ipset_exclude) } fn with_sep(p: &Path) -> String { let s = p.to_string_lossy().into_owned(); let sep = if cfg!(windows) { '\\' } else { '/' }; if s.ends_with(sep) { s } else { format!("{s}{sep}") } } /// The unit for zapret-discord-youtube: the preset's winws.exe line, with the lists in the /// service's run directory (the release's own, the user's entries added) and the game /// filter. `program` is the verified winws.exe. pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result { let y = &cfg.zapret.discord_youtube; let component = paths.bin().join("zapret"); let bats: Vec = std::fs::read_dir(&component) .with_context(|| format!("reading {}", component.display()))? .filter_map(|e| e.ok()?.file_name().into_string().ok()) .collect(); let file = zapret::find_preset(&bats, &y.config_name).map_err(anyhow::Error::msg)?; let bat = std::fs::read(component.join(&file))?; let args = zapret::preset_args(&String::from_utf8_lossy(&bat)).map_err(anyhow::Error::msg)?; // The lists: the release's, copied, with the user's beside them. let lists = paths.run().join("zapret").join("lists"); std::fs::create_dir_all(&lists)?; let release = component.join("lists"); for entry in std::fs::read_dir(&release)?.flatten() { let name = entry.file_name(); if name.to_string_lossy().ends_with(".txt") { std::fs::copy(entry.path(), lists.join(&name))?; } } let exempt: &[String] = if cfg.zapret.cidr_exemption.enable { &cfg.zapret.cidr_exemption.cidrs } else { &[] }; let user = zapret::user_lists(y, exempt); write_atomic(&lists.join("list-general-user.txt"), user.general_user.as_bytes())?; write_atomic(&lists.join("list-exclude-user.txt"), user.exclude_user.as_bytes())?; write_atomic(&lists.join("ipset-exclude-user.txt"), user.ipset_exclude_user.as_bytes())?; if !user.ipset_all_extra.is_empty() { let mut all = std::fs::read_to_string(lists.join("ipset-all.txt")).unwrap_or_default(); if !all.ends_with('\n') && !all.is_empty() { all.push('\n'); } all.push_str(&user.ipset_all_extra); write_atomic(&lists.join("ipset-all.txt"), all.as_bytes())?; } // 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 (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()); } // A change of the arguments or of a list winws reads is a restart. let generation = { use sha2::{Digest, Sha256}; let mut h = Sha256::new(); for a in &argv { 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"].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() }; Ok(UnitSpec { name: UNIT.into(), program, args: argv, env: Vec::new(), cwd: Some(bin_dir), generation }) } /// TCP timestamps on, as Flowseal's and bol-van's installers turn them on: strategies that /// fool DPI with them need them. pub async fn enable_tcp_timestamps() -> Result<()> { if !cfg!(windows) { return Ok(()); } let status = tokio::process::Command::new("netsh") .args(["interface", "tcp", "set", "global", "timestamps=enabled"]) .status() .await .context("running netsh")?; if !status.success() { bail!("netsh could not turn TCP timestamps on"); } Ok(()) } /// The unit for zapret2: winws2 with nfqws2-keenetic's strategies (ps_core::zapret2), its /// lists in the service's `zapret2\\` directory, the learned one where winws2 can still write /// once it runs at Low integrity. pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result { use ps_core::zapret2; let z = &cfg.zapret.zapret2; let component = paths.bin().join("zapret2"); let conf = std::fs::read_to_string(component.join("keenetic").join("nfqws2.conf")).context("reading nfqws2-keenetic's nfqws2.conf")?; let source = zapret2::keenetic(&conf, &with_sep(&component.join("keenetic"))).map_err(anyhow::Error::msg)?; let state = paths.root.join("zapret2"); let learned = state.join("learned"); std::fs::create_dir_all(&learned)?; #[cfg(windows)] low_integrity(&learned)?; let user = state.join("zapret-hosts-user.txt"); let exclude = state.join("zapret-hosts-user-exclude.txt"); let auto = learned.join("zapret-hosts-auto.txt"); // nfqws2 refuses a list it cannot open; an empty one is fine. for f in [&user, &exclude, &auto] { if !f.exists() { std::fs::write(f, b"")?; } } let p = zapret2::Paths { lua: with_sep(&component.join("lua")), user: user.to_string_lossy().into_owned(), exclude: exclude.to_string_lossy().into_owned(), auto: auto.to_string_lossy().into_owned(), }; let argv = zapret2::args(z, &source, &p, cfg.debug.zapret2.packets).map_err(anyhow::Error::msg)?; let generation = { use sha2::{Digest, Sha256}; let mut h = Sha256::new(); for a in &argv { h.update(a.as_bytes()); h.update(b"\n"); } h.finalize().iter().map(|b| format!("{b:02x}")).collect() }; Ok(UnitSpec { name: UNIT.into(), program, args: argv, env: Vec::new(), cwd: Some(component), generation }) } /// A Low mandatory label on `dir`, inherited below it: what a Low-integrity process (winws2, /// once it runs) may still write to. Its DACL stays as it is. #[cfg(windows)] fn low_integrity(dir: &Path) -> Result<()> { use std::ffi::c_void; use std::os::windows::ffi::OsStrExt; use std::ptr::null_mut; use windows_sys::Win32::Foundation::{ERROR_SUCCESS, LocalFree}; use windows_sys::Win32::Security::Authorization::{ ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, SE_FILE_OBJECT, SetNamedSecurityInfoW, }; use windows_sys::Win32::Security::{ACL, GetSecurityDescriptorSacl, LABEL_SECURITY_INFORMATION}; let sddl: Vec = "S:(ML;OICI;NW;;;LW)".encode_utf16().chain(Some(0)).collect(); let path: Vec = dir.as_os_str().encode_wide().chain(Some(0)).collect(); let mut sd: *mut c_void = null_mut(); // SAFETY: NUL-terminated inputs; the SACL points into sd, freed below. unsafe { if ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut()) == 0 { return Err(std::io::Error::last_os_error().into()); } let (mut present, mut defaulted) = (0, 0); let mut sacl: *mut ACL = null_mut(); GetSecurityDescriptorSacl(sd, &mut present, &mut sacl, &mut defaulted); let rc = SetNamedSecurityInfoW(path.as_ptr() as *mut u16, SE_FILE_OBJECT, LABEL_SECURITY_INFORMATION, null_mut(), null_mut(), null_mut(), sacl); LocalFree(sd); if rc != ERROR_SUCCESS { return Err(std::io::Error::from_raw_os_error(rc as i32).into()); } } Ok(()) }