diff --git a/windows/Cargo.lock b/windows/Cargo.lock index 5622fae..8d02e7e 100644 --- a/windows/Cargo.lock +++ b/windows/Cargo.lock @@ -5007,6 +5007,7 @@ dependencies = [ "ps-client", "ps-core", "ps-ipc", + "rpassword", "serde_json", "tokio", ] @@ -5623,6 +5624,27 @@ dependencies = [ "memchr", ] +[[package]] +name = "rpassword" +version = "7.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "rust-embed" version = "8.13.0" diff --git a/windows/Cargo.toml b/windows/Cargo.toml index 5f586bf..f05185b 100644 --- a/windows/Cargo.toml +++ b/windows/Cargo.toml @@ -22,6 +22,7 @@ ipnet = "2" indexmap = { version = "2", features = ["serde"] } tokio = { version = "1.54", features = ["rt-multi-thread", "macros", "net", "io-util", "process", "time", "sync", "fs", "signal"] } clap = { version = "4.6", features = ["derive"] } +rpassword = "7" reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "socks", "json", "stream", "http2", "query"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } windows-service = "0.8" diff --git a/windows/README.md b/windows/README.md index b3bbb13..aaad27c 100644 --- a/windows/README.md +++ b/windows/README.md @@ -26,11 +26,12 @@ tray icon) or with `proxy-ctl`, as upstream's is. | Tor | `tor`: the Tor Project's own Windows build (the Expert Bundle, signed, pinned), with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy | | AmneziaWG | `amneziaWg` profiles as outbounds, from a `.conf`, an AmneziaVPN `vpn://` link or settings: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too | | WARP | `warp` with `asOutbound = "singBox"` or `"userspace"`: each device registered with Cloudflare as wgcf registers (through the local proxy first, then directly, then `generatorUrl`), or a profile given; a sing-box WireGuard endpoint, several grouped as `warp` | +| whitelist-bypass | `whitelistBypass`: [whitelist-bypass](https://github.com/kulikov0/whitelist-bypass)'s headless creators and joiners (WB Stream, Telemost, DION, Bitrix; VK creators), built from upstream's source: a joiner is an outbound of the proxy tunnelled through a video call, a creator the call's free end. `proxy-ctl wl` gives the links and logins | | 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 as a system-wide VPN (its driver), Tor's onion service, whitelist-bypass, +Not in this release, still to come: AmneziaWG as a system-wide VPN (its driver), Tor's onion service, 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. @@ -51,6 +52,7 @@ Needs 64-bit Windows 10 (1903 or later) or 11. | 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`) | | Tor | its Windows `tor.exe` (under Wine) accepts the torrc the service writes, bridges and transports included; on Linux the service runs Tor with it and Tor starts bootstrapping (where Tor's relays are blocked, it needs bridges) | | AmneziaWG | profiles from `.conf`, `vpn://` links and settings converted exactly as upstream's script converts them (its own encoder's links as test vectors); end to end on Linux: sing-box as a WireGuard server, the service running wireproxy-awg, a page through its listener and through the proxy's outbound (`an_amneziawg_tunnel`) | +| whitelist-bypass | its Windows programs built from upstream's tag with upstream's patches (links and passwords from the environment, never the command line); on Linux the service runs a joiner and a creator with their flags, the link and the login reaching them (`proxy-ctl wl join`, `wl auth`, `wl new`, `wl link`); a real call needs an account on a platform, so none was made | | WARP | a device registered live with Cloudflare by the service, its profile rendered as a sing-box endpoint and accepted; traffic through it not (this test machine blocks outgoing UDP) | | 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`) | @@ -110,6 +112,14 @@ proxy-ctl config get > config.json # set "tgWsProxy": { "enable": true } proxy-ctl config set config.json proxy-ctl logs proxy-suite-tg-ws-proxy # its tg:// link and secret +# whitelist-bypass: a joiner here (set "whitelistBypass": { "enable": true, +# "joiners": { "wl": { "platform": "wbstream" } } }), its creator's link from the other end: +proxy-ctl wl join wl "https://..." +proxy-ctl proxy pin wl +# A creator: its login (a cookies export; DION and Bitrix ask for an email and password), its call: +proxy-ctl wl auth laptop cookies.json +proxy-ctl wl link laptop + proxy-ctl logs -f # everything, following proxy-ctl --help ``` diff --git a/windows/components.json b/windows/components.json index edff6da..2ab6f4b 100644 --- a/windows/components.json +++ b/windows/components.json @@ -125,6 +125,13 @@ "homepage": "https://github.com/artem-russkikh/wireproxy-awg", "bundled": true, "sources": [] + }, + "whitelist-bypass": { + "version": "0.4.4", + "license": "MIT", + "homepage": "https://github.com/kulikov0/whitelist-bypass", + "bundled": true, + "sources": [] } } } diff --git a/windows/crates/ps-core/src/config/validate.rs b/windows/crates/ps-core/src/config/validate.rs index 35d49a6..21546e0 100644 --- a/windows/crates/ps-core/src/config/validate.rs +++ b/windows/crates/ps-core/src/config/validate.rs @@ -116,7 +116,6 @@ fn not_ported(cfg: &Config, v: &mut Issues) { (cfg.amnezia_wg.enable && cfg.amnezia_wg.profiles.values().any(|p| p.as_outbound.is_none()), "amneziaWg.profiles", "AmneziaWG as a system-wide VPN (its driver; as outbounds it is here)"), (cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"), (cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"), - (cfg.whitelist_bypass.enable, "whitelistBypass.enable", "whitelist-bypass"), (cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"), (cfg.proxy.auto_proxy.enable, "proxy.autoProxy.enable", "autoProxy"), ] { diff --git a/windows/crates/ps-ctl/Cargo.toml b/windows/crates/ps-ctl/Cargo.toml index 6f5cb1c..fc933a6 100644 --- a/windows/crates/ps-ctl/Cargo.toml +++ b/windows/crates/ps-ctl/Cargo.toml @@ -17,6 +17,7 @@ anyhow.workspace = true serde_json.workspace = true tokio.workspace = true clap.workspace = true +rpassword.workspace = true [dev-dependencies] serde_json.workspace = true diff --git a/windows/crates/ps-ctl/src/main.rs b/windows/crates/ps-ctl/src/main.rs index fa85453..e968ceb 100644 --- a/windows/crates/ps-ctl/src/main.rs +++ b/windows/crates/ps-ctl/src/main.rs @@ -54,6 +54,11 @@ enum Cmd { #[command(subcommand)] verb: TgVerb, }, + /// whitelist-bypass creators and joiners. + Wl { + #[command(subcommand)] + verb: Option, + }, /// The backend programs: what is installed, and installing them (administrator). Components { #[command(subcommand)] @@ -67,6 +72,23 @@ enum TgVerb { Link, } +#[derive(Subcommand)] +enum WlVerb { + /// Creators and joiners, and their state. + List, + /// The call a creator made, for its joiner. + Link { creator: String }, + /// A creator's login: a cookies export (a file, or - for stdin); DION and Bitrix ask for + /// an email and password without one. + Auth { creator: String, file: Option }, + /// The call link a joiner joins (or - for stdin). + Join { joiner: String, link: String }, + /// Start a new call, if the platform closed the old one. + New { creator: String }, + /// Restart all of them, or the one named. + Restart { name: Option }, +} + #[derive(Subcommand)] enum ZapretVerb { Status, @@ -245,9 +267,13 @@ fn read_arg(value: &str) -> Result { } } +/// A file's text, or stdin's for -. +fn read_arg_file(file: &str) -> Result { + if file == "-" { read_arg("-") } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}")) } +} + fn read_file_arg(file: &str) -> Result { - let text = if file == "-" { read_arg("-")? } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}"))? }; - serde_json::from_str(&text).with_context(|| format!("{file} is not JSON")) + serde_json::from_str(&read_arg_file(file)?).with_context(|| format!("{file} is not JSON")) } async fn status(ctl: &Ctl) -> Result<()> { @@ -549,6 +575,106 @@ async fn zapret(ctl: &Ctl, verb: Option) -> Result<()> { Ok(()) } +/// A login for the DION and Bitrix creators, which log in on their own from it. +fn password_login(platform: &str, name: &str) -> Result { + let fields: &[&str] = match platform { + "dion" => &["email", "password"], + "bitrix" => &["email", "password", "portal"], + _ => bail!("{platform} logs in only in a browser: export its cookies from the desktop Creator, then: proxy-ctl wl auth {name} "), + }; + let mut login = serde_json::Map::new(); + for field in fields { + let value = if *field == "password" { + rpassword::prompt_password("Password: ")? + } else { + eprint!("{}{}: ", field[..1].to_uppercase(), &field[1..]); + let mut line = String::new(); + std::io::stdin().read_line(&mut line)?; + line.trim().to_owned() + }; + let value = match *field { + "portal" => { + let portal = value.trim_end_matches('/'); + if portal.contains("://") { portal.to_owned() } else { format!("https://{portal}") } + } + _ => value, + }; + login.insert((*field).to_owned(), Value::String(value)); + } + Ok(Value::Object(login).to_string()) +} + +async fn wl(ctl: &Ctl, verb: Option) -> Result<()> { + let say = |r: &Value| println!("{}: {}", r["unit"].as_str().unwrap_or("?"), r["state"].as_str().unwrap_or("?")); + match verb.unwrap_or(WlVerb::List) { + WlVerb::List => { + let r = ctl.call(Request::WlList).await?; + if ctl.json { + ctl.print(&r); + return Ok(()); + } + let list = r.as_array().cloned().unwrap_or_default(); + if list.is_empty() { + println!("No whitelist-bypass creators or joiners configured."); + return Ok(()); + } + println!(" {:<16} {:<8} {:<10} STATUS", "NAME", "ROLE", "PLATFORM"); + for w in list { + let f = |k: &str| w[k].as_str().unwrap_or("").to_owned(); + println!(" {:<16} {:<8} {:<10} {}", f("name"), f("role"), f("platform"), f("state")); + } + } + WlVerb::Link { creator } => { + let r = ctl.call(Request::WlLink { name: creator }).await?; + println!("{}", r["link"].as_str().unwrap_or("")); + } + WlVerb::Auth { creator, file } => { + let login = match file { + Some(f) => { + let text = read_arg_file(&f)?; + serde_json::from_str::(&text).context("not a cookies export, not valid JSON")?; + text + } + None => { + let list = ctl.call(Request::WlList).await?; + let platform = list + .as_array() + .into_iter() + .flatten() + .find(|w| w["name"] == creator.as_str() && w["role"] == "creator") + .and_then(|w| w["platform"].as_str().map(str::to_owned)) + .with_context(|| format!("no whitelist-bypass creator '{creator}'"))?; + password_login(&platform, &creator)? + } + }; + say(&ctl.call(Request::WlAuth { name: creator, login }).await?); + } + WlVerb::Join { joiner, link } => { + let link = read_arg(&link)?; + say(&ctl.call(Request::WlJoin { name: joiner, link: link.trim().to_owned() }).await?); + } + WlVerb::New { creator } => { + say(&ctl.call(Request::WlNew { name: creator.clone() }).await?); + println!("Its joiner needs the new call: proxy-ctl wl link {creator}"); + } + WlVerb::Restart { name } => { + let list = ctl.call(Request::WlList).await?; + let units: Vec = list + .as_array() + .into_iter() + .flatten() + .filter(|w| name.as_deref().is_none_or(|n| w["name"] == n)) + .map(|w| format!("proxy-suite-wb-{}-{}", w["role"].as_str().unwrap_or(""), w["name"].as_str().unwrap_or(""))) + .collect(); + if units.is_empty() { + bail!("no such whitelist-bypass creator or joiner"); + } + ctl.call(Request::Restart { units }).await?; + } + } + Ok(()) +} + async fn components(ctl: &Ctl, verb: Option) -> Result<()> { match verb.unwrap_or(ComponentsVerb::List) { ComponentsVerb::List => { @@ -601,6 +727,7 @@ async fn real_main() -> Result<()> { Cmd::Proxy(p) => proxy(&ctl, p.verb).await?, Cmd::Zapret { verb } => zapret(&ctl, verb).await?, Cmd::Components { verb } => components(&ctl, verb).await?, + Cmd::Wl { verb } => wl(&ctl, verb).await?, Cmd::Tg { verb: TgVerb::Link } => { let r = ctl.call(Request::TgLinks).await?; for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) { diff --git a/windows/crates/ps-ipc/src/lib.rs b/windows/crates/ps-ipc/src/lib.rs index d4d4819..f4ba357 100644 --- a/windows/crates/ps-ipc/src/lib.rs +++ b/windows/crates/ps-ipc/src/lib.rs @@ -65,6 +65,17 @@ pub enum Request { TgLinks, /// Fetch and install components (all wanted, or the named ones). ComponentsInstall { names: Vec }, + /// whitelist-bypass's creators and joiners, and their state. + WlList, + /// The call a creator made and keeps rejoining. + WlLink { name: String }, + /// A creator's login: a cookies export, or (DION, Bitrix) the JSON of its email, password + /// and portal. + WlAuth { name: String, login: String }, + /// The call link a joiner joins. + WlJoin { name: String, link: String }, + /// Drops the call a creator rejoins: it makes a new one. + WlNew { name: String }, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] diff --git a/windows/crates/ps-service/src/api.rs b/windows/crates/ps-service/src/api.rs index f9c7c8f..3da8622 100644 --- a/windows/crates/ps-service/src/api.rs +++ b/windows/crates/ps-service/src/api.rs @@ -135,10 +135,27 @@ fn scope_of(req: &Request) -> Option { // Backend logs name the sites visited (at info), and errors may quote what was dialled. Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets), Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services), + Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass), _ => None, } } +/// Re-applies whitelist-bypass, so a unit that waited starts, and restarts `unit` on what +/// was just left for it. +async fn wl_restart(s: &mut service::Service, unit: &str) -> Response { + let started = |s: &service::Service| s.sup.status().into_iter().find(|u| u.name == unit).map(|u| u.since); + let before = started(s); + if let Err(e) = s.apply_wl().await { + return Response::err(format!("{e:#}")); + } + // Unless the apply (re)started it on a new spec, or it does not run (off, or its proxy is). + let after = started(s); + if after.is_some() && after == before { + s.sup.restart(unit); + } + Response::ok(json!({ "unit": unit, "state": s.sup.state_of(unit).as_str() })) +} + fn has_secrets(cfg: &Config, peer: &Peer) -> bool { allowed(cfg, peer, Some(Scope::Secrets)).is_ok() } @@ -476,6 +493,81 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response { } } + Request::WlList => { + let s = shared.lock().await; + let wl = &s.cfg().whitelist_bypass; + let state = |unit: String| if wl.enable { s.sup.state_of(&unit).as_str() } else { "off" }; + let mut list: Vec = wl + .creators + .iter() + .map(|(name, c)| json!({ "name": name, "role": "creator", "platform": c.platform.as_str(), "state": state(format!("{}{name}", crate::wl::CREATOR_PREFIX)) })) + .collect(); + list.extend(wl.joiners.iter().map(|(name, j)| { + json!({ "name": name, "role": "joiner", "platform": j.platform.as_str(), "state": state(format!("{}{name}", crate::wl::JOINER_PREFIX)) }) + })); + Response::ok(json!(list)) + } + + Request::WlLink { name } => { + let s = shared.lock().await; + if !s.cfg().whitelist_bypass.creators.contains_key(&name) { + return Response::err(format!("no whitelist-bypass creator '{name}'")); + } + match crate::wl::last_link(s.paths(), &name) { + Some(link) => Response::ok(json!({ "link": link })), + None => Response::err(format!("{name} has no call yet: see proxy-ctl logs {}{name}", crate::wl::CREATOR_PREFIX)), + } + } + + Request::WlAuth { name, login } => { + let mut s = shared.lock().await; + if !s.cfg().whitelist_bypass.creators.contains_key(&name) { + return Response::err(format!("no whitelist-bypass creator '{name}'")); + } + if login.len() > 1 << 20 || serde_json::from_str::(&login).is_err() { + return Response::err("not a cookies export (or a login): not valid JSON"); + } + let file = crate::wl::state_dir(s.paths()).join(format!("{name}.cookies.json")); + if let Err(e) = crate::wl::write_private(&file, login.as_bytes()) { + return Response::err(format!("{e:#}")); + } + wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await + } + + Request::WlJoin { name, link } => { + let mut s = shared.lock().await; + if !s.cfg().whitelist_bypass.joiners.contains_key(&name) { + return Response::err(format!("no whitelist-bypass joiner '{name}'")); + } + let link = link.trim(); + let link = match crate::wl::clean_link(link) { + Ok(l) if l == link => l, + _ => return Response::err("a call link is one word: a room id, a slug or a URL"), + }; + let file = crate::wl::state_dir(s.paths()).join(format!("{name}.join")); + if let Err(e) = crate::wl::write_private(&file, format!("{link}\n").as_bytes()) { + return Response::err(format!("{e:#}")); + } + wl_restart(&mut s, &format!("{}{name}", crate::wl::JOINER_PREFIX)).await + } + + Request::WlNew { name } => { + let mut s = shared.lock().await; + let Some(c) = s.cfg().whitelist_bypass.creators.get(&name) else { + return Response::err(format!("no whitelist-bypass creator '{name}'")); + }; + if c.link_file.is_some() { + return Response::err(format!("{name} rejoins the call its linkFile sets: change that instead")); + } + let file = crate::wl::state_dir(s.paths()).join(format!("{name}.link")); + if let Err(e) = std::fs::remove_file(&file) + && e.kind() != std::io::ErrorKind::NotFound + { + return Response::err(format!("removing {}: {e}", file.display())); + } + wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await + } + Request::ComponentsInstall { names } => { // Programs the service runs as SYSTEM: an administrator's call, whatever the scopes. if !peer.admin { diff --git a/windows/crates/ps-service/src/main.rs b/windows/crates/ps-service/src/main.rs index 687c705..9c9930e 100644 --- a/windows/crates/ps-service/src/main.rs +++ b/windows/crates/ps-service/src/main.rs @@ -21,6 +21,7 @@ mod units; mod warp; #[cfg(windows)] mod winsvc; +mod wl; mod zapret; use std::path::PathBuf; diff --git a/windows/crates/ps-service/src/service.rs b/windows/crates/ps-service/src/service.rs index 413d875..e3e2cfe 100644 --- a/windows/crates/ps-service/src/service.rs +++ b/windows/crates/ps-service/src/service.rs @@ -1,6 +1,6 @@ //! The service's state and what it does with it: render, write, check, (re)start, fetch. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, SystemTime}; @@ -37,6 +37,8 @@ pub struct Service { pub last_error: Option, pub last_fetch: BTreeMap, tcp_timestamps_on: bool, + /// What whitelist-bypass's units waited for at the last apply, said when it first did. + wl_waiting: BTreeSet, } fn digest(data: &[u8]) -> String { @@ -59,6 +61,7 @@ impl Service { last_error: None, last_fetch: BTreeMap::new(), tcp_timestamps_on: false, + wl_waiting: BTreeSet::new(), store, }) } @@ -99,6 +102,17 @@ impl Service { { direct.push(p.to_string_lossy().into_owned()); } + // The joiners' calls, and the creators' unless they go through the proxy. + if cfg.whitelist_bypass.enable { + let wl = &cfg.whitelist_bypass; + let joiners = wl.joiners.values().map(|j| format!("headless-{}-joiner", j.platform.as_str())); + let creators = wl.creators.values().filter(|c| c.upstream == ps_core::config::Upstream::Direct).map(|c| format!("headless-{}-creator", c.platform.as_str())); + for name in joiners.chain(creators).collect::>() { + if let Some(p) = self.comps.find("whitelist-bypass", &name) { + direct.push(p.to_string_lossy().into_owned()); + } + } + } // Tor's own connections, unless it is to go through the proxy (upstream = "proxy"). if cfg.tor.enable && cfg.tor.upstream == ps_core::config::Upstream::Direct @@ -163,8 +177,52 @@ impl Service { if let Err(e) = &awg { self.sup.note(SOCKS_UNIT, format!("proxy-suite: AmneziaWG: {e:#}")); } + let wl = self.apply_wl().await; + if let Err(e) = &wl { + self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}")); + } let proxy = self.apply_proxy().await; - zapret.and(tg).and(ssh).and(tor).and(awg).and(proxy) + zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy) + } + + /// whitelist-bypass: the joiners while the proxy they serve runs, the creators while it + /// is on; the ones no longer wanted stopped, and what the rest wait for said once. + pub async fn apply_wl(&mut self) -> Result<()> { + let cfg = self.cfg().clone(); + let mut wanted_cfg = cfg.clone(); + let on = cfg.enable && cfg.whitelist_bypass.enable; + if !self.proxy_wanted() { + wanted_cfg.whitelist_bypass.joiners.clear(); + } + let (units, waiting) = if on { + let auth = &cfg.proxy.listener.auth; + let password = match (&auth.password, &auth.password_file) { + (Some(p), _) => Some(p.clone()), + (None, Some(f)) => Some(std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?.lines().next().unwrap_or("").to_owned()), + (None, None) => None, + }; + let login = auth.username.clone().zip(password); + let hop = (self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone()); + let program = |name: &str| self.comps.program("whitelist-bypass", name); + crate::wl::units(&wanted_cfg, self.paths(), &program, (&hop.0, &hop.1), login) + } else { + (Vec::new(), Vec::new()) + }; + let waiting: BTreeSet = waiting.into_iter().collect(); + for w in waiting.difference(&self.wl_waiting) { + self.sup.note(SOCKS_UNIT, format!("proxy-suite: {w}")); + } + self.wl_waiting = waiting; + let wanted: Vec = units.iter().map(|u| u.name.clone()).collect(); + for name in self.sup.names() { + if (name.starts_with(crate::wl::JOINER_PREFIX) || name.starts_with(crate::wl::CREATOR_PREFIX)) && !wanted.contains(&name) { + self.sup.stop(&name).await; + } + } + for unit in units { + self.sup.ensure(unit); + } + Ok(()) } /// The wireproxy tunnels behind "userspace" AmneziaWG outbounds and WARP devices, while diff --git a/windows/crates/ps-service/src/wl.rs b/windows/crates/ps-service/src/wl.rs new file mode 100644 index 0000000..9e2bf4c --- /dev/null +++ b/windows/crates/ps-service/src/wl.rs @@ -0,0 +1,199 @@ +//! whitelist-bypass, as upstream's whitelist-bypass.nix runs it: joiners, each a SOCKS listener +//! on loopback (with the hop login) behind its outbound, tunnelled through a video call; and +//! creators, the free ends of those calls. Links, logins and passwords reach them through the +//! environment (the build makes those the flags' defaults), never their command lines. +//! +//! A joiner waits for its call's link (`proxy-ctl wl join`, or `linkFile`); a creator for a login +//! (`proxy-ctl wl auth`, or `cookiesFile`), which it keeps refreshing in its own working copy. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use ps_core::config::{Config, Upstream, WlCreator, WlResources}; +use ps_core::derived::ports; + +use crate::paths::{Paths, write_atomic}; +use crate::units::UnitSpec; + +pub const JOINER_PREFIX: &str = "proxy-suite-wb-joiner-"; +pub const CREATOR_PREFIX: &str = "proxy-suite-wb-creator-"; + +/// What `proxy-ctl wl` leaves for the units: links (`.join`), logins +/// (`.cookies.json`), and the creators' calls (`.link`, last line the current). +pub fn state_dir(paths: &Paths) -> PathBuf { + paths.root.join("whitelist-bypass") +} + +/// The creators' working logins, which they rewrite as they refresh them. +fn sessions_dir(paths: &Paths) -> PathBuf { + paths.root.join("whitelist-bypass-sessions") +} + +fn resources(r: WlResources) -> &'static str { + match r { + WlResources::Moderate => "moderate", + WlResources::Default => "default", + WlResources::Unlimited => "unlimited", + } +} + +/// A link as the units take it: whitespace gone, one line. +pub fn clean_link(text: &str) -> Result { + let link: String = text.chars().filter(|c| !c.is_whitespace()).collect(); + if link.is_empty() { + bail!("an empty link"); + } + if link.len() > 4096 || link.chars().any(char::is_control) { + bail!("that is not a call link"); + } + Ok(link) +} + +/// The units, and what each that cannot run yet waits for. `program` finds one of the +/// component's programs by name. +pub fn units( + cfg: &Config, + paths: &Paths, + program: &dyn Fn(&str) -> Result, + hop: (&str, &str), + proxy_login: Option<(String, String)>, +) -> (Vec, Vec) { + let w = &cfg.whitelist_bypass; + let state = state_dir(paths); + let mut units = Vec::new(); + let mut waiting = Vec::new(); + for (i, (tag, j)) in w.joiners.iter().enumerate() { + let port = ports::WL_JOINER_BASE + i as u16; + // The link `wl join` gave wins over linkFile. + let link = std::fs::read_to_string(state.join(format!("{tag}.join"))) + .ok() + .or_else(|| j.link_file.as_ref().and_then(|f| std::fs::read_to_string(f).ok())) + .and_then(|t| clean_link(&t).ok()); + let Some(link) = link else { + waiting.push(format!("whitelist-bypass joiner '{tag}' waits for its call's link: proxy-ctl wl join {tag} ")); + continue; + }; + let program = match program(&format!("headless-{}-joiner", j.platform.as_str())) { + Ok(p) => p, + Err(e) => { + waiting.push(format!("whitelist-bypass joiner '{tag}': {e:#}")); + continue; + } + }; + let args = vec!["--socks-port".into(), port.to_string(), "--socks-user".into(), hop.0.to_owned()]; + units.push(UnitSpec { + name: format!("{JOINER_PREFIX}{tag}"), + program, + generation: format!("{args:?}{link}"), + args, + env: vec![("WB_LINK".into(), link), ("WB_SOCKS_PASS".into(), hop.1.to_owned())], + cwd: None, + }); + } + for (name, c) in &w.creators { + match creator(cfg, paths, program, name, c, proxy_login.clone()) { + Ok(Some(unit)) => units.push(unit), + Ok(None) => waiting.push(format!("whitelist-bypass creator '{name}' waits for a login: proxy-ctl wl auth {name} ")), + Err(e) => waiting.push(format!("whitelist-bypass creator '{name}': {e:#}")), + } + } + (units, waiting) +} + +/// The call a creator made and keeps rejoining: the last line it wrote. +pub fn last_link(paths: &Paths, name: &str) -> Option { + let text = std::fs::read_to_string(state_dir(paths).join(format!("{name}.link"))).ok()?; + text.lines().map(str::trim).rfind(|l| !l.is_empty()).map(str::to_owned) +} + +/// Writes a file only the service reads: a link, a login. +pub fn write_private(file: &Path, data: &[u8]) -> Result<()> { + if let Some(dir) = file.parent() { + std::fs::create_dir_all(dir)?; + } + write_atomic(file, data).with_context(|| format!("writing {}", file.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600))?; + } + Ok(()) +} + +fn creator( + cfg: &Config, + paths: &Paths, + program: &dyn Fn(&str) -> Result, + name: &str, + c: &WlCreator, + proxy_login: Option<(String, String)>, +) -> Result> { + let program = program(&format!("headless-{}-creator", c.platform.as_str()))?; + let state = state_dir(paths); + let sessions = sessions_dir(paths); + std::fs::create_dir_all(&state)?; + std::fs::create_dir_all(&sessions)?; + let given = state.join(format!("{name}.cookies.json")); + let cookies = sessions.join(format!("{name}.cookies.json")); + // A login `wl auth` left replaces the working copy, then goes. + if given.is_file() { + write_private(&cookies, &std::fs::read(&given)?)?; + std::fs::remove_file(&given)?; + } else if !cookies.is_file() + && let Some(f) = &c.cookies_file + { + write_private(&cookies, &std::fs::read(f).with_context(|| format!("reading {f}"))?)?; + } + if !cookies.is_file() { + return Ok(None); + } + let links = state.join(format!("{name}.link")); + // linkFile's call, or the last one it made (empty: it makes one). + let link = match &c.link_file { + Some(f) => clean_link(&std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?)?, + None => last_link(paths, name).unwrap_or_default(), + }; + let mut args: Vec = vec![ + "--cookies".into(), + cookies.display().to_string(), + "--write-file".into(), + links.display().to_string(), + "--resources".into(), + resources(c.resources).into(), + ]; + let mut env = vec![("WB_LINK".to_owned(), link)]; + if c.upstream == Upstream::Proxy { + // From the parsed address, as Tor's: the listener's own, or loopback for a wildcard. + let l = &cfg.proxy.listener; + let host = match l.address.parse::().context("proxy.listener.address is not an IP address")? { + ip if ip.is_unspecified() => "127.0.0.1".to_owned(), + std::net::IpAddr::V6(v6) => format!("[{v6}]"), + v4 => v4.to_string(), + }; + args.extend(["--upstream-socks".into(), format!("{host}:{}", l.port)]); + if let Some((user, password)) = proxy_login { + args.extend(["--upstream-user".into(), user]); + env.push(("WB_UPSTREAM_PASS".into(), password)); + } + } + Ok(Some(UnitSpec { + name: format!("{CREATOR_PREFIX}{name}"), + program, + generation: format!("{args:?}{}", env[0].1), + args, + env, + cwd: None, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn links_are_one_clean_line() { + assert_eq!(clean_link(" https://stream.wb.ru/room/abc \n").unwrap(), "https://stream.wb.ru/room/abc"); + assert!(clean_link(" \n").is_err()); + assert!(clean_link("a\u{7}b").is_err()); + } +} diff --git a/windows/release-notes/0.2.0-pre.1.md b/windows/release-notes/0.2.0-pre.1.md index eb59f63..5ead068 100644 --- a/windows/release-notes/0.2.0-pre.1.md +++ b/windows/release-notes/0.2.0-pre.1.md @@ -20,6 +20,7 @@ The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ct - 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). - Tor (`tor`): the Tor Project's own Windows build, with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy. - AmneziaWG as outbounds (`amneziaWg`): profiles from a `.conf`, an AmneziaVPN `vpn://` link or settings; `"userspace"` runs wireproxy-awg (AmneziaWG's obfuscation kept, no driver), `"singBox"` plain WireGuard. WARP devices can be either. +- whitelist-bypass (`whitelistBypass`): its creators and joiners, built from upstream's source; a joiner is an outbound of the proxy through a video call (WB Stream, Telemost, DION, Bitrix), a creator the call's other end. `proxy-ctl wl join|auth|link|new`. - WARP (`warp`, as a sing-box outbound): devices registered with Cloudflare as wgcf registers them (through the local proxy first, where its API is blocked), or profiles given; several grouped as `warp`. - 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`). @@ -29,7 +30,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 as a system-wide VPN, Tor's onion service, whitelist-bypass, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies. +AmneziaWG as a system-wide VPN, Tor's onion service, 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/build-whitelist-bypass.sh b/windows/tools/build-whitelist-bypass.sh new file mode 100755 index 0000000..ece3799 --- /dev/null +++ b/windows/tools/build-whitelist-bypass.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# whitelist-bypass's headless ends for Windows (creators and joiners: a tunnel through the media +# servers of video calls), built from upstream's tag as upstream's pkgs/whitelist-bypass.nix +# builds them: the call link, the local proxy's password and a joiner's SOCKS password read +# from the environment by default, never the command line (any local user reads that). +# +# tools/build-whitelist-bypass.sh OUT_DIR [GOOS] (needs git, go, sed; GOOS: windows) +set -euo pipefail +OUT=$(realpath -m "${1:?output directory}") +GOOS=${2:-windows} +VERSION=0.4.4 +COMMIT=7c19a7ec40900940fe0c43ea1db7768ee632393d +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +git -c advice.detachedHead=false clone -q --depth 1 --branch "v$VERSION" https://github.com/kulikov0/whitelist-bypass "$WORK/src" +[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; } +cd "$WORK/src" + +# upstream's postPatch: flag.String("NAME", "", …) defaults to os.Getenv("VAR"). +env_default() { + local file="headless/$1/main.go" + grep -q "flag.String(\"$2\", \"\"," "$file" || { echo "$file has no flag $2 to patch"; exit 1; } + sed -i "s|flag.String(\"$2\", \"\",|flag.String(\"$2\", os.Getenv(\"$3\"),|" "$file" +} +for p in vk telemost wbstream dion bitrix; do env_default "$p" upstream-pass WB_UPSTREAM_PASS; done +for p in bitrix dion dion-joiner wbstream wbstream-joiner; do env_default "$p" room WB_LINK; done +for p in telemost-joiner wbstream-joiner dion-joiner bitrix-joiner; do env_default "$p" socks-pass WB_SOCKS_PASS; done +env_default bitrix-joiner link WB_LINK +env_default telemost tm-link WB_LINK +env_default telemost-joiner tm-link WB_LINK +env_default vk vk-link WB_LINK + +export GOTOOLCHAIN=local CGO_ENABLED=0 GOOS GOARCH=amd64 +ext= +[ "$GOOS" = windows ] && ext=.exe +rm -rf "$OUT" && mkdir -p "$OUT" +# Upstream's names (build-headless.sh): headless--creator and -joiner. +for p in vk telemost wbstream dion bitrix; do + go build -trimpath -ldflags "-s -w" -o "$OUT/headless-$p-creator$ext" "./headless/$p" +done +for p in telemost wbstream dion bitrix; do + go build -trimpath -ldflags "-s -w" -o "$OUT/headless-$p-joiner$ext" "./headless/$p-joiner" +done +cp LICENSE "$OUT/" +echo "$VERSION" >"$OUT/.version" +echo "whitelist-bypass $VERSION ($GOOS) in $OUT" diff --git a/windows/tools/package.sh b/windows/tools/package.sh index e2c0730..7c065b3 100755 --- a/windows/tools/package.sh +++ b/windows/tools/package.sh @@ -17,6 +17,7 @@ mkdir -p "$DIST/components" echo "== components" tools/build-tg-ws-proxy.sh "$DIST/components/tg-ws-proxy" tools/build-wireproxy-awg.sh "$DIST/components/wireproxy-awg" windows +tools/build-whitelist-bypass.sh "$DIST/components/whitelist-bypass" windows cargo build -q --release -p ps-service target/release/proxy-suite-service stage-components --to "$DIST/components" --cache "$CACHE" rm -rf "$DIST"/components/*.old "$DIST"/components/*.staging @@ -52,6 +53,7 @@ echo "== THIRD-PARTY.md" echo "- **zapret2** (winws2.exe, its Lua) and **nfqws2-keenetic** (its strategies, lists, blobs): MIT, https://github.com/bol-van/zapret2, https://github.com/nfqws/nfqws2-keenetic" echo "- **wintun** (inside sing-box): WireGuard's prebuilt-binary license, https://www.wintun.net" echo "- **amneziawg-go** (inside wireproxy-awg, with the suite's patch): MIT, https://github.com/amnezia-vpn/amneziawg-go" + echo "- **Go modules** (inside wireproxy-awg and whitelist-bypass, e.g. Pion's WebRTC): as each project's go.mod pins them, under their own licenses (MIT, BSD-3-Clause, Apache-2.0)" echo "- **lyrebird** and **conjure** (Tor's pluggable transports, in the Expert Bundle): their licenses are in components/tor/docs" echo "- **CPython $( sed 's/.*+py//' "$DIST/components/tg-ws-proxy/.version" )** (tg-ws-proxy): PSF License, https://www.python.org" echo "- **The programs themselves** (proxy-suite-service, proxy-ctl, proxy-suite) are built from"