From aa44527082aea253e9bf0b6e3af3bac3bc4f23a7 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 28 Oct 2026 00:21:37 +0300 Subject: [PATCH] windows: the kill switch holds to what is wanted on, and says what is in place From the security review of 32ff264: - Turning a system-wide AmneziaWG profile off lifted the whole kill switch, the TUN's protection too, through a request of the AmneziaWG scope. Now the profile only leaves the plan; lifting it all stays killswitch off (services scope). - Which profiles count came from their tunnels' state this moment (one that crashed fell out: fail open), and one whose addresses did not read made the plan none. Now from intent (started at boot, or turned on), and one unread still holds, letting nothing through it. - holding said what was meant, not what was in place; failed now says filters that did not go in. Co-Authored-By: Claude Opus 5.5 --- windows/crates/ps-ctl/src/main.rs | 2 ++ windows/crates/ps-gui/src/ui/overview.rs | 5 ++- windows/crates/ps-service/src/api.rs | 11 ++++-- windows/crates/ps-service/src/killswitch.rs | 40 ++++++++++++++++----- windows/crates/ps-service/src/service.rs | 34 ++++++++++++------ 5 files changed, 70 insertions(+), 22 deletions(-) diff --git a/windows/crates/ps-ctl/src/main.rs b/windows/crates/ps-ctl/src/main.rs index 129ceb3..54cbb13 100644 --- a/windows/crates/ps-ctl/src/main.rs +++ b/windows/crates/ps-ctl/src/main.rs @@ -1030,6 +1030,8 @@ async fn real_main() -> Result<()> { ctl.print(&r); } else if r["enabled"] != true { println!("The kill switch is off (killSwitch.enable)."); + } else if r["failed"] == true { + println!("The kill switch should hold, but its filters are not in place: see the service's log (proxy-ctl logs)."); } else if r["holding"] == true { println!("The kill switch holds: what would leave past the tunnel is blocked."); } else if r["lifted"] == true { diff --git a/windows/crates/ps-gui/src/ui/overview.rs b/windows/crates/ps-gui/src/ui/overview.rs index d69b83d..5536801 100644 --- a/windows/crates/ps-gui/src/ui/overview.rs +++ b/windows/crates/ps-gui/src/ui/overview.rs @@ -70,7 +70,9 @@ pub fn render(model: &Entity, _: &mut Window, cx: &mut Context) .child(fact(tr("Outbound"), p["pinned"].as_str().map(|t| trf("{} (pinned)", &[&t])).unwrap_or_else(|| trf("{} selection", &[&p["selection"].as_str().unwrap_or("?")])), cx)) .when(s["killSwitch"]["enabled"] == true, |d| { let k = &s["killSwitch"]; - let (state, action, on) = if k["holding"] == true { + let (state, action, on) = if k["failed"] == true { + (tr("not in place: its filters failed (the Logs say why)"), tr("Lift"), false) + } else if k["holding"] == true { (tr("holding: what would leave past the tunnel is blocked"), tr("Lift"), false) } else if k["lifted"] == true { (tr("lifted until a tunnel is turned on"), tr("Hold again"), true) @@ -224,6 +226,7 @@ pub const RU: &[(&str, &str)] = &[ ("lifted until a tunnel is turned on", "снят до включения туннеля"), ("nothing to hold: no global tunnel is on", "не нужен: ни один общий туннель не включён"), ("Lift", "Снять"), + ("not in place: its filters failed (the Logs say why)", "не действует: фильтры не установлены (причина — в «Журналах»)"), ("Hold again", "Включить снова"), ("The kill switch holds again", "Kill switch снова действует"), ("The kill switch is lifted", "Kill switch снят"), diff --git a/windows/crates/ps-service/src/api.rs b/windows/crates/ps-service/src/api.rs index fe8a144..f86ee4f 100644 --- a/windows/crates/ps-service/src/api.rs +++ b/windows/crates/ps-service/src/api.rs @@ -666,9 +666,16 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response { // 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; - // Turned off by hand, the kill switch lets go; turned on, it holds again. + // The kill switch holds to the profiles wanted on: turned off, this one leaves its + // plan (the TUN's, and other profiles', stay); turned on, it joins, and a kill switch + // lifted holds again. if matches!(r, Ok(Ok(()))) { - s.killswitch_lifted = !on; + if on { + s.awg_wanted.insert(vpn.iface.clone()); + s.killswitch_lifted = false; + } else { + s.awg_wanted.remove(&vpn.iface); + } if let Err(e) = s.apply_killswitch() { s.sup.note(crate::service::SOCKS_UNIT, format!("proxy-suite: the kill switch: {e:#}")); } diff --git a/windows/crates/ps-service/src/killswitch.rs b/windows/crates/ps-service/src/killswitch.rs index 53a5fe5..ebdece8 100644 --- a/windows/crates/ps-service/src/killswitch.rs +++ b/windows/crates/ps-service/src/killswitch.rs @@ -63,11 +63,15 @@ const LOCAL: [&str; 13] = [ "0.0.0.0/32", ]; -/// What the tunnels are, for the plan. +/// What the tunnels are, for the plan: what is wanted on, whatever runs this moment (a tunnel +/// that failed or restarts is still held to). pub struct Tunnels { /// The TUN is configured, and wanted on now. pub tun: bool, - /// The system-wide AmneziaWG profiles' interface addresses (their `Address` lines). + /// A system-wide AmneziaWG profile is wanted on (turned on, or started at boot). + pub awg_on: bool, + /// Those profiles' interface addresses (their `Address` lines); none read still holds, + /// with nothing let out through them. pub awg: Vec, } @@ -75,7 +79,7 @@ pub struct Tunnels { /// or no global tunnel to protect). pub fn plan(cfg: &Config, tunnels: &Tunnels, lifted: bool, programs: Vec) -> Option { let k = &cfg.kill_switch; - if !cfg.enable || !k.enable || lifted || (!tunnels.tun && tunnels.awg.is_empty()) { + if !cfg.enable || !k.enable || lifted || (!tunnels.tun && !tunnels.awg_on) { return None; } let mut open: Vec = LOCAL.iter().filter_map(|n| Net::parse(n)).collect(); @@ -105,17 +109,27 @@ pub fn awg_addresses(conf: &str) -> Vec { } #[cfg(windows)] -pub use wfp::apply; +pub use wfp::{apply, installed}; + +/// Off Windows there is nothing to filter with: the plan is kept, for the status, and said. +#[cfg(not(windows))] +static APPLIED: std::sync::Mutex> = std::sync::Mutex::new(None); -/// Off Windows there is nothing to filter with: said, and left. #[cfg(not(windows))] pub fn apply(plan: Option<&Plan>) -> anyhow::Result<()> { if let Some(p) = plan { tracing::debug!("kill switch (not on this system): {} open ranges, {} tunnel ranges, {} programs", p.open.len(), p.tunnels.len(), p.programs.len()); } + *APPLIED.lock().unwrap_or_else(|e| e.into_inner()) = plan.cloned(); Ok(()) } +/// The plan whose filters are in place. +#[cfg(not(windows))] +pub fn installed() -> Option { + APPLIED.lock().unwrap_or_else(|e| e.into_inner()).clone() +} + #[cfg(windows)] mod wfp { use std::sync::Mutex; @@ -337,6 +351,11 @@ mod wfp { result.map(|()| engine) } + /// The plan whose filters are in place. + pub fn installed() -> Option { + ACTIVE.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(p, _, _)| p.clone()) + } + /// The filters for `plan` in place of the ones there (none: lifted). A plan already in /// place is left as it is; a new one is put in before the old goes, so nothing leaks /// between them. One that cannot be put in leaves the old one holding. @@ -382,22 +401,25 @@ mod tests { #[test] fn it_holds_only_with_a_tunnel_to_protect_and_not_lifted() { let c = cfg(); - let tun = Tunnels { tun: true, awg: Vec::new() }; - let none = Tunnels { tun: false, awg: Vec::new() }; + let tun = Tunnels { tun: true, awg_on: false, awg: Vec::new() }; + let none = Tunnels { tun: false, awg_on: false, awg: Vec::new() }; assert!(plan(&c, &tun, false, Vec::new()).is_some()); assert_eq!(plan(&c, &tun, true, Vec::new()), None, "lifted"); assert_eq!(plan(&c, &none, false, Vec::new()), None, "no tunnel"); let mut off = c.clone(); off.kill_switch.enable = false; assert_eq!(plan(&off, &tun, false, Vec::new()), None); - let awg = Tunnels { tun: false, awg: awg_addresses("[Interface]\nAddress = 10.8.0.2/24, fd00:8::2/64\n") }; + let awg = Tunnels { tun: false, awg_on: true, awg: awg_addresses("[Interface]\nAddress = 10.8.0.2/24, fd00:8::2/64\n") }; let p = plan(&c, &awg, false, Vec::new()).unwrap(); assert_eq!(p.tunnels, [Net::parse("10.8.0.2/32").unwrap(), Net::parse("fd00:8::2/128").unwrap()]); + // A profile wanted on whose addresses do not read still holds, letting nothing through it. + let unread = Tunnels { tun: false, awg_on: true, awg: Vec::new() }; + assert!(plan(&c, &unread, false, Vec::new()).is_some_and(|p| p.tunnels.is_empty())); } #[test] fn the_plan_opens_the_local_networks_and_the_tuns_addresses() { - let p = plan(&cfg(), &Tunnels { tun: true, awg: Vec::new() }, false, vec![PathBuf::from(r"C:\sing-box.exe")]).unwrap(); + let p = plan(&cfg(), &Tunnels { tun: true, awg_on: false, awg: Vec::new() }, false, vec![PathBuf::from(r"C:\sing-box.exe")]).unwrap(); for n in ["192.168.0.0/16", "fe80::/10", "198.51.100.0/24", "255.255.255.255/32"] { assert!(p.open.contains(&Net::parse(n).unwrap()), "{n}"); } diff --git a/windows/crates/ps-service/src/service.rs b/windows/crates/ps-service/src/service.rs index e58d4bd..4be5cda 100644 --- a/windows/crates/ps-service/src/service.rs +++ b/windows/crates/ps-service/src/service.rs @@ -44,9 +44,12 @@ pub struct Service { /// Whether the system-wide AmneziaWG tunnels were registered since the service started: /// the first time, the `autostart` ones start too. awg_vpn_started: bool, - /// The kill switch lifted: a tunnel turned off, or `proxy-ctl killswitch off`, until a - /// tunnel is turned on again (crate::killswitch). + /// The kill switch lifted (`proxy-ctl killswitch off`) until a tunnel is turned on again + /// (crate::killswitch). pub killswitch_lifted: bool, + /// The system-wide AmneziaWG profiles wanted on, by interface: started at boot, or turned + /// on since. What the kill switch holds to, whatever their tunnels are doing this moment. + pub awg_wanted: BTreeSet, } fn digest(data: &[u8]) -> String { @@ -73,6 +76,7 @@ impl Service { ap: Arc::default(), awg_vpn_started: false, killswitch_lifted: false, + awg_wanted: BTreeSet::new(), store, }) } @@ -221,8 +225,8 @@ impl Service { let cfg = self.cfg(); let paths = self.paths(); let tun = cfg.enable && cfg.proxy.enable && cfg.proxy.tun.enable && self.tun && self.proxy_on; - // A system-wide profile counts while it runs or is to start by itself. - let vpns: Vec<_> = crate::awgvpn::profiles(cfg).into_iter().filter(|v| v.autostart || matches!(crate::awgvpn::state(&v.iface).as_str(), "active" | "activating")).collect(); + // A system-wide profile counts while it is wanted on, whatever its tunnel is doing. + let vpns: Vec<_> = crate::awgvpn::profiles(cfg).into_iter().filter(|v| self.awg_wanted.contains(&v.iface)).collect(); let awg = vpns.iter().flat_map(|v| crate::killswitch::awg_addresses(&std::fs::read_to_string(crate::awgvpn::conf_path(paths, &v.iface)).unwrap_or_default())).collect(); let me = std::env::current_exe().ok(); let mut programs: Vec = self @@ -243,7 +247,7 @@ impl Service { } programs.sort(); programs.dedup(); - crate::killswitch::plan(cfg, &crate::killswitch::Tunnels { tun, awg }, self.killswitch_lifted, programs) + crate::killswitch::plan(cfg, &crate::killswitch::Tunnels { tun, awg_on: !vpns.is_empty(), awg }, self.killswitch_lifted, programs) } pub fn apply_killswitch(&mut self) -> Result<()> { @@ -256,6 +260,9 @@ impl Service { let cfg = self.cfg().clone(); let boot = !self.awg_vpn_started; self.awg_vpn_started = true; + if boot { + self.awg_wanted.extend(crate::awgvpn::profiles(&cfg).into_iter().filter(|v| v.autostart).map(|v| v.iface)); + } 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"); @@ -546,6 +553,17 @@ impl Service { warnings.extend(validate(cfg).into_iter().filter(|i| i.severity == Severity::Warning).map(|i| format!("{}: {}", i.path, i.message))); let units: Vec = self.sup.status().into_iter().map(|u| serde_json::to_value(u).unwrap()).collect(); let socks = self.sup.state_of(SOCKS_UNIT); + let kill_switch = { + let plan = self.killswitch_plan(); + let installed = crate::killswitch::installed(); + // What is in place, not what is meant to be. + json!({ + "enabled": cfg.kill_switch.enable, + "holding": plan.is_some() && installed == plan, + "failed": plan.is_some() && installed != plan, + "lifted": cfg.kill_switch.enable && self.killswitch_lifted, + }) + }; json!({ "units": units, "proxy": { @@ -559,11 +577,7 @@ impl Service { "pinned": self.store.state.pin, "selection": cfg.proxy.selection.as_str(), }, - "killSwitch": { - "enabled": cfg.kill_switch.enable, - "holding": self.killswitch_plan().is_some(), - "lifted": cfg.kill_switch.enable && self.killswitch_lifted, - }, + "killSwitch": kill_switch, "zapret": { "enabled": cfg.zapret.enable, "engine": serde_json::to_value(cfg.zapret.engine).unwrap(),