//! The kill switch (upstream's `killSwitch`, there in nftables): what would leave past the //! global tunnel (the TUN, or a system-wide AmneziaWG profile) is blocked, while the tunnel runs //! and while it restarts or has failed. LAN, DHCP and NTP stay open, and so do the tunnel's own //! programs. Turning the tunnel off (`proxy-ctl proxy tun off`, `awg off`) or `proxy-ctl //! killswitch off` lifts it until a tunnel is turned on again. //! //! On Windows: Windows Filtering Platform filters in a dynamic session of this service's, so //! they go with the service: stopping it lifts them. (Upstream's holds from boot; that needs //! persistent filters, left for when these have been seen to work.) use std::net::IpAddr; use std::path::PathBuf; use ps_core::config::Config; /// An address range: an address and its prefix length. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Net { pub addr: IpAddr, pub prefix: u8, } impl Net { pub fn parse(s: &str) -> Option { let s = s.trim(); let (a, p) = s.split_once('/').unwrap_or((s, "")); let addr: IpAddr = a.trim().parse().ok()?; let max = if addr.is_ipv4() { 32 } else { 128 }; let prefix = if p.is_empty() { max } else { p.trim().parse().ok().filter(|p| *p <= max)? }; Some(Net { addr, prefix }) } } /// What the kill switch leaves open; everything else that leaves is blocked. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct Plan { /// Destinations: the local networks, private and reserved ranges, `allowedSubnets`. pub open: Vec, /// Sources: the tunnels' own addresses, which what goes through them leaves from. pub tunnels: Vec, /// Programs that reach the network themselves: the tunnel's own (sing-box, its helpers, /// the AmneziaWG tunnel), and the service when `directFallbacks` lets it fetch directly. pub programs: Vec, /// NTP (UDP 123) to anywhere: `allowTimeSync`. pub time_sync: bool, } /// The ranges upstream's kill switch leaves open besides `allowedSubnets`: this machine, the /// private and reserved networks, link-local, multicast and broadcast (DHCP's among them). const LOCAL: [&str; 13] = [ "127.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "224.0.0.0/4", "255.255.255.255/32", "::1/128", "fc00::/7", "fe80::/10", "ff00::/8", "0.0.0.0/32", ]; /// 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, /// 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, } /// What the kill switch would leave open now; None when it holds nothing back (off, lifted, /// 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_on) { return None; } let mut open: Vec = LOCAL.iter().filter_map(|n| Net::parse(n)).collect(); open.extend(k.allowed_subnets.iter().filter_map(|n| Net::parse(n))); let mut tun_nets = Vec::new(); if tunnels.tun { tun_nets.extend(Net::parse(&cfg.proxy.tun.address)); if cfg.proxy.ipv6 { tun_nets.extend(Net::parse(ps_core::render::TUN_IPV6_ADDRESS)); } } tun_nets.extend(tunnels.awg.iter().copied()); Some(Plan { open, tunnels: tun_nets, programs, time_sync: k.allow_time_sync }) } /// A system-wide profile's addresses, from its configuration's `Address` lines. pub fn awg_addresses(conf: &str) -> Vec { conf.lines() .filter_map(|l| { let (k, v) = l.split_once('=')?; k.trim().eq_ignore_ascii_case("address").then_some(v) }) .flat_map(|v| v.split(',')) .filter_map(Net::parse) .map(|n| Net { prefix: if n.addr.is_ipv4() { 32 } else { 128 }, ..n }) .collect() } #[cfg(windows)] 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); #[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; use anyhow::{Result, bail}; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::NetworkManagement::WindowsFilteringPlatform::*; use windows_sys::core::GUID; use super::{IpAddr, Net, Plan}; /// The session the filters live in: closing it removes them. struct Engine(HANDLE); // SAFETY: a WFP engine handle may be used and closed from any thread. unsafe impl Send for Engine {} impl Drop for Engine { fn drop(&mut self) { // SAFETY: a handle FwpmEngineOpen0 gave, closed once. unsafe { FwpmEngineClose0(self.0) }; } } /// The plan in place, its session, and which of the two sublayers it took. static ACTIVE: Mutex> = Mutex::new(None); /// Two keys, taken in turn: a new plan's filters go in under one while the old plan's still /// hold under the other, so nothing leaks between them. const SUBLAYERS: [GUID; 2] = [GUID::from_u128(0x6f0d_4a3e_8f1c_4b2a_9d57_2c1e_8a4b_7f31), GUID::from_u128(0x6f0d_4a3e_8f1c_4b2a_9d57_2c1e_8a4b_7f32)]; const RPC_C_AUTHN_WINNT: u32 = 10; fn wide(s: &str) -> Vec { s.encode_utf16().chain(Some(0)).collect() } fn check(rc: u32, what: &str) -> Result<()> { if rc != 0 { bail!("{what}: WFP error {rc:#x}"); } Ok(()) } /// One condition's value, kept alive (with what it points to) until the filters are added. enum Value { V4(Box), V6(Box), U8(u8), U16(u16), U32(u32), Blob(*mut FWP_BYTE_BLOB), } fn value(v: &Value) -> FWP_CONDITION_VALUE0 { // SAFETY: plain data; the unions take the member the type names. unsafe { let mut c: FWP_CONDITION_VALUE0 = std::mem::zeroed(); match v { Value::V4(m) => { c.r#type = FWP_V4_ADDR_MASK; c.Anonymous.v4AddrMask = (&**m as *const FWP_V4_ADDR_AND_MASK).cast_mut(); } Value::V6(m) => { c.r#type = FWP_V6_ADDR_MASK; c.Anonymous.v6AddrMask = (&**m as *const FWP_V6_ADDR_AND_MASK).cast_mut(); } Value::U8(n) => { c.r#type = FWP_UINT8; c.Anonymous.uint8 = *n; } Value::U16(n) => { c.r#type = FWP_UINT16; c.Anonymous.uint16 = *n; } Value::U32(n) => { c.r#type = FWP_UINT32; c.Anonymous.uint32 = *n; } Value::Blob(b) => { c.r#type = FWP_BYTE_BLOB_TYPE; c.Anonymous.byteBlob = *b; } } c } } fn net(n: &Net) -> Value { match n.addr { IpAddr::V4(a) => { let mask = if n.prefix == 0 { 0 } else { u32::MAX << (32 - u32::from(n.prefix)) }; Value::V4(Box::new(FWP_V4_ADDR_AND_MASK { addr: u32::from(a) & mask, mask })) } IpAddr::V6(a) => Value::V6(Box::new(FWP_V6_ADDR_AND_MASK { addr: a.octets(), prefixLength: n.prefix })), } } /// A filter of `conditions` (field, match, value), all of them to hold. struct Rule { name: &'static str, v6: Option, conditions: Vec<(GUID, FWP_MATCH_TYPE, Value)>, permit: bool, weight: u8, } fn add(engine: HANDLE, rule: &Rule, layer: GUID, sublayer: GUID) -> Result<()> { let mut conds: Vec = rule.conditions.iter().map(|(field, m, v)| FWPM_FILTER_CONDITION0 { fieldKey: *field, matchType: *m, conditionValue: value(v) }).collect(); let mut name = wide(&format!("Proxy Suite kill switch: {}", rule.name)); // SAFETY: the filter and what it points to live across the call; zeroed fields are // WFP's "none". unsafe { let mut f: FWPM_FILTER0 = std::mem::zeroed(); f.displayData.name = name.as_mut_ptr(); f.layerKey = layer; f.subLayerKey = sublayer; f.weight.r#type = FWP_UINT8; f.weight.Anonymous.uint8 = rule.weight; f.numFilterConditions = conds.len() as u32; f.filterCondition = if conds.is_empty() { std::ptr::null_mut() } else { conds.as_mut_ptr() }; f.action.r#type = if rule.permit { FWP_ACTION_PERMIT } else { FWP_ACTION_BLOCK }; let mut id = 0u64; check(FwpmFilterAdd0(engine, &f, std::ptr::null_mut(), &mut id), rule.name) } } /// The filters for `plan`: permits above, the block beneath, in a sublayer of their own. fn rules(plan: &Plan, apps: &[*mut FWP_BYTE_BLOB]) -> Vec { let mut out = vec![Rule { name: "loopback", v6: None, conditions: vec![(FWPM_CONDITION_FLAGS, FWP_MATCH_FLAGS_ALL_SET, Value::U32(FWP_CONDITION_FLAG_IS_LOOPBACK))], permit: true, weight: 15, }]; for n in &plan.open { out.push(Rule { name: "local network", v6: Some(n.addr.is_ipv6()), conditions: vec![(FWPM_CONDITION_IP_REMOTE_ADDRESS, FWP_MATCH_EQUAL, net(n))], permit: true, weight: 14 }); } for n in &plan.tunnels { out.push(Rule { name: "through the tunnel", v6: Some(n.addr.is_ipv6()), conditions: vec![(FWPM_CONDITION_IP_LOCAL_ADDRESS, FWP_MATCH_EQUAL, net(n))], permit: true, weight: 14 }); } for app in apps { out.push(Rule { name: "the tunnel's own program", v6: None, conditions: vec![(FWPM_CONDITION_ALE_APP_ID, FWP_MATCH_EQUAL, Value::Blob(*app))], permit: true, weight: 13 }); } if plan.time_sync { out.push(Rule { name: "NTP", v6: None, conditions: vec![(FWPM_CONDITION_IP_PROTOCOL, FWP_MATCH_EQUAL, Value::U8(17)), (FWPM_CONDITION_IP_REMOTE_PORT, FWP_MATCH_EQUAL, Value::U16(123))], permit: true, weight: 12, }); } out.push(Rule { name: "everything else", v6: None, conditions: Vec::new(), permit: false, weight: 0 }); out } fn install(plan: &Plan, sublayer: GUID) -> Result { let mut engine: HANDLE = std::ptr::null_mut(); let mut session_name = wide("Proxy Suite kill switch"); // SAFETY: zeroed is WFP's "none" for the session's other fields; the name lives across // the call. unsafe { let mut session: FWPM_SESSION0 = std::mem::zeroed(); session.displayData.name = session_name.as_mut_ptr(); session.flags = FWPM_SESSION_FLAG_DYNAMIC; check(FwpmEngineOpen0(std::ptr::null(), RPC_C_AUTHN_WINNT, std::ptr::null(), &session, &mut engine), "opening the filtering engine")?; } let engine = Engine(engine); let mut apps: Vec<*mut FWP_BYTE_BLOB> = Vec::new(); for p in &plan.programs { let mut blob: *mut FWP_BYTE_BLOB = std::ptr::null_mut(); let path = wide(&p.to_string_lossy()); // SAFETY: a NUL-terminated path; the blob is freed below. if unsafe { FwpmGetAppIdFromFileName0(path.as_ptr(), &mut blob) } == 0 { apps.push(blob); } else { tracing::warn!("kill switch: no application id for {}", p.display()); } } let result = (|| -> Result<()> { // SAFETY: the engine is open; the transaction is committed or aborted below. unsafe { check(FwpmTransactionBegin0(engine.0, 0), "starting a transaction")? }; let added = (|| -> Result<()> { let mut name = wide("Proxy Suite kill switch"); // SAFETY: zeroed fields are "none"; the name lives across the call. unsafe { let mut sub: FWPM_SUBLAYER0 = std::mem::zeroed(); sub.subLayerKey = sublayer; sub.displayData.name = name.as_mut_ptr(); sub.weight = 0xffff; check(FwpmSubLayerAdd0(engine.0, &sub, std::ptr::null_mut()), "adding the sublayer")?; } for rule in rules(plan, &apps) { for (v6, layer) in [(false, FWPM_LAYER_ALE_AUTH_CONNECT_V4), (true, FWPM_LAYER_ALE_AUTH_CONNECT_V6)] { if rule.v6.is_none_or(|r| r == v6) { add(engine.0, &rule, layer, sublayer)?; } } } Ok(()) })(); // SAFETY: the transaction begun above. unsafe { match &added { Ok(()) => check(FwpmTransactionCommit0(engine.0), "committing the filters")?, Err(_) => { FwpmTransactionAbort0(engine.0); } } } added })(); for mut blob in apps { // SAFETY: each from FwpmGetAppIdFromFileName0, freed once. unsafe { FwpmFreeMemory0((&mut blob as *mut *mut FWP_BYTE_BLOB).cast()) }; } 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. pub fn apply(plan: Option<&Plan>) -> Result<()> { let mut active = ACTIVE.lock().unwrap_or_else(|e| e.into_inner()); match plan { None => { if active.take().is_some() { tracing::info!("kill switch: lifted"); } Ok(()) } Some(p) if active.as_ref().is_some_and(|(q, _, _)| q == p) => Ok(()), Some(p) => { let next = active.as_ref().map_or(0, |(_, _, i)| 1 - i); let engine = install(p, SUBLAYERS[next])?; tracing::info!("kill switch: holding ({} open ranges, {} tunnel ranges, {} programs)", p.open.len(), p.tunnels.len(), p.programs.len()); // The old session closes, and its filters with it, once the new ones hold. *active = Some((p.clone(), engine, next)); Ok(()) } } } } #[cfg(test)] mod tests { use std::net::{Ipv4Addr, Ipv6Addr}; use super::*; fn cfg() -> Config { let mut c = Config::default(); c.enable = true; c.kill_switch.enable = true; c.kill_switch.allowed_subnets = vec!["198.51.100.0/24".into()]; c.proxy.enable = true; c.proxy.tun.enable = true; c.proxy.ipv6 = true; c } #[test] fn it_holds_only_with_a_tunnel_to_protect_and_not_lifted() { let c = cfg(); 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_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_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}"); } assert_eq!(p.tunnels, [Net::parse(&Config::default().proxy.tun.address).unwrap(), Net::parse(ps_core::render::TUN_IPV6_ADDRESS).unwrap()]); assert_eq!(p.programs, [PathBuf::from(r"C:\sing-box.exe")]); assert_eq!(Net::parse("10.1.2.3"), Some(Net { addr: IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)), prefix: 32 })); assert_eq!(Net::parse("::1/129"), None); assert_eq!(Net::parse("fd00::/8").unwrap().addr, IpAddr::V6(Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 0))); } }