diff --git a/windows/components.json b/windows/components.json index 2ab6f4b..ce4bf75 100644 --- a/windows/components.json +++ b/windows/components.json @@ -126,6 +126,13 @@ "bundled": true, "sources": [] }, + "amneziawg": { + "version": "0-unstable-2026-08-14+e90531d", + "license": "MIT", + "homepage": "https://github.com/amnezia-vpn/amneziawg-windows", + "bundled": true, + "sources": [] + }, "whitelist-bypass": { "version": "0.4.4", "license": "MIT", diff --git a/windows/crates/ps-client/src/edits.rs b/windows/crates/ps-client/src/edits.rs index 35876a3..c61da83 100644 --- a/windows/crates/ps-client/src/edits.rs +++ b/windows/crates/ps-client/src/edits.rs @@ -268,6 +268,40 @@ pub fn remove_wl(c: &mut Value, role: &str, name: &str) -> Result<()> { } } +/// An AmneziaWG profile from an AmneziaVPN `vpn://` link or a `.conf`'s text: `kind` "vpn" +/// (system-wide), "userspace" or "singBox" (an outbound of the proxy). +pub fn add_awg_profile(c: &mut Value, name: &str, text: &str, kind: &str) -> Result<()> { + if !ps_core::config::path_name_ok(name) || name.len() > 32 { + bail!("a profile name takes up to 32 letters, digits, '.', '_' and '-', and no leading dot"); + } + let text = text.trim(); + let mut profile = if text.starts_with("vpn://") { + json!({ "vpn": text }) + } else if text.contains("[Interface]") { + json!({ "config": text }) + } else { + bail!("paste an AmneziaVPN vpn:// link or a .conf (with its [Interface])"); + }; + match kind { + "vpn" => {} + "userspace" | "singBox" => profile["asOutbound"] = kind.into(), + _ => bail!("a profile is a system-wide VPN or an outbound (userspace, singBox)"), + } + if c["amneziaWg"]["profiles"].get(name).is_some() { + bail!("there is a profile '{name}' already"); + } + set_path(c, &["amneziaWg", "profiles", name], profile); + set_path(c, &["amneziaWg", "enable"], true.into()); + Ok(()) +} + +pub fn remove_awg_profile(c: &mut Value, name: &str) -> Result<()> { + match c.get_mut("amneziaWg").and_then(|w| w.get_mut("profiles")).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) { + Some(_) => Ok(()), + None => bail!("no AmneziaWG profile '{name}'"), + } +} + /// The sites an engine also handles and those it leaves alone: for `zapret-discord-youtube` /// beside its release's lists, for `zapret2` beside its strategies' own. pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude: &[String]) -> Result<()> { @@ -292,6 +326,21 @@ pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude mod tests { use super::*; + #[test] + fn amneziawg_profiles_come_from_links_or_confs() { + let mut c = json!({}); + add_awg_profile(&mut c, "home", "vpn://AAAA", "vpn").unwrap(); + add_awg_profile(&mut c, "exit", "[Interface]\nPrivateKey = x\n", "userspace").unwrap(); + assert_eq!(c["amneziaWg"]["profiles"]["home"], json!({ "vpn": "vpn://AAAA" })); + assert_eq!(c["amneziaWg"]["profiles"]["exit"]["asOutbound"], "userspace"); + assert_eq!(c["amneziaWg"]["enable"], true); + assert!(add_awg_profile(&mut c, "home", "vpn://B", "vpn").is_err()); + assert!(add_awg_profile(&mut c, "x", "hello", "vpn").is_err()); + assert!(add_awg_profile(&mut c, "a/b", "vpn://B", "vpn").is_err()); + remove_awg_profile(&mut c, "home").unwrap(); + assert!(remove_awg_profile(&mut c, "home").is_err()); + } + #[test] fn whitelist_bypass_entries_are_added_once_and_removed() { let mut c = json!({}); diff --git a/windows/crates/ps-core/src/config/validate.rs b/windows/crates/ps-core/src/config/validate.rs index 11da469..5b271c7 100644 --- a/windows/crates/ps-core/src/config/validate.rs +++ b/windows/crates/ps-core/src/config/validate.rs @@ -122,7 +122,6 @@ fn not_ported(cfg: &Config, v: &mut Issues) { v.warn("killSwitch.enable", "the kill switch is not on Windows yet: nothing blocks traffic that bypasses the tunnel"); } for (on, path, what) in [ - (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.inbounds.enable, "inbounds.enable", "Serving inbounds"), @@ -839,12 +838,10 @@ mod tests { assert!(quiet.is_empty(), "{quiet:?}"); let mut cfg = Config::default(); cfg.kill_switch.enable = true; - cfg.amnezia_wg.enable = true; - cfg.amnezia_wg.profiles.insert("vpn".into(), Default::default()); cfg.zapret.enable = true; cfg.proxy.tun.enable = true; let paths: Vec = validate(&cfg).into_iter().filter(|i| i.severity == Severity::Warning && i.message.contains("Windows yet")).map(|i| i.path).collect(); - for want in ["killSwitch.enable", "amneziaWg.profiles", "proxy.tun.enable"] { + for want in ["killSwitch.enable", "proxy.tun.enable"] { assert!(paths.iter().any(|p| p == want), "{want} not in {paths:?}"); } } diff --git a/windows/crates/ps-ctl/src/main.rs b/windows/crates/ps-ctl/src/main.rs index 51a9c46..7fc1a59 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, }, + /// AmneziaWG profiles: the system-wide ones started and stopped. + Awg { + #[command(subcommand)] + verb: Option, + }, /// whitelist-bypass creators and joiners. Wl { #[command(subcommand)] @@ -72,6 +77,22 @@ enum TgVerb { Link, } +#[derive(Subcommand)] +enum AwgVerb { + /// Profiles and their state. + List, + /// Start a system-wide profile's tunnel. + On { profile: String }, + /// Stop it. + Off { profile: String }, + /// Its tunnel's log. + Log { + profile: String, + #[arg(short = 'n', long, default_value_t = 50)] + lines: usize, + }, +} + #[derive(Subcommand)] enum WlVerb { /// Creators and joiners, and their state. @@ -681,6 +702,51 @@ async fn zapret(ctl: &Ctl, verb: Option) -> Result<()> { Ok(()) } +async fn awg(ctl: &Ctl, verb: Option) -> Result<()> { + match verb.unwrap_or(AwgVerb::List) { + AwgVerb::List => { + let r = ctl.call(Request::AwgList).await?; + if ctl.json { + ctl.print(&r); + return Ok(()); + } + let profiles = r["profiles"].as_array().cloned().unwrap_or_default(); + if profiles.is_empty() { + println!("No AmneziaWG profiles configured."); + return Ok(()); + } + if r["enabled"] != true { + println!("AmneziaWG is off (amneziaWg.enable)."); + } + println!(" {:<24} {:<12} {:<12} INTERFACE", "PROFILE", "KIND", "STATUS"); + for p in profiles { + let kind = match p["kind"].as_str().unwrap_or("") { + "vpn" => "system VPN", + "userspace" => "outbound", + "singBox" => "outbound (WG)", + k => k, + }; + println!(" {:<24} {:<12} {:<12} {}", p["name"].as_str().unwrap_or(""), kind, p["state"].as_str().unwrap_or(""), p["interface"].as_str().unwrap_or("-")); + } + } + AwgVerb::On { profile } => { + let r = ctl.call(Request::AwgSet { name: profile.clone(), on: true }).await?; + println!("{profile}: {}", r["state"].as_str().unwrap_or("?")); + } + AwgVerb::Off { profile } => { + let r = ctl.call(Request::AwgSet { name: profile.clone(), on: false }).await?; + println!("{profile}: {}", r["state"].as_str().unwrap_or("?")); + } + AwgVerb::Log { profile, lines } => { + let r = ctl.call(Request::AwgLog { name: profile, lines }).await?; + for l in r["lines"].as_array().into_iter().flatten().filter_map(Value::as_str) { + println!("{l}"); + } + } + } + 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 { @@ -834,6 +900,7 @@ async fn real_main() -> Result<()> { Cmd::Zapret { verb } => zapret(&ctl, verb).await?, Cmd::Components { verb } => components(&ctl, verb).await?, Cmd::Wl { verb } => wl(&ctl, verb).await?, + Cmd::Awg { verb } => awg(&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-gui/src/assets.rs b/windows/crates/ps-gui/src/assets.rs index e0484b9..b5f55ee 100644 --- a/windows/crates/ps-gui/src/assets.rs +++ b/windows/crates/ps-gui/src/assets.rs @@ -5,7 +5,7 @@ use std::borrow::Cow; use gpui_kit::*; -gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp, Route]); +gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp, Route, Lock]); pub struct AppAssets; diff --git a/windows/crates/ps-gui/src/ui/amneziawg.rs b/windows/crates/ps-gui/src/ui/amneziawg.rs new file mode 100644 index 0000000..fd21462 --- /dev/null +++ b/windows/crates/ps-gui/src/ui/amneziawg.rs @@ -0,0 +1,206 @@ +//! AmneziaWG: its profiles, system-wide VPNs (started and stopped here, their tunnel's log) or +//! outbounds of the proxy; one added from an AmneziaVPN vpn:// link or a .conf, or removed. + +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; + +use gpui_kit::assets::IconName; +use gpui_kit::component::button::{Button, ButtonVariants as _}; +use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState}; +use gpui_kit::component::notification::Notification; +use gpui_kit::component::radio::RadioGroup; +use gpui_kit::component::switch::Switch; +use gpui_kit::component::tag::Tag; +use gpui_kit::component::*; +use gpui_kit::*; +use ps_client::edits; +use ps_ipc::Request; +use serde_json::Value; + +use super::widgets::{card, hint, page, state_tag}; +use crate::model::Model; + +const KINDS: [(&str, &str); 3] = [("vpn", "System-wide VPN"), ("userspace", "Outbound (AmneziaWG)"), ("singBox", "Outbound (plain WireGuard)")]; + +pub struct AmneziaWgPage { + model: Entity, + name: Entity, + text: Entity, + kind: usize, + list: Result, + loaded_at: Option, + /// A profile's tunnel log, while shown. + logs: BTreeMap, String>>, + _subscriptions: Vec, +} + +impl AmneziaWgPage { + pub fn new(model: Entity, window: &mut Window, cx: &mut Context) -> Self { + let name = cx.new(|cx| InputState::new(window, cx).placeholder("home")); + let text = cx.new(|cx| TextareaState::new(window, cx).rows(5).placeholder("vpn://… from AmneziaVPN, or a .conf: [Interface] …")); + let subscriptions = vec![cx.observe(&model, |this, _, cx| { + if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(3)) { + this.load(cx); + } + })]; + let mut this = Self { model, name, text, kind: 0, list: Ok(Value::Null), loaded_at: None, logs: BTreeMap::new(), _subscriptions: subscriptions }; + this.load(cx); + this + } + + fn load(&mut self, cx: &mut Context) { + self.loaded_at = Some(Instant::now()); + let job = self.model.read(cx).bridge().call(Request::AwgList); + cx.spawn(async move |this, cx| { + let r = job.await; + this.update(cx, |this, cx| { + this.list = r.map_err(|e| format!("{e:#}")); + cx.notify(); + }) + .ok(); + }) + .detach(); + } + + fn set(&mut self, name: String, on: bool, cx: &mut Context) { + let what = format!("{name}: {}", if on { "tunnel up" } else { "tunnel down" }); + let job = self.model.read(cx).bridge().call(Request::AwgSet { name, on }); + let model = self.model.clone(); + cx.spawn(async move |this, cx| { + let r = job.await; + model.update(cx, |m, cx| m.track(what, async move { r.map(drop) }, cx)); + this.update(cx, |this, cx| this.load(cx)).ok(); + }) + .detach(); + } + + fn toggle_log(&mut self, name: String, cx: &mut Context) { + if self.logs.remove(&name).is_some() { + cx.notify(); + return; + } + let job = self.model.read(cx).bridge().call(Request::AwgLog { name: name.clone(), lines: 30 }); + cx.spawn(async move |this, cx| { + let r = job.await.map(|v| v["lines"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()).map_err(|e| format!("{e:#}")); + this.update(cx, |this, cx| { + this.logs.insert(name, r); + cx.notify(); + }) + .ok(); + }) + .detach(); + } + + fn add(&mut self, window: &mut Window, cx: &mut Context) { + let name = self.name.read(cx).value().trim().to_owned(); + let text = self.text.read(cx).value().to_string(); + let kind = KINDS[self.kind].0; + // Checked here first, for a message at once. + if let Err(e) = edits::add_awg_profile(&mut serde_json::json!({}), &name, &text, kind) { + window.push_notification(Notification::error(format!("{e:#}")), cx); + return; + } + self.name.update(cx, |s, cx| s.set_value("", window, cx)); + self.text.update(cx, |s, cx| s.set_value("", window, cx)); + let what = format!("AmneziaWG profile '{name}' added"); + self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_awg_profile(c, &name, &text, kind), cx)); + } + + fn remove(&mut self, name: String, cx: &mut Context) { + self.model.update(cx, |m, cx| m.edit(format!("AmneziaWG profile '{name}' removed"), move |c| edits::remove_awg_profile(c, &name), cx)); + } +} + +impl Render for AmneziaWgPage { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let m = self.model.read(cx); + let body = page("AmneziaWG", cx); + if m.config().is_null() { + return body.child(hint("Waiting for the service…", cx)); + } + let on = m.config()["amneziaWg"]["enable"] == true; + let model = self.model.clone(); + let enable = Switch::new("awg-enable").checked(on).on_change(move |on, _, cx| { + let on = *on; + model.update(cx, |m, cx| { + m.edit( + if on { "AmneziaWG is on" } else { "AmneziaWG is off" }, + move |c| { + edits::set_path(c, &["amneziaWg", "enable"], on.into()); + Ok(()) + }, + cx, + ) + }) + }); + let about = card("AmneziaWG", Some(enable.into_any_element()), cx).child(hint( + "WireGuard with AmneziaVPN's obfuscation. A system-wide profile is a VPN of its own (a network adapter, its routes and DNS); with one peer that takes everything, it also blocks what would leave outside the tunnel. An outbound profile is one more exit for the proxy, with nothing else changed.", + cx, + )); + + let mut profiles = card("Profiles", Some(Button::new("awg-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))).into_any_element()), cx); + match &self.list { + Err(e) => profiles = profiles.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())), + Ok(l) => { + let list = l["profiles"].as_array().cloned().unwrap_or_default(); + if list.is_empty() { + profiles = profiles.child(hint("None yet: add one below.", cx)); + } + for (i, p) in list.iter().enumerate() { + let name = p["name"].as_str().unwrap_or("").to_owned(); + let vpn = p["kind"] == "vpn"; + let state = p["state"].as_str().unwrap_or("").to_owned(); + let kind = match p["kind"].as_str().unwrap_or("") { + "vpn" => Tag::info().child("system VPN"), + "userspace" => Tag::secondary().child("outbound"), + _ => Tag::secondary().child("outbound (WireGuard)"), + }; + let mut line = div() + .h_flex() + .gap_3() + .items_center() + .child(div().font_medium().child(name.clone())) + .child(kind) + .child(if state == "windows-only" { Tag::secondary().child("Windows only") } else { state_tag(&state) }) + .child(div().flex_1()); + if vpn { + let (n1, n2) = (name.clone(), name.clone()); + let running = matches!(state.as_str(), "active" | "activating"); + line = line + .child(Button::new(("awg-log", i)).small().ghost().label("Log").on_click(cx.listener(move |this, _, _, cx| this.toggle_log(n1.clone(), cx)))) + .child( + Switch::new(("awg-on", i)) + .checked(running) + .disabled(!on) + .on_change(cx.listener(move |this, v: &bool, _, cx| this.set(n2.clone(), *v, cx))), + ); + } + let n3 = name.clone(); + line = line.child(Button::new(("awg-remove", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove(n3.clone(), cx)))); + let mut row = div().v_flex().gap_2().py_2().border_t_1().border_color(cx.theme().border).child(line); + match self.logs.get(&name) { + Some(Ok(lines)) => { + let text = if lines.is_empty() { "(no log yet)".to_owned() } else { lines.join("\n") }; + row = row.child(div().text_xs().font_family("monospace").text_color(cx.theme().muted_foreground).child(text)); + } + Some(Err(e)) => row = row.child(hint(e.clone(), cx)), + None => {} + } + profiles = profiles.child(row); + } + } + } + + let kinds = RadioGroup::horizontal("awg-kind").children(KINDS.map(|(_, label)| label)).selected_index(Some(self.kind)).on_change(cx.listener(|this, ix: &usize, _, cx| { + this.kind = *ix; + cx.notify(); + })); + let add = card("Add a profile", Some(Button::new("awg-add").small().primary().icon(IconName::Plus).label("Add").on_click(cx.listener(|this, _, window, cx| this.add(window, cx))).into_any_element()), cx) + .child(div().v_flex().gap_1().child(div().text_sm().child("Name (also the adapter's)")).child(Input::new(&self.name))) + .child(kinds) + .child(Textarea::new(&self.text)) + .child(hint("The link or .conf stays in the service's configuration, which only you and administrators read. Starting at sign-in (autostart), the endpoint and the rest are in Settings, under amneziaWg.profiles.", cx)); + + body.child(about).child(profiles).child(add) + } +} diff --git a/windows/crates/ps-gui/src/ui/mod.rs b/windows/crates/ps-gui/src/ui/mod.rs index d61bdc6..5db7882 100644 --- a/windows/crates/ps-gui/src/ui/mod.rs +++ b/windows/crates/ps-gui/src/ui/mod.rs @@ -1,6 +1,7 @@ //! The window: a sidebar of pages, the page shown, and what came of each change as a //! notification. +mod amneziawg; mod autoproxy; mod components; mod dpi; @@ -28,14 +29,25 @@ pub enum Page { Whitelist, Outbounds, AutoProxy, + AmneziaWg, Logs, Settings, Components, } impl Page { - const ALL: [Page; 9] = - [Page::Overview, Page::Dpi, Page::Telegram, Page::Whitelist, Page::Outbounds, Page::AutoProxy, Page::Logs, Page::Settings, Page::Components]; + const ALL: [Page; 10] = [ + Page::Overview, + Page::Dpi, + Page::Telegram, + Page::Whitelist, + Page::Outbounds, + Page::AutoProxy, + Page::AmneziaWg, + Page::Logs, + Page::Settings, + Page::Components, + ]; fn title(self) -> &'static str { match self { @@ -45,6 +57,7 @@ impl Page { Page::Whitelist => "Whitelist bypass", Page::Outbounds => "Outbounds", Page::AutoProxy => "autoProxy", + Page::AmneziaWg => "AmneziaWG", Page::Logs => "Logs", Page::Settings => "Settings", Page::Components => "Components", @@ -59,6 +72,7 @@ impl Page { Page::Whitelist => IconName::Video, Page::Outbounds => IconName::Globe, Page::AutoProxy => IconName::Route, + Page::AmneziaWg => IconName::Lock, Page::Logs => IconName::SquareTerminal, Page::Settings => IconName::Settings, Page::Components => IconName::Package, @@ -75,6 +89,7 @@ pub struct AppView { /// Made when first shown. whitelist: Option>, autoproxy: Option>, + amneziawg: Option>, /// Made when first shown: following the logs starts then. logs: Option>, /// Made when first shown, as it loads the configuration into its editor then. @@ -98,7 +113,7 @@ impl AppView { let dpi = cx.new(|cx| dpi::DpiPage::new(model.clone(), window, cx)); let telegram = cx.new(|cx| telegram::TelegramPage::new(model.clone(), window, cx)); let outbounds = cx.new(|cx| outbounds::OutboundsPage::new(model.clone(), window, cx)); - Self { model, page: Page::Overview, dpi, telegram, outbounds, whitelist: None, autoproxy: None, logs: None, settings: None, components: None, _subscriptions: subscriptions } + Self { model, page: Page::Overview, dpi, telegram, outbounds, whitelist: None, autoproxy: None, amneziawg: None, logs: None, settings: None, components: None, _subscriptions: subscriptions } } fn sidebar(&self, cx: &mut Context) -> impl IntoElement { @@ -131,6 +146,10 @@ impl Render for AppView { self.whitelist.get_or_insert_with(|| cx.new(|cx| whitelist::WhitelistPage::new(model, window, cx))).clone().into_any_element() } Page::Outbounds => self.outbounds.clone().into_any_element(), + Page::AmneziaWg => { + let model = self.model.clone(); + self.amneziawg.get_or_insert_with(|| cx.new(|cx| amneziawg::AmneziaWgPage::new(model, window, cx))).clone().into_any_element() + } Page::AutoProxy => { let model = self.model.clone(); self.autoproxy.get_or_insert_with(|| cx.new(|cx| autoproxy::AutoProxyPage::new(model, window, cx))).clone().into_any_element() diff --git a/windows/crates/ps-ipc/src/lib.rs b/windows/crates/ps-ipc/src/lib.rs index 4a72684..4a2d1ed 100644 --- a/windows/crates/ps-ipc/src/lib.rs +++ b/windows/crates/ps-ipc/src/lib.rs @@ -96,6 +96,12 @@ pub enum Request { #[serde(default)] domain: Option, }, + /// AmneziaWG's profiles: system-wide ones with their tunnel's state, outbounds by kind. + AwgList, + /// Starts or stops a system-wide profile's tunnel. + AwgSet { name: String, on: bool }, + /// The last lines of a system-wide profile's tunnel log. Secrets scope, as logs are. + AwgLog { name: String, lines: usize }, } #[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 bad562b..5102a1f 100644 --- a/windows/crates/ps-service/src/api.rs +++ b/windows/crates/ps-service/src/api.rs @@ -137,6 +137,8 @@ fn scope_of(req: &Request) -> Option { Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services), Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass), Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy), + Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg), + Request::AwgLog { .. } => Some(Scope::Secrets), _ => None, } } @@ -628,6 +630,49 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response { Err(e) => Response::err(format!("{e:#}")), }, + Request::AwgList => { + let s = shared.lock().await; + let cfg = s.cfg(); + let vpns = crate::awgvpn::profiles(cfg); + let list: Vec = cfg + .amnezia_wg + .profiles + .iter() + .map(|(name, p)| match vpns.iter().find(|v| &v.name == name) { + Some(v) => json!({ "name": name, "kind": "vpn", "interface": v.iface, "autostart": v.autostart, "state": crate::awgvpn::state(&v.iface) }), + None => json!({ + "name": name, + "kind": match p.as_outbound { Some(ps_core::config::AwgOutboundKind::SingBox) => "singBox", Some(_) => "userspace", None => "vpn" }, + "state": if cfg.amnezia_wg.enable { "outbound" } else { "off" }, + }), + }) + .collect(); + Response::ok(json!({ "enabled": cfg.amnezia_wg.enable, "profiles": list })) + } + + Request::AwgSet { name, on } => { + let s = shared.lock().await; + let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else { + return Response::err(format!("no system-wide AmneziaWG profile '{name}' (is amneziaWg.enable on, and the profile without asOutbound?)")); + }; + // The SCM's calls wait for the tunnel: not in the async runtime's threads. + let iface = vpn.iface.clone(); + let r = tokio::task::spawn_blocking(move || if on { crate::awgvpn::start(&iface) } else { crate::awgvpn::stop(&iface) }).await; + match r { + Ok(Ok(())) => Response::ok(json!({ "name": name, "state": crate::awgvpn::state(&vpn.iface) })), + Ok(Err(e)) => Response::err(format!("{e:#}")), + Err(e) => Response::err(e.to_string()), + } + } + + Request::AwgLog { name, lines } => { + let s = shared.lock().await; + let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else { + return Response::err(format!("no system-wide AmneziaWG profile '{name}'")); + }; + Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) })) + } + 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/awgvpn.rs b/windows/crates/ps-service/src/awgvpn.rs new file mode 100644 index 0000000..b815a4a --- /dev/null +++ b/windows/crates/ps-service/src/awgvpn.rs @@ -0,0 +1,322 @@ +//! AmneziaWG as a system-wide VPN: each profile with no `asOutbound` is a tunnel service of +//! its own, `AmneziaWGTunnel$`, as amneziawg-windows's client installs one: +//! amneziawg-go on Wintun, routes and DNS from the configuration, and, for a single peer that +//! takes everything (0.0.0.0/0, ::/0), its firewall blocking what would leave outside the +//! tunnel. It runs `awg-tunnel.exe` (tools/build-amneziawg.sh) with the profile's `.conf`, +//! written below the protected state root, and logs beside it. +//! +//! The service writes the configuration and registers the tunnel; `proxy-ctl awg on|off` and +//! the app start and stop it; `autostart` starts it with the service. Windows only: on Linux +//! (development) the profiles are listed and say so. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use ps_core::config::Config; + +use crate::paths::{Paths, write_atomic}; + +/// The tunnel services' names: amneziawg-windows's own. +#[cfg_attr(not(windows), allow(dead_code))] +pub const SERVICE_PREFIX: &str = "AmneziaWGTunnel$"; + +/// Where the service's notes about the tunnels go: `proxy-ctl logs proxy-suite-awg-vpn`. +pub const UNIT: &str = "proxy-suite-awg-vpn"; + +/// A system-wide profile. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Vpn { + pub name: String, + /// The adapter's and the service's name. + pub iface: String, + pub autostart: bool, +} + +/// The profiles that are system-wide VPNs, while AmneziaWG is on. +pub fn profiles(cfg: &Config) -> Vec { + if !cfg.enable || !cfg.amnezia_wg.enable { + return Vec::new(); + } + cfg.amnezia_wg + .profiles + .iter() + .filter(|(_, p)| p.as_outbound.is_none()) + .map(|(name, p)| Vpn { name: name.clone(), iface: p.interface_name.clone().unwrap_or_else(|| name.clone()), autostart: p.autostart }) + .collect() +} + +#[cfg_attr(not(windows), allow(dead_code))] +pub fn service_name(iface: &str) -> String { + format!("{SERVICE_PREFIX}{iface}") +} + +/// The tunnels' configurations: each `.conf` there is a tunnel this suite +/// registered, which is how it finds its own to remove. +fn dir(paths: &Paths) -> PathBuf { + paths.root.join("awg-vpn") +} + +/// The tunnels registered, by interface name. +fn registered(paths: &Paths) -> Vec { + std::fs::read_dir(dir(paths)) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| e.file_name().to_str()?.strip_suffix(".conf").map(str::to_owned)) + .collect() +} + +/// A tunnel unregistered: its service, configuration and log gone. +fn forget(paths: &Paths, iface: &str) -> Result<()> { + #[cfg(windows)] + scm::remove(iface, &paths.bin())?; + let _ = std::fs::remove_file(conf_path(paths, iface)); + let _ = std::fs::remove_file(log_path(paths, iface)); + Ok(()) +} + +pub fn conf_path(paths: &Paths, iface: &str) -> PathBuf { + dir(paths).join(format!("{iface}.conf")) +} + +/// The tunnel's log: awg-tunnel.exe writes it anew at each start. +pub fn log_path(paths: &Paths, iface: &str) -> PathBuf { + dir(paths).join(format!("{iface}.conf.log")) +} + +/// The profile's `.conf`, as the tunnel reads it: it holds the private key, so only below +/// the protected state root. +pub fn write_conf(cfg: &Config, paths: &Paths, vpn: &Vpn) -> Result { + let p = &cfg.amnezia_wg.profiles[&vpn.name]; + let read = |f: &str| std::fs::read_to_string(f).map_err(|e| format!("{f}: {e}")); + let text = ps_core::awg::prepare(p, &read).map_err(|e| anyhow::anyhow!("AmneziaWG profile '{}': {e}", vpn.name))?; + let file = conf_path(paths, &vpn.iface); + std::fs::create_dir_all(dir(paths))?; + if std::fs::read_to_string(&file).ok().as_deref() != Some(text.as_str()) { + write_atomic(&file, text.as_bytes()).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(file) +} + +/// The last lines of a tunnel's log. +pub fn log_tail(paths: &Paths, iface: &str, lines: usize) -> Vec { + let text = std::fs::read_to_string(log_path(paths, iface)).unwrap_or_default(); + let all: Vec<&str> = text.lines().collect(); + all[all.len().saturating_sub(lines)..].iter().map(|l| (*l).to_owned()).collect() +} + +#[cfg(windows)] +mod scm { + use std::ffi::OsString; + use std::path::Path; + use std::time::Duration; + + use anyhow::{Context, Result}; + use windows_service::service::{ + ServiceAccess, ServiceDependency, ServiceErrorControl, ServiceInfo, ServiceSidType, ServiceStartType, ServiceState, ServiceType, + }; + use windows_service::service_manager::{ServiceManager, ServiceManagerAccess}; + + fn manager() -> Result { + ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE | ServiceManagerAccess::ENUMERATE_SERVICE) + .context("opening the Service Control Manager") + } + + const ACCESS: ServiceAccess = ServiceAccess::QUERY_STATUS + .union(ServiceAccess::QUERY_CONFIG) + .union(ServiceAccess::START) + .union(ServiceAccess::STOP) + .union(ServiceAccess::CHANGE_CONFIG) + .union(ServiceAccess::DELETE); + + /// The tunnel's service, created or brought in line with `program` and `conf`. + pub fn register(iface: &str, program: &Path, conf: &Path) -> Result<()> { + let m = manager()?; + let info = ServiceInfo { + name: OsString::from(super::service_name(iface)), + display_name: OsString::from(format!("AmneziaWG tunnel: {iface} (Proxy Suite)")), + service_type: ServiceType::OWN_PROCESS, + start_type: ServiceStartType::OnDemand, + error_control: ServiceErrorControl::Normal, + executable_path: program.to_path_buf(), + launch_arguments: vec![conf.as_os_str().to_owned(), OsString::from(iface)], + // As amneziawg-windows's client: the network stack first. + dependencies: vec![ServiceDependency::Service(OsString::from("Nsi")), ServiceDependency::Service(OsString::from("TcpIp"))], + account_name: None, + account_password: None, + }; + let service = match m.open_service(super::service_name(iface), ACCESS) { + Ok(s) => { + let current = s.query_config()?; + let wanted_args = format!("\"{}\" \"{}\" \"{iface}\"", program.display(), conf.display()); + if current.executable_path.to_string_lossy() != wanted_args { + s.change_config(&info)?; + } + s + } + Err(_) => m.create_service(&info, ACCESS).context("creating the tunnel service")?, + }; + // Its firewall lets the tunnel's own traffic out by the service's SID, which a service + // has in its token only with this. + service.set_config_service_sid_info(ServiceSidType::Unrestricted)?; + Ok(()) + } + + pub fn start(iface: &str) -> Result<()> { + let s = manager()?.open_service(super::service_name(iface), ACCESS).context("the tunnel is not registered")?; + if s.query_status()?.current_state == ServiceState::Stopped { + s.start::<&str>(&[]).context("starting the tunnel")?; + } + Ok(()) + } + + pub fn stop(iface: &str) -> Result<()> { + let Ok(s) = manager()?.open_service(super::service_name(iface), ACCESS) else { return Ok(()) }; + if s.query_status()?.current_state != ServiceState::Stopped { + let _ = s.stop(); + for _ in 0..40 { + if s.query_status()?.current_state == ServiceState::Stopped { + break; + } + std::thread::sleep(Duration::from_millis(250)); + } + } + Ok(()) + } + + pub fn state(iface: &str) -> String { + let Ok(m) = manager() else { return "unknown".into() }; + let Ok(s) = m.open_service(super::service_name(iface), ServiceAccess::QUERY_STATUS) else { return "inactive".into() }; + match s.query_status().map(|st| st.current_state) { + Ok(ServiceState::Running) => "active", + Ok(ServiceState::StartPending) => "activating", + Ok(ServiceState::StopPending) => "deactivating", + Ok(_) => "inactive", + Err(_) => "unknown", + } + .into() + } + + /// Stopped and deleted, if it runs this suite's program (under `bin`): a tunnel of + /// amneziawg-windows's own client by the same name is left alone. + pub fn remove(iface: &str, bin: &Path) -> Result<()> { + let Ok(s) = manager()?.open_service(super::service_name(iface), ACCESS) else { return Ok(()) }; + let bin = bin.to_string_lossy().to_lowercase(); + if !s.query_config().is_ok_and(|c| c.executable_path.to_string_lossy().to_lowercase().contains(&bin)) { + return Ok(()); + } + stop(iface)?; + s.delete()?; + Ok(()) + } +} + +/// Registers every system-wide profile's tunnel (its `.conf` written), removes the tunnels +/// of profiles gone, and starts the `autostart` ones when `boot`. Errors per profile are +/// returned as lines, the rest done. +pub fn apply(cfg: &Config, paths: &Paths, program: Option<&Path>, boot: bool) -> Vec { + let wanted = profiles(cfg); + let mut notes = Vec::new(); + let keep: Vec<&str> = wanted.iter().map(|v| v.iface.as_str()).collect(); + for iface in registered(paths) { + if !keep.contains(&iface.as_str()) { + match forget(paths, &iface) { + Ok(()) => notes.push(format!("AmneziaWG tunnel {iface} removed: its profile is gone, or AmneziaWG is off")), + Err(e) => notes.push(format!("AmneziaWG tunnel {iface}: {e:#}")), + } + } + } + if wanted.is_empty() { + return notes; + } + let Some(program) = program else { + notes.push("AmneziaWG's tunnel (component amneziawg) is not installed: the system-wide profiles cannot start".into()); + return notes; + }; + for vpn in &wanted { + let r = write_conf(cfg, paths, vpn).and_then(|conf| register(&vpn.iface, program, &conf)); + match r { + Ok(()) if boot && vpn.autostart => { + if let Err(e) = start(&vpn.iface) { + notes.push(format!("AmneziaWG profile '{}': {e:#}", vpn.name)); + } + } + Ok(()) => {} + Err(e) => notes.push(format!("AmneziaWG profile '{}': {e:#}", vpn.name)), + } + } + notes +} + +#[cfg(windows)] +fn register(iface: &str, program: &Path, conf: &Path) -> Result<()> { + scm::register(iface, program, conf) +} + +#[cfg(not(windows))] +fn register(_iface: &str, _program: &Path, _conf: &Path) -> Result<()> { + Ok(()) +} + +#[cfg(windows)] +pub fn start(iface: &str) -> Result<()> { + scm::start(iface) +} + +#[cfg(not(windows))] +pub fn start(_iface: &str) -> Result<()> { + anyhow::bail!("AmneziaWG as a system-wide VPN runs on Windows only") +} + +#[cfg(windows)] +pub fn stop(iface: &str) -> Result<()> { + scm::stop(iface) +} + +#[cfg(not(windows))] +pub fn stop(_iface: &str) -> Result<()> { + Ok(()) +} + +#[cfg(windows)] +pub fn state(iface: &str) -> String { + scm::state(iface) +} + +#[cfg(not(windows))] +pub fn state(_iface: &str) -> String { + "windows-only".into() +} + +/// Every tunnel this suite registered, stopped and deleted: on uninstall. +#[cfg_attr(not(windows), allow(dead_code))] +pub fn remove_all(paths: &Paths) { + for iface in registered(paths) { + let _ = forget(paths, &iface); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ps_core::config::{AwgOutboundKind, AwgProfile}; + + #[test] + fn only_profiles_without_an_outbound_are_vpns() { + let mut cfg = Config::default(); + cfg.amnezia_wg.enable = true; + cfg.amnezia_wg.profiles.insert("home".into(), AwgProfile { autostart: true, ..Default::default() }); + cfg.amnezia_wg.profiles.insert("office".into(), AwgProfile { interface_name: Some("awg-office".into()), ..Default::default() }); + cfg.amnezia_wg.profiles.insert("exit".into(), AwgProfile { as_outbound: Some(AwgOutboundKind::Userspace), ..Default::default() }); + let v = profiles(&cfg); + assert_eq!(v.iter().map(|v| (v.name.as_str(), v.iface.as_str(), v.autostart)).collect::>(), [("home", "home", true), ("office", "awg-office", false)]); + assert_eq!(service_name("home"), "AmneziaWGTunnel$home"); + cfg.amnezia_wg.enable = false; + assert!(profiles(&cfg).is_empty()); + } +} diff --git a/windows/crates/ps-service/src/main.rs b/windows/crates/ps-service/src/main.rs index e6b758b..886fb76 100644 --- a/windows/crates/ps-service/src/main.rs +++ b/windows/crates/ps-service/src/main.rs @@ -6,6 +6,7 @@ mod api; mod autoproxy; mod awg; +mod awgvpn; mod clash; mod components; mod fetch; diff --git a/windows/crates/ps-service/src/service.rs b/windows/crates/ps-service/src/service.rs index 940cf66..3e6b7c2 100644 --- a/windows/crates/ps-service/src/service.rs +++ b/windows/crates/ps-service/src/service.rs @@ -41,6 +41,9 @@ pub struct Service { wl_waiting: BTreeSet, /// autoProxy's requests and the hosts its prober learns from (crate::autoproxy). pub ap: Arc, + /// Whether the system-wide AmneziaWG tunnels were registered since the service started: + /// the first time, the `autostart` ones start too. + awg_vpn_started: bool, } fn digest(data: &[u8]) -> String { @@ -65,6 +68,7 @@ impl Service { tcp_timestamps_on: false, wl_waiting: BTreeSet::new(), ap: Arc::default(), + awg_vpn_started: false, store, }) } @@ -181,6 +185,7 @@ impl Service { if let Err(e) = &awg { self.sup.note(SOCKS_UNIT, format!("proxy-suite: AmneziaWG: {e:#}")); } + self.apply_awg_vpn(); let wl = self.apply_wl().await; if let Err(e) = &wl { self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}")); @@ -189,6 +194,24 @@ impl Service { zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy) } + /// AmneziaWG's system-wide tunnels: registered (their `.conf` written) or removed with + /// their profiles, the `autostart` ones started with the service. + fn apply_awg_vpn(&mut self) { + let cfg = self.cfg().clone(); + let boot = !self.awg_vpn_started; + self.awg_vpn_started = true; + if !cfg!(windows) { + if !crate::awgvpn::profiles(&cfg).is_empty() { + self.sup.note(crate::awgvpn::UNIT, "proxy-suite: AmneziaWG as a system-wide VPN runs on Windows only; not registered"); + } + return; + } + let program = self.comps.program("amneziawg", "awg-tunnel").ok(); + for note in crate::awgvpn::apply(&cfg, self.paths(), program.as_deref(), boot) { + self.sup.note(crate::awgvpn::UNIT, format!("proxy-suite: {note}")); + } + } + /// 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<()> { diff --git a/windows/crates/ps-service/src/winsvc.rs b/windows/crates/ps-service/src/winsvc.rs index a7ff971..86960a9 100644 --- a/windows/crates/ps-service/src/winsvc.rs +++ b/windows/crates/ps-service/src/winsvc.rs @@ -167,6 +167,7 @@ pub fn uninstall() -> Result<()> { println!("{DISPLAY} was not installed."); } remove_windivert(&manager); + crate::awgvpn::remove_all(&crate::paths::Paths::platform_default()); let dir = install_dir(); desktop::remove(); apps::remove(); diff --git a/windows/docs/screenshots/amneziawg.log b/windows/docs/screenshots/amneziawg.log new file mode 100644 index 0000000..e69de29 diff --git a/windows/docs/screenshots/amneziawg.png b/windows/docs/screenshots/amneziawg.png new file mode 100644 index 0000000..fff8793 Binary files /dev/null and b/windows/docs/screenshots/amneziawg.png differ diff --git a/windows/docs/screenshots/autoproxy.log b/windows/docs/screenshots/autoproxy.log new file mode 100644 index 0000000..e69de29 diff --git a/windows/docs/screenshots/autoproxy.png b/windows/docs/screenshots/autoproxy.png new file mode 100644 index 0000000..1cb18a0 Binary files /dev/null and b/windows/docs/screenshots/autoproxy.png differ diff --git a/windows/docs/screenshots/components.png b/windows/docs/screenshots/components.png index 88c6244..b0997a2 100644 Binary files a/windows/docs/screenshots/components.png and b/windows/docs/screenshots/components.png differ diff --git a/windows/docs/screenshots/dpi-bypass.png b/windows/docs/screenshots/dpi-bypass.png index c365719..0e0bf60 100644 Binary files a/windows/docs/screenshots/dpi-bypass.png and b/windows/docs/screenshots/dpi-bypass.png differ diff --git a/windows/docs/screenshots/logs.png b/windows/docs/screenshots/logs.png index de3ca37..8124fe0 100644 Binary files a/windows/docs/screenshots/logs.png and b/windows/docs/screenshots/logs.png differ diff --git a/windows/docs/screenshots/outbounds.png b/windows/docs/screenshots/outbounds.png index 33188ad..08c7302 100644 Binary files a/windows/docs/screenshots/outbounds.png and b/windows/docs/screenshots/outbounds.png differ diff --git a/windows/docs/screenshots/overview.png b/windows/docs/screenshots/overview.png index 1ecae44..c23a097 100644 Binary files a/windows/docs/screenshots/overview.png and b/windows/docs/screenshots/overview.png differ diff --git a/windows/docs/screenshots/settings.png b/windows/docs/screenshots/settings.png index 3a350f0..830e974 100644 Binary files a/windows/docs/screenshots/settings.png and b/windows/docs/screenshots/settings.png differ diff --git a/windows/docs/screenshots/telegram.png b/windows/docs/screenshots/telegram.png index 49e10a9..2174c16 100644 Binary files a/windows/docs/screenshots/telegram.png and b/windows/docs/screenshots/telegram.png differ diff --git a/windows/docs/screenshots/whitelist-bypass.png b/windows/docs/screenshots/whitelist-bypass.png index e83a918..0bf96ad 100644 Binary files a/windows/docs/screenshots/whitelist-bypass.png and b/windows/docs/screenshots/whitelist-bypass.png differ diff --git a/windows/tools/build-amneziawg.sh b/windows/tools/build-amneziawg.sh new file mode 100755 index 0000000..d44fc50 --- /dev/null +++ b/windows/tools/build-amneziawg.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# AmneziaWG as a system-wide VPN: amneziawg-windows's tunnel (amneziawg-go on Wintun, its +# firewall that blocks what leaves outside a full tunnel, its DNS and routes), built from its +# pinned commit as awg-tunnel.exe rather than its tunnel.dll: the same Run() a tunnel service +# makes, with a main that takes the config's path and the tunnel's name, and its log in a +# file beside the config (not its ring log). Wintun's signed driver DLL from wintun.net, +# pinned as amneziawg-windows's own build pins it. +# +# tools/build-amneziawg.sh OUT_DIR (needs git, go, curl, unzip) +set -euo pipefail +. "$(dirname "$0")/lib.sh" +OUT=$(realpath -m "${1:?output directory}") +COMMIT=e90531d15802cb976773f3b63443bc281f738ca3 +VERSION=0-unstable-2026-08-14+e90531d +WINTUN_URL=https://www.wintun.net/builds/wintun-0.14.1.zip +WINTUN_SHA256=07c256185d6ee3652e09fa55c0b673e2624b565e02c4b9091c79ca7d2f24ef51 +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +clone_commit https://github.com/amnezia-vpn/amneziawg-windows "$COMMIT" "$WORK/src" +cd "$WORK/src" +# Its exports (tunnel.dll's, through cgo) out; a main of ours in. +rm main.go +grep -q 'err = ringlogger.InitGlobalLogger("TUN")' service.go || { echo "service.go changed: no ring logger to replace"; exit 1; } +sed -i 's|err = ringlogger.InitGlobalLogger("TUN")|err = nil|' service.go +sed -i '/"github.com\/amnezia-vpn\/amneziawg-windows\/v3\/ringlogger"/d' service.go +cat > proxysuite_main.go <<'GO' +/* SPDX-License-Identifier: MIT + * + * Proxy Suite's AmneziaWG tunnel service: run by the Service Control Manager as + * `awg-tunnel `, as amneziawg-windows's tunnel.dll is from its + * client's service. Its log goes to .log, written anew at each start. + */ + +package main + +import ( + "fmt" + "log" + "os" +) + +func main() { + if len(os.Args) != 3 { + fmt.Fprintln(os.Stderr, "usage: awg-tunnel (as a Windows service)") + os.Exit(2) + } + confPath, name := os.Args[1], os.Args[2] + if f, err := os.OpenFile(confPath+".log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600); err == nil { + log.SetOutput(f) + } + text, err := os.ReadFile(confPath) + if err != nil { + log.Printf("reading %s: %v", confPath, err) + os.Exit(1) + } + if err := Run(string(text), name); err != nil { + log.Printf("the tunnel service: %v", err) + os.Exit(1) + } +} +GO +export GOTOOLCHAIN=local GOFLAGS=-mod=mod CGO_ENABLED=0 GOOS=windows GOARCH=amd64 +go build -trimpath -ldflags "-s -w" -o "$WORK/awg-tunnel.exe" . + +rm -rf "$OUT" && mkdir -p "$OUT" +cp "$WORK/awg-tunnel.exe" "$OUT/" +# Its license is the MIT text in its README. +sed -n '/^```text/,/^```/p' README.md | sed '1d;$d' >"$OUT/LICENSE" +grep -q 'Permission is hereby granted' "$OUT/LICENSE" || { echo "README.md: no license text"; exit 1; } +fetch_pinned "$WINTUN_URL" "$WINTUN_SHA256" "$WORK/wintun.zip" +unzip -q -o "$WORK/wintun.zip" -d "$WORK/wintun" +cp "$WORK/wintun/wintun/bin/amd64/wintun.dll" "$OUT/" +cp "$WORK/wintun/wintun/LICENSE.txt" "$OUT/wintun-LICENSE.txt" +echo "$VERSION" >"$OUT/.version" +echo "amneziawg $VERSION (windows) in $OUT" diff --git a/windows/tools/lib.sh b/windows/tools/lib.sh index 62fb5ea..d0787c4 100644 --- a/windows/tools/lib.sh +++ b/windows/tools/lib.sh @@ -28,3 +28,63 @@ clone_tag() { done return 1 } + +# clone_commit URL COMMIT DIR: COMMIT alone, for a project without release tags; cached and +# tried again as clone_tag is. +clone_commit() { + local url=$1 commit=$2 dir=$3 try cached="" + if [ -n "${SRC_CACHE:-}" ]; then + cached="$SRC_CACHE/$(basename "$url")@$commit" + if [ -d "$cached/.git" ]; then + rm -rf "$dir" && cp -a "$cached" "$dir" && git -C "$dir" reset -q --hard && git -C "$dir" clean -qfdx && return 0 + fi + fi + for try in 1 2 3; do + rm -rf "$dir" && mkdir -p "$dir" + if git -C "$dir" init -q && git -C "$dir" remote add origin "$url" && + git -C "$dir" -c http.lowSpeedLimit=1000 -c http.lowSpeedTime=60 fetch -q --depth 1 origin "$commit" && + git -C "$dir" -c advice.detachedHead=false checkout -q FETCH_HEAD; then + if [ -n "$cached" ]; then + mkdir -p "$SRC_CACHE" && rm -rf "$cached.tmp" && cp -a "$dir" "$cached.tmp" && mv "$cached.tmp" "$cached" + fi + return 0 + fi + echo "fetching $url ($commit) failed, try $try of 3" >&2 + sleep 5 + done + return 1 +} + +# fetch_pinned URL SHA256 FILE: a download, checked by its hash; kept in SRC_CACHE. +fetch_pinned() { + local url=$1 sha=$2 out=$3 cached="" + if [ -n "${SRC_CACHE:-}" ]; then + cached="$SRC_CACHE/$sha" + if [ -f "$cached" ] && echo "$sha $cached" | sha256sum -c --quiet 2>/dev/null; then + cp "$cached" "$out" && return 0 + fi + fi + # Whole, unless it stalls: some networks cut TLS to some hosts after about 16 KB (as + # zapret2's cutoff option knows). Then in ranges below that, each on a connection of its own. + if ! curl -fsSL --connect-timeout 30 --speed-limit 1 --speed-time 15 --max-time 900 --retry 2 -o "$out" "$url"; then + echo "$url stalled; fetching it in pieces" >&2 + local size from=0 step=12000 tries=0 + size=$(curl -fsSIL --connect-timeout 30 --max-time 60 "$url" | tr -d '\r' | awk 'tolower($1) == "content-length:" { n = $2 } END { print n }') + [[ "$size" =~ ^[0-9]+$ ]] && [ "$size" -gt 0 ] || { echo "$url: no size to fetch it in pieces by" >&2; return 1; } + : >"$out" + while [ "$from" -lt "$size" ]; do + if curl -fsSL --connect-timeout 30 --max-time 60 -r "$from-$((from + step - 1))" "$url" >>"$out.piece" 2>/dev/null && + [ "$(stat -c %s "$out.piece")" -gt 0 ]; then + cat "$out.piece" >>"$out" + from=$(stat -c %s "$out") + tries=0 + else + tries=$((tries + 1)) + [ "$tries" -lt 5 ] || { rm -f "$out.piece"; echo "$url: a piece failed five times" >&2; return 1; } + fi + rm -f "$out.piece" + done + fi + echo "$sha $out" | sha256sum -c --quiet || { echo "$url: not the pinned file" >&2; return 1; } + if [ -n "$cached" ]; then mkdir -p "$SRC_CACHE" && cp "$out" "$cached"; fi +} diff --git a/windows/tools/package.sh b/windows/tools/package.sh index 3d66661..c47aeb7 100755 --- a/windows/tools/package.sh +++ b/windows/tools/package.sh @@ -21,6 +21,7 @@ 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 +tools/build-amneziawg.sh "$DIST/components/amneziawg" 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 @@ -57,7 +58,8 @@ echo "== THIRD-PARTY.md" echo "- **cygwin1.dll** (zapret, zapret2): LGPL-3.0, https://cygwin.com" 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 "- **amneziawg-go** (inside wireproxy-awg, with the suite's patch, and inside amneziawg's awg-tunnel.exe): MIT, https://github.com/amnezia-vpn/amneziawg-go" + echo "- **Wintun** (amneziawg's wintun.dll, as WireGuard LLC builds and signs it): its prebuilt-binaries license, components/amneziawg/wintun-LICENSE.txt" 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" diff --git a/windows/tools/screenshots.sh b/windows/tools/screenshots.sh index d414ac4..093b280 100755 --- a/windows/tools/screenshots.sh +++ b/windows/tools/screenshots.sh @@ -39,6 +39,9 @@ cat >"$STATE/config.json" </dev/null 2>&1 && break; sleep 1; done wine "$PF/proxy-ctl.exe" components | tr -d '\r' | sed 's/^/ /' || fail "no answer over the pipe" +echo "== an AmneziaWG system-wide profile: its tunnel service registered, then removed" +CONF='[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 10.8.0.2/32\nDNS = 1.1.1.1\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.7:51820\n' +printf '{ "amneziaWg": { "enable": true, "profiles": { "home": { "config": "%s" } } } }' "$CONF" >"$WORK/awg.json" +wine "$PF/proxy-ctl.exe" config set "Z:$WORK/awg.json" | tr -d '\r' | sed 's/^/ /' +sleep 3 +qc=$(wine sc qc 'AmneziaWGTunnel$home' 2>/dev/null | tr -d '\r') +grep -q 'awg-tunnel.exe' <<<"$qc" || fail "no tunnel service registered: $(wine "$PF/proxy-ctl.exe" logs proxy-suite-awg-vpn -n 20 | tr -d '\r')" +grep -i 'BINARY_PATH_NAME' <<<"$qc" | sed 's/^ */ /' +wine "$PF/proxy-ctl.exe" awg | tr -d '\r' | sed 's/^/ /' +# Wine has no Wintun driver: the tunnel itself cannot come up here, only be asked to. +wine "$PF/proxy-ctl.exe" awg on home 2>&1 | tr -d '\r' | sed 's/^/ on: /' || true +sleep 3 +wine "$PF/proxy-ctl.exe" awg log home -n 5 2>&1 | tr -d '\r' | sed 's/^/ log: /' || true +printf '{}' >"$WORK/none.json" +wine "$PF/proxy-ctl.exe" config set "Z:$WORK/none.json" >/dev/null +sleep 3 +wine sc query 'AmneziaWGTunnel$home' >/dev/null 2>&1 && fail "the tunnel service outlived its profile" +echo " registered, and removed with its profile" + echo "== setup /S again, over the running install" wine "$SETUP" /S && rc=0 || rc=$? [ "$rc" = 0 ] || fail "the upgrade exited with $rc"