windows: the kill switch

Upstream's killSwitch, on the Windows Filtering Platform: while the TUN or a
system-wide AmneziaWG profile is on, connections that would leave past it are
blocked at the ALE connect layers, while the tunnel runs, restarts or has
failed. Open: loopback, the private and reserved networks with
allowedSubnets, what leaves from the tunnels' own addresses, the tunnel's own
programs (the backend, its helpers, awg-tunnel; the service with
directFallbacks), NTP with allowTimeSync. Turning a tunnel off, or
proxy-ctl killswitch off / the Overview's Lift, lifts it until a tunnel is
turned on again.

The filters live in a dynamic WFP session of the service's: they go with
it, so stopping the service always gets the network back. Upstream holds
from boot; that needs persistent filters, for once these are seen to work
on real Windows (Wine has no WFP). A changed plan goes in under the other of
two sublayers before the old one goes, so nothing leaks between.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-28 00:17:24 +03:00
1 parent ddc1bbe686
commit 32ff264c81
12 files changed
+557 -9

No files matched your search

+4 -2
View File
@@ -31,10 +31,11 @@ tray icon) or with `proxy-ctl`, as upstream's is.
| 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 | | 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) | | 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`, alongside zapret too — **see the caveats** | | TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on`, alongside zapret too — **see the caveats** |
| Kill switch | `killSwitch`: while the TUN or a system-wide AmneziaWG profile is on, what would leave past it is blocked (Windows Filtering Platform filters, in the service's session); LAN, DHCP, NTP and the tunnel's own programs stay open. `proxy-ctl killswitch [on\|off]`, or the Overview |
| 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; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy; in English or Russian (as Windows is set, or chosen); a light and a dark theme (or as Windows is set); a newer release installed from its Overview | | 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; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy; in English or Russian (as Windows is set, or chosen); a light and a dark theme (or as Windows is set); a newer release installed from its Overview |
Not in this release, still to come: Tor's onion service, Not in this release, still to come: Tor's onion service and
the kill switch and server inbounds. Their options are accepted (they are upstream's), but the server inbounds. 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. service says, in its status and in the app, that it does not run them yet.
Needs 64-bit Windows 10 (1903 or later) or 11. Needs 64-bit Windows 10 (1903 or later) or 11.
@@ -61,6 +62,7 @@ DPI bypass, which runs on Windows only, shows as inactive.
| Share-link and subscription parsing | upstream's tests, ported; ~750 links through upstream's Python and this, identical results | | Share-link and subscription parsing | upstream's tests, ported; ~750 links through upstream's Python and this, identical results |
| sing-box and XRay configs | rendered for many setups and accepted by `sing-box check` and `xray run -test` | | sing-box and XRay configs | rendered for many setups and accepted by `sing-box check` and `xray run -test` |
| The XRay-only backend | its config (listener login, DNS order and pinned server names, route modes, urltest balancer and pin, chains, helper hops, zapret's direct lists) accepted by `xray run -test` and asserted as upstream's filter vectors are; end to end on Linux: the service running xray with the release's own `geoip.dat`/`geosite.dat`, a page fetched through its listener and a Shadowsocks outbound (urltest, then pinned), a wrong password refused, the latency test refused as upstream refuses it | | The XRay-only backend | its config (listener login, DNS order and pinned server names, route modes, urltest balancer and pin, chains, helper hops, zapret's direct lists) accepted by `xray run -test` and asserted as upstream's filter vectors are; end to end on Linux: the service running xray with the release's own `geoip.dat`/`geosite.dat`, a page fetched through its listener and a Shadowsocks outbound (urltest, then pinned), a wrong password refused, the latency test refused as upstream refuses it |
| The kill switch | its plan (what stays open: local networks, the tunnels' addresses, their programs, NTP; when it holds and when it is lifted) by unit tests; the Windows Filtering Platform filters built and compiled for Windows. Not run: Wine has no Windows Filtering Platform, so whether the filters block and let through as meant needs real Windows |
| zapret beside the TUN | the filter part that leaves the TUN's packets out (IPv4 and IPv6), alone, with the cutoff probe's and around Flowseal's own filter as `--wf-raw` takes it, compiled by WinDivert's own `WinDivertHelperCompileFilter` (under Wine); zapret2's arguments with it checked by `winws2 --dry-run`. Traffic through both needs real Windows | | zapret beside the TUN | the filter part that leaves the TUN's packets out (IPv4 and IPv6), alone, with the cutoff probe's and around Flowseal's own filter as `--wf-raw` takes it, compiled by WinDivert's own `WinDivertHelperCompileFilter` (under Wine); zapret2's arguments with it checked by `winws2 --dry-run`. Traffic through both needs real Windows |
| Service, API, `proxy-ctl` | end to end on Linux: a real sing-box Shadowsocks server, the service, `proxy-ctl` adding the outbound, a page fetched through the local proxy | | Service, API, `proxy-ctl` | end to end on Linux: a real sing-box Shadowsocks server, the service, `proxy-ctl` adding the outbound, a page fetched through the local proxy |
| Windows build: service, named pipe, its ACL, caller identification, component hashes, supervisor | under Wine (`tools/wine-e2e.sh`) | | Windows build: service, named pipe, its ACL, caller identification, component hashes, supervisor | under Wine (`tools/wine-e2e.sh`) |
+3 -2
View File
@@ -9,8 +9,9 @@ use serde::{Deserialize, Serialize};
pub struct KillSwitch { pub struct KillSwitch {
/// Block outgoing traffic that bypasses the active global tunnel (TUN or a global /// Block outgoing traffic that bypasses the active global tunnel (TUN or a global
/// AmneziaWG profile), from the service's start until the tunnel is up, while it restarts /// AmneziaWG profile), from the service's start until the tunnel is up, while it restarts
/// and after it fails. Windows Filtering Platform filters do it, so it holds even while /// and after it fails. Windows Filtering Platform filters in the service's own session do
/// the service itself is stopped, until `proxy-ctl killswitch off`. /// it: they go with the service. `proxy-ctl killswitch off`, or turning the tunnel off,
/// lifts it until a tunnel is turned on again.
pub enable: bool, pub enable: bool,
pub direct_fallbacks: bool, pub direct_fallbacks: bool,
pub allowed_subnets: Vec<String>, pub allowed_subnets: Vec<String>,
@@ -119,7 +119,7 @@ pub fn validate(cfg: &Config) -> Vec<Issue> {
fn not_ported(cfg: &Config, v: &mut Issues) { fn not_ported(cfg: &Config, v: &mut Issues) {
const IGNORED: &str = "is not on Windows yet: this release ignores it"; const IGNORED: &str = "is not on Windows yet: this release ignores it";
if cfg.kill_switch.enable { if cfg.kill_switch.enable {
v.warn("killSwitch.enable", "the kill switch is not on Windows yet: nothing blocks traffic that bypasses the tunnel"); v.warn("killSwitch.enable", "on Windows the kill switch holds while the service runs, not from boot as upstream's: stopping the service lifts it");
} }
for (on, path, what) in [ for (on, path, what) in [
(cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"), (cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"),
@@ -897,9 +897,9 @@ mod tests {
cfg.zapret.enable = true; cfg.zapret.enable = true;
cfg.proxy.tun.enable = true; cfg.proxy.tun.enable = true;
let paths: Vec<String> = validate(&cfg).into_iter().filter(|i| i.severity == Severity::Warning && i.message.contains("Windows yet")).map(|i| i.path).collect(); let paths: Vec<String> = validate(&cfg).into_iter().filter(|i| i.severity == Severity::Warning && i.message.contains("Windows yet")).map(|i| i.path).collect();
assert!(paths.iter().any(|p| p == "killSwitch.enable"), "{paths:?}"); // Both are ported: the kill switch says how it differs, the TUN beside zapret nothing.
// The TUN beside zapret is: no warning for it any more. assert!(paths.is_empty(), "{paths:?}");
assert!(!paths.iter().any(|p| p == "proxy.tun.enable"), "{paths:?}"); assert!(validate(&cfg).iter().any(|i| i.path == "killSwitch.enable" && i.message.contains("not from boot")));
} }
#[test] #[test]
+32
View File
@@ -69,6 +69,12 @@ enum Cmd {
#[command(subcommand)] #[command(subcommand)]
verb: Option<ComponentsVerb>, verb: Option<ComponentsVerb>,
}, },
/// The kill switch: what it holds back, or lift it (off) until a tunnel is turned on, or
/// hold it again (on).
Killswitch {
#[command(subcommand)]
verb: Option<KillswitchVerb>,
},
/// Proxy Suite itself: whether a newer release is out, and installing it. /// Proxy Suite itself: whether a newer release is out, and installing it.
Update { Update {
#[command(subcommand)] #[command(subcommand)]
@@ -76,6 +82,13 @@ enum Cmd {
}, },
} }
#[derive(Subcommand)]
enum KillswitchVerb {
Status,
On,
Off,
}
#[derive(Subcommand)] #[derive(Subcommand)]
enum UpdateVerb { enum UpdateVerb {
/// This version, and a newer release if there is one. /// This version, and a newer release if there is one.
@@ -1006,6 +1019,25 @@ async fn real_main() -> Result<()> {
Cmd::Wl { verb } => wl(&ctl, verb).await?, Cmd::Wl { verb } => wl(&ctl, verb).await?,
Cmd::Awg { verb } => awg(&ctl, verb).await?, Cmd::Awg { verb } => awg(&ctl, verb).await?,
Cmd::Update { verb } => update(&ctl, verb).await?, Cmd::Update { verb } => update(&ctl, verb).await?,
Cmd::Killswitch { verb } => {
let on = match verb.unwrap_or(KillswitchVerb::Status) {
KillswitchVerb::Status => None,
KillswitchVerb::On => Some(true),
KillswitchVerb::Off => Some(false),
};
let r = ctl.call(Request::KillSwitch { on }).await?;
if ctl.json {
ctl.print(&r);
} else if r["enabled"] != true {
println!("The kill switch is off (killSwitch.enable).");
} else if r["holding"] == true {
println!("The kill switch holds: what would leave past the tunnel is blocked.");
} else if r["lifted"] == true {
println!("The kill switch is lifted until a tunnel is turned on (proxy-ctl killswitch on holds it again).");
} else {
println!("The kill switch holds nothing back: no global tunnel is on.");
}
}
Cmd::Tg { verb: TgVerb::Link } => { Cmd::Tg { verb: TgVerb::Link } => {
let r = ctl.call(Request::TgLinks).await?; let r = ctl.call(Request::TgLinks).await?;
for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) { for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) {
+26
View File
@@ -68,6 +68,24 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
.child(fact(tr("Backend"), text(&p["backend"]), cx)) .child(fact(tr("Backend"), text(&p["backend"]), cx))
.child(fact(tr("Mode"), p["mode"].as_str().unwrap_or("default").to_owned(), cx)) .child(fact(tr("Mode"), p["mode"].as_str().unwrap_or("default").to_owned(), cx))
.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)) .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 {
(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)
} else {
(tr("nothing to hold: no global tunnel is on"), "", true)
};
let model = model.clone();
d.child(
div().h_flex().gap_2().items_center().child(fact(tr("Kill switch"), state, cx)).when(!action.is_empty(), |d| {
d.child(Button::new("killswitch").xsmall().label(action).on_click(move |_, _, cx| {
model.update(cx, |m, cx| m.request(if on { tr("The kill switch holds again") } else { tr("The kill switch is lifted") }, ps_ipc::Request::KillSwitch { on: Some(on) }, cx))
}))
}),
)
})
.child({ .child({
let model = model.clone(); let model = model.clone();
let on = m.config()["proxy"]["systemProxy"]["enable"] == true; let on = m.config()["proxy"]["systemProxy"]["enable"] == true;
@@ -201,6 +219,14 @@ pub const RU: &[(&str, &str)] = &[
("{} (pinned)", "{} (закреплён)"), ("{} (pinned)", "{} (закреплён)"),
("{} selection", "выбор: {}"), ("{} selection", "выбор: {}"),
("Use it as the system proxy (browsers and most programs follow it)", "Использовать как системный прокси (ему следуют браузеры и большинство программ)"), ("Use it as the system proxy (browsers and most programs follow it)", "Использовать как системный прокси (ему следуют браузеры и большинство программ)"),
("Kill switch", "Kill switch"),
("holding: what would leave past the tunnel is blocked", "действует: всё, что пошло бы мимо туннеля, блокируется"),
("lifted until a tunnel is turned on", "снят до включения туннеля"),
("nothing to hold: no global tunnel is on", "не нужен: ни один общий туннель не включён"),
("Lift", "Снять"),
("Hold again", "Включить снова"),
("The kill switch holds again", "Kill switch снова действует"),
("The kill switch is lifted", "Kill switch снят"),
("The system proxy follows the local proxy", "Системный прокси следует за локальным прокси"), ("The system proxy follows the local proxy", "Системный прокси следует за локальным прокси"),
("The system proxy is left alone", "Системный прокси не затрагивается"), ("The system proxy is left alone", "Системный прокси не затрагивается"),
("Engine", "Движок"), ("Engine", "Движок"),
+6
View File
@@ -108,6 +108,12 @@ pub enum Request {
#[serde(default)] #[serde(default)]
probe: bool, probe: bool,
}, },
/// The kill switch: lift it (`on: false`, until a tunnel is turned on), hold it again
/// (`true`), or (none) what it does.
KillSwitch {
#[serde(default)]
on: Option<bool>,
},
/// This version, and the newest release if it is newer. /// This version, and the newest release if it is newer.
UpdateCheck, UpdateCheck,
/// Fetches the newest release's setup program, checks it, and runs it: the service stops, /// Fetches the newest release's setup program, checks it, and runs it: the service stops,
+2
View File
@@ -43,6 +43,8 @@ windows-sys = { workspace = true, features = [
"Win32_Networking_WinInet", "Win32_Networking_WinInet",
"Win32_System_RemoteDesktop", "Win32_System_RemoteDesktop",
"Win32_System_Environment", "Win32_System_Environment",
"Win32_NetworkManagement_WindowsFilteringPlatform",
"Win32_System_Rpc",
] } ] }
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
+22 -1
View File
@@ -141,6 +141,7 @@ fn scope_of(req: &Request) -> Option<Scope> {
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg), Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
Request::AwgLog { .. } => Some(Scope::Secrets), Request::AwgLog { .. } => Some(Scope::Secrets),
Request::ZapretCutoff { .. } => Some(Scope::Zapret), Request::ZapretCutoff { .. } => Some(Scope::Zapret),
Request::KillSwitch { on: Some(_) } => Some(Scope::Services),
_ => None, _ => None,
} }
} }
@@ -400,6 +401,8 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
return Response::err("the global TUN is off in the configuration (proxy.tun.enable)"); return Response::err("the global TUN is off in the configuration (proxy.tun.enable)");
} }
s.tun = true; s.tun = true;
// A tunnel turned on: the kill switch holds again.
s.killswitch_lifted = false;
} }
s.proxy_on = true; s.proxy_on = true;
applied(s.apply().await) applied(s.apply().await)
@@ -656,13 +659,20 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
} }
Request::AwgSet { name, on } => { Request::AwgSet { name, on } => {
let s = shared.lock().await; let mut s = shared.lock().await;
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else { 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?)")); 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. // The SCM's calls wait for the tunnel: not in the async runtime's threads.
let iface = vpn.iface.clone(); let iface = vpn.iface.clone();
let r = tokio::task::spawn_blocking(move || if on { crate::awgvpn::start(&iface) } else { crate::awgvpn::stop(&iface) }).await; 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.
if matches!(r, Ok(Ok(()))) {
s.killswitch_lifted = !on;
if let Err(e) = s.apply_killswitch() {
s.sup.note(crate::service::SOCKS_UNIT, format!("proxy-suite: the kill switch: {e:#}"));
}
}
match r { match r {
Ok(Ok(())) => Response::ok(json!({ "name": name, "state": crate::awgvpn::state(&vpn.iface) })), Ok(Ok(())) => Response::ok(json!({ "name": name, "state": crate::awgvpn::state(&vpn.iface) })),
Ok(Err(e)) => Response::err(format!("{e:#}")), Ok(Err(e)) => Response::err(format!("{e:#}")),
@@ -678,6 +688,17 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) })) Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
} }
Request::KillSwitch { on } => {
let mut s = shared.lock().await;
if let Some(on) = on {
s.killswitch_lifted = !on;
if let Err(e) = s.apply_killswitch() {
return Response::err(format!("{e:#}"));
}
}
Response::ok(s.status()["killSwitch"].clone())
}
Request::ZapretCutoff { probe } => { Request::ZapretCutoff { probe } => {
let s = shared.lock().await; let s = shared.lock().await;
if probe { if probe {
+410
View File
@@ -0,0 +1,410 @@
//! 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<Net> {
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<Net>,
/// Sources: the tunnels' own addresses, which what goes through them leaves from.
pub tunnels: Vec<Net>,
/// 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<PathBuf>,
/// 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.
pub struct Tunnels {
/// The TUN is configured, and wanted on now.
pub tun: bool,
/// The system-wide AmneziaWG profiles' interface addresses (their `Address` lines).
pub awg: Vec<Net>,
}
/// 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<PathBuf>) -> Option<Plan> {
let k = &cfg.kill_switch;
if !cfg.enable || !k.enable || lifted || (!tunnels.tun && tunnels.awg.is_empty()) {
return None;
}
let mut open: Vec<Net> = 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<Net> {
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;
/// 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());
}
Ok(())
}
#[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<Option<(Plan, Engine, usize)>> = 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<u16> {
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<FWP_V4_ADDR_AND_MASK>),
V6(Box<FWP_V6_ADDR_AND_MASK>),
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<bool>,
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<FWPM_FILTER_CONDITION0> =
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<Rule> {
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<Engine> {
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 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: Vec::new() };
let none = Tunnels { tun: 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 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()]);
}
#[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();
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)));
}
}
+1
View File
@@ -14,6 +14,7 @@ mod fetch;
mod install; mod install;
#[cfg(windows)] #[cfg(windows)]
mod job; mod job;
mod killswitch;
mod paths; mod paths;
mod service; mod service;
mod ssh; mod ssh;
+46
View File
@@ -44,6 +44,9 @@ pub struct Service {
/// Whether the system-wide AmneziaWG tunnels were registered since the service started: /// Whether the system-wide AmneziaWG tunnels were registered since the service started:
/// the first time, the `autostart` ones start too. /// the first time, the `autostart` ones start too.
awg_vpn_started: bool, 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).
pub killswitch_lifted: bool,
} }
fn digest(data: &[u8]) -> String { fn digest(data: &[u8]) -> String {
@@ -69,6 +72,7 @@ impl Service {
wl_waiting: BTreeSet::new(), wl_waiting: BTreeSet::new(),
ap: Arc::default(), ap: Arc::default(),
awg_vpn_started: false, awg_vpn_started: false,
killswitch_lifted: false,
store, store,
}) })
} }
@@ -206,9 +210,46 @@ impl Service {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}")); self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}"));
} }
let proxy = self.apply_proxy().await; let proxy = self.apply_proxy().await;
if let Err(e) = self.apply_killswitch() {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: the kill switch: {e:#}"));
}
zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy) zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy)
} }
/// What the kill switch leaves open now, if it holds anything back.
pub fn killswitch_plan(&self) -> Option<crate::killswitch::Plan> {
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();
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<std::path::PathBuf> = self
.env()
.direct_processes
.into_iter()
.map(std::path::PathBuf::from)
// The service's own fetches leave directly only with directFallbacks.
.filter(|p| cfg.kill_switch.direct_fallbacks || me.as_ref() != Some(p))
.collect();
let main = if cfg.proxy.backend == Backend::Xray { self.comps.xray() } else { self.comps.sing_box() };
programs.extend(main.ok());
if cfg.proxy.backend == Backend::Hybrid {
programs.extend(self.comps.xray().ok());
}
if !vpns.is_empty() {
programs.extend(self.comps.find("amneziawg", "awg-tunnel"));
}
programs.sort();
programs.dedup();
crate::killswitch::plan(cfg, &crate::killswitch::Tunnels { tun, awg }, self.killswitch_lifted, programs)
}
pub fn apply_killswitch(&mut self) -> Result<()> {
crate::killswitch::apply(self.killswitch_plan().as_ref())
}
/// AmneziaWG's system-wide tunnels: registered (their `.conf` written) or removed with /// AmneziaWG's system-wide tunnels: registered (their `.conf` written) or removed with
/// their profiles, the `autostart` ones started with the service. /// their profiles, the `autostart` ones started with the service.
fn apply_awg_vpn(&mut self) { fn apply_awg_vpn(&mut self) {
@@ -518,6 +559,11 @@ impl Service {
"pinned": self.store.state.pin, "pinned": self.store.state.pin,
"selection": cfg.proxy.selection.as_str(), "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,
},
"zapret": { "zapret": {
"enabled": cfg.zapret.enable, "enabled": cfg.zapret.enable,
"engine": serde_json::to_value(cfg.zapret.engine).unwrap(), "engine": serde_json::to_value(cfg.zapret.engine).unwrap(),
+1
View File
@@ -14,4 +14,5 @@ Each has its SHA-256 in the `.sha256` file next to it. SmartScreen may warn of a
- **The app in Russian**: every page, the tray's menu and the notifications, as Windows' display language is (or chosen in Settings → This app). What the service itself says (its warnings and errors) and `proxy-ctl` stay English. - **The app in Russian**: every page, the tray's menu and the notifications, as Windows' display language is (or chosen in Settings → This app). What the service itself says (its warnings and errors) and `proxy-ctl` stay English.
- **The XRay-only backend** (`proxy.backend = "xray"`): the local proxy runs on XRay alone, with upstream's config: a SOCKS listener (with a login when set), DNS ordered by the routing mode with the proxy servers' names kept off the proxy, the route modes' lists, `urltest` as a `leastPing` balancer with an observatory (a pin or `first` leaves the one exit), chains, and the helpers (Tor, SSH, WARP, AmneziaWG, whitelist-bypass) as SOCKS hops. What needs sing-box is refused as upstream refuses it (groups, rule sets, autoProxy, latency tests, `selector`/`failover`, DoT, fake IP, the connection log), and so are the TUN and per-app routing, which XRay has no Windows counterpart for yet. The service checks the config with `xray run -test` before it replaces the running one. - **The XRay-only backend** (`proxy.backend = "xray"`): the local proxy runs on XRay alone, with upstream's config: a SOCKS listener (with a login when set), DNS ordered by the routing mode with the proxy servers' names kept off the proxy, the route modes' lists, `urltest` as a `leastPing` balancer with an observatory (a pin or `first` leaves the one exit), chains, and the helpers (Tor, SSH, WARP, AmneziaWG, whitelist-bypass) as SOCKS hops. What needs sing-box is refused as upstream refuses it (groups, rule sets, autoProxy, latency tests, `selector`/`failover`, DoT, fake IP, the connection log), and so are the TUN and per-app routing, which XRay has no Windows counterpart for yet. The service checks the config with `xray run -test` before it replaces the running one.
- **The TUN and the DPI bypass together**: zapret and zapret2 leave the TUN's own packets alone (by its address, in WinDivert's filter) and handle what sing-box sends out of the real adapter, as upstream keeps zapret off the TUN interface. - **The TUN and the DPI bypass together**: zapret and zapret2 leave the TUN's own packets alone (by its address, in WinDivert's filter) and handle what sing-box sends out of the real adapter, as upstream keeps zapret off the TUN interface.
- **The kill switch** (`killSwitch`, off by default): while the global tunnel (the TUN, or a system-wide AmneziaWG profile) is on, what would leave past it is blocked, while it runs, restarts or has failed; LAN, DHCP and NTP stay open, and the tunnel's own programs. Windows Filtering Platform filters do it, in the service's own session: they go with the service (upstream's holds from boot; that comes once these have been seen to work on real Windows). Turning the tunnel off, `proxy-ctl killswitch off` or the Overview's **Lift** lets go until a tunnel is turned on again. Not yet tried on real Windows: please do, and `sc stop ProxySuite` gets the network back if it misbehaves.
- **A dark theme**: light, dark, or as Windows is set (the default), in Settings → This app or at the sun/moon in the sidebar; the window's title bar follows it. - **A dark theme**: light, dark, or as Windows is set (the default), in Settings → This app or at the sun/moon in the sidebar; the window's title bar follows it.