windows: AmneziaWG as a system-wide VPN

Each profile without asOutbound is a tunnel service of its own,
AmneziaWGTunnel$<interface>, as amneziawg-windows's client installs one:
amneziawg-go on Wintun, its routes and DNS, and for one peer that takes
everything its firewall blocking what would leave outside the tunnel.
It runs awg-tunnel.exe, amneziawg-windows built from its pinned commit
with a main of ours (its Run(), its log in a file) instead of its
tunnel.dll, beside Wintun's signed DLL (tools/build-amneziawg.sh).

The service writes each profile's .conf below its state root, registers
the tunnel (unrestricted service SID, which its firewall exempts it by),
starts the autostart ones with itself, and removes the tunnels of
profiles gone, and all of them on uninstall. proxy-ctl awg
list|on|off|log, and the app's AmneziaWG page: profiles (a system-wide
one switched on and off, its log), one added from a vpn:// link or a
.conf, or removed.

tools/lib.sh: clone_commit, and fetch_pinned, which fetches in pieces a
download that stalls (some networks cut TLS after about 16 KB, as
wintun.net's here).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 17:23:11 +03:00
1 parent 95ec15e14a
commit 5cf3a237e6
30 files changed
+916 -12

No files matched your search

+45
View File
@@ -137,6 +137,8 @@ fn scope_of(req: &Request) -> Option<Scope> {
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<Value> = 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 {
+322
View File
@@ -0,0 +1,322 @@
//! AmneziaWG as a system-wide VPN: each profile with no `asOutbound` is a tunnel service of
//! its own, `AmneziaWGTunnel$<interface name>`, 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<Vpn> {
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 `<interface>.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<String> {
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<PathBuf> {
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<String> {
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> {
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<String> {
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::<Vec<_>>(), [("home", "home", true), ("office", "awg-office", false)]);
assert_eq!(service_name("home"), "AmneziaWGTunnel$home");
cfg.amnezia_wg.enable = false;
assert!(profiles(&cfg).is_empty());
}
}
+1
View File
@@ -6,6 +6,7 @@
mod api;
mod autoproxy;
mod awg;
mod awgvpn;
mod clash;
mod components;
mod fetch;
+23
View File
@@ -41,6 +41,9 @@ pub struct Service {
wl_waiting: BTreeSet<String>,
/// autoProxy's requests and the hosts its prober learns from (crate::autoproxy).
pub ap: Arc<crate::autoproxy::AutoProxy>,
/// 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<()> {
+1
View File
@@ -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();