diff --git a/README.md b/README.md index 66254c2..b8eca3d 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Declarative proxy stack for NixOS. -Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.com/XTLS/Xray-core), [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy). Built specifically for dealing with Roskomnadzor (RKN) and the usual Russian ISP nonsense. +Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.com/XTLS/Xray-core), native [AmneziaWG](https://github.com/amnezia-vpn/amneziawg-go) client tunnels, [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy). Built specifically for dealing with Roskomnadzor (RKN) and the usual Russian ISP nonsense. The goal is to replace GUI clients like v2rayN and throne – you configure your proxies in Nix, rebuild, and they just work as systemd services. @@ -14,6 +14,7 @@ The goal is to replace GUI clients like v2rayN and throne – you configure your - **Backend choice** – use SingBox or XRay through the same `services.proxy-suite.proxy` option tree - **Transparent proxy (TProxy)** – redirect all system traffic through the active backend without configuring each app; start/stop on demand or autostart at boot - **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something, with optional boot-time autostart +- **AmneziaWG profiles** – native AWG 1.x–3.x tunnels from `.conf`, self-contained `vpn://`, or declarative Nix configuration - **Per-app wrapping** – run selected apps through the local proxy with `proxy-ctl wrap -- `, without enabling global TProxy or TUN - **Subscription URLs** – point at a v2rayN/Clash-format subscription endpoint; the module fetches, decodes, and imports all proxies automatically, with a periodic refresh timer - **Multiple outbounds** with automatic latency-based switching or manual selection @@ -90,6 +91,21 @@ services.proxy-suite = { }; }; + # Native AmneziaWG profiles are independent of the SingBox/XRay backend. + # Only one AWG, TUN, or TProxy global tunnel can be active at once; + # zapret is mutually exclusive with AWG while its service is running. + amneziaWg = { + enable = true; + profiles.home = { + # Secret-managed exported .conf files are the simplest input. + configFile = "/run/secrets/home-amneziawg.conf"; + autostart = false; + }; + + # Self-contained AmneziaVPN exports are supported too: + profiles.work.vpnFile = "/run/secrets/work-amnezia.vpn"; + }; + zapret = { enable = true; perApp.enable = true; @@ -140,6 +156,10 @@ Commands: proxy on|off enable/disable the proxy backend stack tproxy on|off enable/disable TProxy transparent mode tun on|off enable/disable TUN mode + awg list|status [profile] list profiles or show AmneziaWG status + awg on start an AmneziaWG profile + awg off [profile] stop one or all active AmneziaWG profiles + awg restart [profile] restart one or all active AmneziaWG profiles route-mode default|whitelist|blacklist|all-proxy|all-bypass|status set temporary routing override zapret on|off enable/disable zapret-discord-youtube diff --git a/docs/options.md b/docs/options.md index 93d1a08..3bde50d 100644 --- a/docs/options.md +++ b/docs/options.md @@ -10,6 +10,64 @@ Update module option docs there instead of editing this file by hand. - [Complete example config](#complete-example-config) - services.proxy-suite - [enable](#services-proxy-suite-enable) + - amneziaWg + - [enable](#services-proxy-suite-amneziawg-enable) + - [kernelModulePackage](#services-proxy-suite-amneziawg-kernelmodulepackage) + - [profiles](#services-proxy-suite-amneziawg-profiles) + - + - [allowConfigHooks](#services-proxy-suite-amneziawg-profiles-name-allowconfighooks) + - [autostart](#services-proxy-suite-amneziawg-profiles-name-autostart) + - [configFile](#services-proxy-suite-amneziawg-profiles-name-configfile) + - [interfaceName](#services-proxy-suite-amneziawg-profiles-name-interfacename) + - [settings](#services-proxy-suite-amneziawg-profiles-name-settings) + - [addresses](#services-proxy-suite-amneziawg-profiles-name-settings-addresses) + - [dns](#services-proxy-suite-amneziawg-profiles-name-settings-dns) + - [listenPort](#services-proxy-suite-amneziawg-profiles-name-settings-listenport) + - [mtu](#services-proxy-suite-amneziawg-profiles-name-settings-mtu) + - [obfuscation](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation) + - [contentPaddingAddition](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-contentpaddingaddition) + - [disableCookies](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-disablecookies) + - [h1](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h1) + - [h2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h2) + - [h3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h3) + - [h4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h4) + - [headerProtectionKey](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkey) + - [headerProtectionKeyFile](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkeyfile) + - [i1](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i1) + - [i2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i2) + - [i3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i3) + - [i4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i4) + - [i5](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i5) + - [jc](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jc) + - [jmax](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmax) + - [jmin](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmin) + - [keepaliveTimeout](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-keepalivetimeout) + - [maxHandshakeAttempts](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-maxhandshakeattempts) + - [randomTrailers](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-randomtrailers) + - [rejectAfterTime](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rejectaftertime) + - [rekeyAfterTime](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeyaftertime) + - [rekeyTimeout](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeytimeout) + - [s1](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s1) + - [s2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s2) + - [s3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s3) + - [s4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s4) + - [peers](#services-proxy-suite-amneziawg-profiles-name-settings-peers) + - item + - [advancedSecurity](#services-proxy-suite-amneziawg-profiles-name-settings-peers-advancedsecurity) + - [allowedIPs](#services-proxy-suite-amneziawg-profiles-name-settings-peers-allowedips) + - [endpoint](#services-proxy-suite-amneziawg-profiles-name-settings-peers-endpoint) + - [persistentKeepalive](#services-proxy-suite-amneziawg-profiles-name-settings-peers-persistentkeepalive) + - [presharedKey](#services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkey) + - [presharedKeyFile](#services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkeyfile) + - [publicKey](#services-proxy-suite-amneziawg-profiles-name-settings-peers-publickey) + - [privateKey](#services-proxy-suite-amneziawg-profiles-name-settings-privatekey) + - [privateKeyFile](#services-proxy-suite-amneziawg-profiles-name-settings-privatekeyfile) + - [table](#services-proxy-suite-amneziawg-profiles-name-settings-table) + - [vpn](#services-proxy-suite-amneziawg-profiles-name-vpn) + - [vpnContainer](#services-proxy-suite-amneziawg-profiles-name-vpncontainer) + - [vpnFile](#services-proxy-suite-amneziawg-profiles-name-vpnfile) + - [toolsPackage](#services-proxy-suite-amneziawg-toolspackage) + - [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage) - perAppRouting - [enable](#services-proxy-suite-perapprouting-enable) - [createDefaultProfiles](#services-proxy-suite-perapprouting-createdefaultprofiles) @@ -188,6 +246,13 @@ Update module option docs there instead of editing this file by hand. ```nix services.proxy-suite = { + amneziaWg = { + enable = false; + kernelModulePackage = ; + profiles = { }; + toolsPackage = ; + userspacePackage = ; + }; enable = false; perAppRouting = { createDefaultProfiles = false; @@ -369,6 +434,13 @@ This is generated by filling in all the options with example values (or defaults ```nix services.proxy-suite = { + amneziaWg = { + enable = true; + kernelModulePackage = ; + profiles = { }; + toolsPackage = ; + userspacePackage = ; + }; enable = true; perAppRouting = { createDefaultProfiles = true; @@ -672,7 +744,9 @@ services.proxy-suite = { ## services\.proxy-suite\.enable -Whether to enable proxy suite (proxy backend + zapret + tg-ws-proxy)\. + + +Whether to enable proxy suite (proxy backend + AmneziaWG + zapret + tg-ws-proxy)\. @@ -700,6 +774,1408 @@ true + +## services\.proxy-suite\.amneziaWg\.enable + +Whether to enable native AmneziaWG client profiles\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +false +``` + + + +*Example:* + +```nix +true +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.kernelModulePackage + + + +AWG 3\.1 kernel module package\. Set null to use userspace-only fallback\. + + + +*Type:* +null or package + + + +*Default:* + +```nix + +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles + + + +Named AmneziaWG client profiles\. Only one global profile can be active\. + + + +*Type:* +attribute set of (submodule) + + + +*Default:* + +```nix +{ } +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.allowConfigHooks + + + +Allow trusted imported configs to execute wg-quick hooks or use SaveConfig\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +false +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.autostart + + + +Whether to start this profile at boot\. At most one profile may autostart\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +false +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.configFile + + + +Runtime path to an AmneziaWG \.conf file\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.interfaceName + + + +Linux interface name\. It must fit Linux’s 15-character limit\. + + + +*Type:* +string matching the pattern ^\[A-Za-z0-9_\.-]{1,15}$ + + + +*Default:* + +```nix +"awg-‹name›" +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings + + + +Typed declarative AmneziaWG client configuration\. + + + +*Type:* +null or (submodule) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.addresses + + + +IP prefixes assigned to the AWG interface\. + + + +*Type:* +list of string + + + +*Default:* + +```nix +[ ] +``` + + + +*Example:* + +```nix +[ + "10.8.0.2/32" +] +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.dns + + + +DNS servers installed while this profile is active\. + + + +*Type:* +list of string + + + +*Default:* + +```nix +[ ] +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.listenPort + + + +Optional local UDP listen port\. + + + +*Type:* +null or 16 bit unsigned integer; between 0 and 65535 (both inclusive) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.mtu + + + +Optional interface MTU\. + + + +*Type:* +null or (unsigned integer, meaning >=0) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation + + + +AmneziaWG 1\.x through 3\.x obfuscation parameters\. + + + +*Type:* +submodule + + + +*Default:* + +```nix +{ } +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.contentPaddingAddition + + + +AWG 3 content-padding addition or range\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.disableCookies + + + +AWG 3 cookie suppression (DisableCookies)\. + + + +*Type:* +null or boolean + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.h1 + + + +Handshake-init header or range (H1)\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.h2 + + + +Handshake-response header or range (H2)\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.h3 + + + +Cookie-reply header or range (H3)\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.h4 + + + +Transport-message header or range (H4)\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.headerProtectionKey + + + +Inline AWG 3 header-protection key\. Prefer headerProtectionKeyFile\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.headerProtectionKeyFile + + + +Runtime path containing the AWG 3 header-protection key\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i1 + + + +First custom signature packet (I1)\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i2 + + + +Second custom signature packet (I2)\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i3 + + + +Third custom signature packet (I3)\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i4 + + + +Fourth custom signature packet (I4)\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.i5 + + + +Fifth custom signature packet (I5)\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.jc + + + +Junk packet count (Jc)\. + + + +*Type:* +null or (unsigned integer, meaning >=0) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.jmax + + + +Maximum junk packet size (Jmax)\. + + + +*Type:* +null or (unsigned integer, meaning >=0) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.jmin + + + +Minimum junk packet size (Jmin)\. + + + +*Type:* +null or (unsigned integer, meaning >=0) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.keepaliveTimeout + + + +AWG 3 keepalive timeout or range\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.maxHandshakeAttempts + + + +AWG 3 maximum handshake attempts or range\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.randomTrailers + + + +AWG 3 random transport trailers (RandomTrailers)\. + + + +*Type:* +null or boolean + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.rejectAfterTime + + + +AWG 3 reject-after interval or range\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.rekeyAfterTime + + + +AWG 3 rekey interval or range\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.rekeyTimeout + + + +AWG 3 rekey timeout or range\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s1 + + + +Handshake-init padding (S1)\. + + + +*Type:* +null or (unsigned integer, meaning >=0) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s2 + + + +Handshake-response padding (S2)\. + + + +*Type:* +null or (unsigned integer, meaning >=0) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s3 + + + +Cookie-reply padding (S3)\. + + + +*Type:* +null or (unsigned integer, meaning >=0) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.obfuscation\.s4 + + + +Transport-message padding (S4)\. + + + +*Type:* +null or (unsigned integer, meaning >=0) + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers + + + +AmneziaWG peers\. + + + +*Type:* +list of (submodule) + + + +*Default:* + +```nix +[ ] +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.advancedSecurity + + + +Optional AWG peer AdvancedSecurity setting\. + + + +*Type:* +null or boolean + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.allowedIPs + + + +IP prefixes routed to and accepted from this peer\. + + + +*Type:* +list of string + + + +*Default:* + +```nix +[ ] +``` + + + +*Example:* + +```nix +[ + "0.0.0.0/0" + "::/0" +] +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.endpoint + + + +Optional peer endpoint in host:port form\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"vpn.example.com:51820" +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.persistentKeepalive + + + +Persistent keepalive seconds, optionally expressed as an AWG 3 range\. + + + +*Type:* +null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$ + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.presharedKey + + + +Inline peer preshared key\. Prefer presharedKeyFile for secrets\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.presharedKeyFile + + + +Runtime path containing the peer preshared key\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.peers\.\*\.publicKey + + + +AmneziaWG peer public key\. + + + +*Type:* +string matching the pattern \[^\[:space:]]+ + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.privateKey + + + +Inline client private key\. Prefer privateKeyFile\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.privateKeyFile + + + +Runtime path containing the client private key\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.settings\.table + + + +wg-quick routing table name/number, auto, or off\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.vpn + + + +Inline self-contained vpn:// export\. This value is stored in the Nix store\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.vpnContainer + + + +AWG container/protocol identifier to select when a vpn:// bundle is ambiguous\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.vpnFile + + + +Runtime path containing a self-contained vpn:// export\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.toolsPackage + + + +AWG 3\.1 package providing awg and awg-quick\. + + + +*Type:* +package + + + +*Default:* + +```nix + +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + + +## services\.proxy-suite\.amneziaWg\.userspacePackage + + + +AWG 3\.1 userspace implementation used when the kernel interface is unavailable\. + + + +*Type:* +package + + + +*Default:* + +```nix + +``` + +*Declared by:* + - [modules/proxy-suite/options/amnezia-wg\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/amnezia-wg.nix) + + + ## services\.proxy-suite\.perAppRouting\.enable @@ -2334,8 +3810,6 @@ list of string ## services\.proxy-suite\.proxy\.routing\.proxy\.geoips - - sing-geoip rule-set names to match in this routing rule\. Each name becomes a backend geoip rule-set reference\. @@ -4337,6 +5811,8 @@ string ## services\.proxy-suite\.tgWsProxy\.logBackups + + Number of rotated tg-ws-proxy log files to keep\. Only used when tgWsProxy\.logFile is set\. diff --git a/flake.nix b/flake.nix index e2c5a49..3aea2fb 100644 --- a/flake.nix +++ b/flake.nix @@ -1,5 +1,5 @@ { - description = "NixOS proxy suite - SingBox, XRay, zapret, tg-ws-proxy"; + description = "NixOS proxy suite - SingBox, XRay, AmneziaWG 3.1, zapret, tg-ws-proxy"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; @@ -44,6 +44,8 @@ overlays.default = final: prev: { inherit (import ./pkgs/default.nix { pkgs = final; }) + amneziawg-tools + amneziawg-go mkProxyCtl mkProxySuiteTray mkTgWsProxy @@ -87,6 +89,8 @@ in { inherit (suitePkgs) + amneziawg-tools + amneziawg-go tg-ws-proxy proxy-suite-tray ; diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix new file mode 100644 index 0000000..53ac3e2 --- /dev/null +++ b/modules/proxy-suite/amnezia-wg.nix @@ -0,0 +1,345 @@ +# Native AmneziaWG client profile services. +{ + config, + lib, + pkgs, + cfg, +}: + +let + awgCfg = cfg.amneziaWg; + profiles = awgCfg.profiles; + profileNames = builtins.attrNames profiles; + serviceName = name: "proxy-suite-awg-${name}"; + serviceNames = map serviceName profileNames; + allProfileConflicts = + name: + map (other: "${serviceName other}.service") (builtins.filter (other: other != name) profileNames); + sourceCount = + profile: + builtins.length ( + builtins.filter (value: value != null) [ + profile.configFile + profile.vpnFile + profile.vpn + profile.settings + ] + ); + inlineVpnFile = name: profile: pkgs.writeText "proxy-suite-awg-${name}.vpn" profile.vpn; + sourceKind = + profile: + if profile.configFile != null then + "configFile" + else if profile.vpnFile != null then + "vpnFile" + else if profile.vpn != null then + "vpn" + else + "settings"; + sourcePath = + name: profile: + if profile.configFile != null then + profile.configFile + else if profile.vpnFile != null then + profile.vpnFile + else if profile.vpn != null then + inlineVpnFile name profile + else + null; + manifestFor = + name: profile: + pkgs.writeText "proxy-suite-awg-${name}-manifest.json" ( + builtins.toJSON ( + { + kind = sourceKind profile; + allowConfigHooks = profile.allowConfigHooks; + vpnContainer = profile.vpnContainer; + } + // lib.optionalAttrs (sourcePath name profile != null) { path = sourcePath name profile; } + // lib.optionalAttrs (profile.settings != null) { settings = profile.settings; } + ) + ); + configTool = ../../scripts/amneziawg_config.py; + runtimeDir = name: "/run/${serviceName name}"; + runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf"; + # Keep proxy backend sockets (which already carry proxyMark) out of AWG's + # default-route policy table. This priority sits ahead of the global TUN + # rules while leaving the per-app rules at 8996/8997 untouched. + proxyBypassRulePriority = 8998; + + mkService = + name: profile: + let + manifest = manifestFor name profile; + configPath = runtimeConfig name profile; + prepare = pkgs.writeShellScript "proxy-suite-awg-${name}-prepare" '' + set -euo pipefail + ${pkgs.python3}/bin/python3 ${configTool} \ + --manifest ${lib.escapeShellArg (toString manifest)} \ + --output ${lib.escapeShellArg configPath} + ''; + proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg-${name}-proxy-bypass-up" '' + set -euo pipefail + + add_bypass_rule() { + local family="$1" + while ${pkgs.iproute2}/bin/ip "$family" rule del \ + pref ${toString proxyBypassRulePriority} \ + fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done + if ! ${pkgs.iproute2}/bin/ip "$family" rule add \ + pref ${toString proxyBypassRulePriority} \ + fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; then + # IPv4 is required: without this rule the proxy backend itself is + # captured by AWG's default-route table and HTTP_PROXY clients can + # hang or recurse. IPv6 is best-effort for hosts without IPv6 + # policy-routing support. + if [ "$family" = "-4" ]; then + echo "proxy-suite: unable to install the AWG proxy-backend bypass rule" >&2 + return 1 + fi + fi + } + + add_bypass_rule -4 + add_bypass_rule -6 + ''; + proxyBypassDown = pkgs.writeShellScript "proxy-suite-awg-${name}-proxy-bypass-down" '' + set +e + + while ${pkgs.iproute2}/bin/ip -4 rule del \ + pref ${toString proxyBypassRulePriority} \ + fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done + while ${pkgs.iproute2}/bin/ip -6 rule del \ + pref ${toString proxyBypassRulePriority} \ + fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done + ''; + start = pkgs.writeShellScript "proxy-suite-awg-${name}-start" '' + set -Eeuo pipefail + + cleanup() { + set +e + ${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath} + + # If the userspace control socket died, awg-quick cannot discover its + # fwmark. Remove only routing/firewall state tied to this interface. + for family in -4 -6; do + had_table=0 + for table in $(${pkgs.iproute2}/bin/ip "$family" route show table all 2>/dev/null \ + | ${pkgs.gawk}/bin/awk '$1 == "default" && $2 == "dev" && $3 == "${profile.interfaceName}" { for (i = 1; i <= NF; i++) if ($i == "table") print $(i + 1) }'); do + had_table=1 + while ${pkgs.iproute2}/bin/ip "$family" rule delete table "$table" 2>/dev/null; do :; done + ${pkgs.iproute2}/bin/ip "$family" route flush table "$table" 2>/dev/null || true + done + if (( had_table )); then + ${pkgs.iproute2}/bin/ip "$family" rule delete table main suppress_prefixlength 0 2>/dev/null || true + fi + done + if command -v nft >/dev/null; then + nft list tables 2>/dev/null \ + | ${pkgs.gnugrep}/bin/grep -F " wg-quick-${profile.interfaceName}" \ + | while read -r _ family table; do nft delete table "$family" "$table" 2>/dev/null || true; done + fi + ${config.networking.resolvconf.package}/bin/resolvconf -d "${profile.interfaceName}" -f 2>/dev/null || true + ${pkgs.iproute2}/bin/ip link delete dev ${lib.escapeShellArg profile.interfaceName} 2>/dev/null || true + } + trap cleanup ERR + + ${lib.optionalString (awgCfg.kernelModulePackage != null) '' + ${pkgs.kmod}/bin/modprobe amneziawg 2>/dev/null || true + ''} + + implementation="$(${pkgs.python3}/bin/python3 ${configTool} \ + --transport-implementation ${lib.escapeShellArg configPath})" + # The official 3.1.20260812 kernel module silently drops transport + # packets for RandomTrailers with ranged H1-H3. The bundled userspace + # build carries the receive-path repair until upstream publishes it. + if [[ "$implementation" == userspace ]]; then + WG_QUICK_FORCE_USERSPACE_IMPLEMENTATION=1 \ + WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ + ${awgCfg.toolsPackage}/bin/awg-quick up ${lib.escapeShellArg configPath} + else + WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ + ${awgCfg.toolsPackage}/bin/awg-quick up ${lib.escapeShellArg configPath} + fi + + probe="$(${pkgs.python3}/bin/python3 ${configTool} --probe-address ${lib.escapeShellArg configPath})" + for _ in $(${pkgs.coreutils}/bin/seq 1 15); do + ${pkgs.iputils}/bin/ping -n -c 1 -W 1 "$probe" >/dev/null 2>&1 || true + if ${awgCfg.toolsPackage}/bin/awg show ${lib.escapeShellArg profile.interfaceName} latest-handshakes 2>/dev/null \ + | ${pkgs.gawk}/bin/awk '$2 + 0 > 0 { found = 1 } END { exit !found }'; then + trap - ERR + exit 0 + fi + done + + echo "proxy-suite: AmneziaWG profile '${name}' did not complete a handshake; rolling back routes" >&2 + false + ''; + stop = pkgs.writeShellScript "proxy-suite-awg-${name}-stop" '' + set -euo pipefail + exec ${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath} + ''; + in + { + description = "proxy-suite AmneziaWG client profile ${name}"; + # When the normal proxy stack is enabled, bring its local HTTP/SOCKS + # listener up before installing AWG's default-route policy. This keeps + # applications using HTTP_PROXY/HTTPS_PROXY (for example Codex) from + # racing the proxy backend during boot or an explicit `awg on`. + after = [ + "network-online.target" + "zapret-discord-youtube.service" + ] + ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; + wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; + wantedBy = lib.optionals profile.autostart [ "multi-user.target" ]; + conflicts = allProfileConflicts name ++ [ + "proxy-suite-tun.service" + "proxy-suite-tproxy.service" + "zapret-discord-youtube.service" + "proxy-suite-per-app-zapret.service" + "proxy-suite-zapret-vm-exempt.service" + ]; + path = [ + awgCfg.toolsPackage + awgCfg.userspacePackage + pkgs.coreutils + pkgs.gnugrep + pkgs.iproute2 + pkgs.iputils + pkgs.kmod + config.networking.firewall.package + config.networking.resolvconf.package + ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + RuntimeDirectory = serviceName name; + RuntimeDirectoryMode = "0700"; + UMask = "0077"; + NoNewPrivileges = true; + LockPersonality = true; + ProtectClock = true; + ProtectControlGroups = true; + ProtectHostname = true; + ProtectKernelLogs = true; + RestrictRealtime = true; + RestrictSUIDSGID = true; + ExecStartPre = [ prepare ] ++ lib.optionals cfg.proxy.enable [ proxyBypassUp ]; + ExecStart = start; + ExecStop = stop; + } + // lib.optionalAttrs cfg.proxy.enable { + ExecStopPost = proxyBypassDown; + }; + }; + + profileAssertions = lib.concatMap ( + name: + let + profile = profiles.${name}; + settings = profile.settings; + obfuscation = if settings == null then null else settings.obfuscation; + in + [ + { + assertion = builtins.match "^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$" name != null; + message = "proxy-suite: AmneziaWG profile '${name}' must be a safe 1-32 character identifier"; + } + { + assertion = sourceCount profile == 1; + message = "proxy-suite: AmneziaWG profile '${name}' must set exactly one of configFile, vpnFile, vpn, or settings"; + } + { + assertion = profile.vpnContainer == null || profile.vpn != null || profile.vpnFile != null; + message = "proxy-suite: AmneziaWG profile '${name}': vpnContainer requires vpn or vpnFile"; + } + { + assertion = settings == null || settings.addresses != [ ]; + message = "proxy-suite: AmneziaWG profile '${name}': declarative settings require at least one address"; + } + { + assertion = settings == null || settings.peers != [ ]; + message = "proxy-suite: AmneziaWG profile '${name}': declarative settings require at least one peer"; + } + { + assertion = + settings == null || ((settings.privateKey != null) != (settings.privateKeyFile != null)); + message = "proxy-suite: AmneziaWG profile '${name}': set exactly one of settings.privateKey or settings.privateKeyFile"; + } + { + assertion = + obfuscation == null + || ((obfuscation.headerProtectionKey != null) != (obfuscation.headerProtectionKeyFile != null)) + || (obfuscation.headerProtectionKey == null && obfuscation.headerProtectionKeyFile == null); + message = "proxy-suite: AmneziaWG profile '${name}': set at most one header-protection key source"; + } + ] + ++ lib.optionals (settings != null) ( + lib.imap0 (index: peer: { + assertion = peer.presharedKey == null || peer.presharedKeyFile == null; + message = "proxy-suite: AmneziaWG profile '${name}' peer ${toString index}: set at most one preshared key source"; + }) settings.peers + ) + ) profileNames; + + interfaceNames = map (name: profiles.${name}.interfaceName) profileNames; + autostartProfiles = builtins.filter (name: profiles.${name}.autostart) profileNames; + globalAutostartCount = + builtins.length autostartProfiles + + (if cfg.proxy.tun.autostart then 1 else 0) + + (if cfg.proxy.tproxy.autostart then 1 else 0); +in +{ + environment.systemPackages = [ + awgCfg.toolsPackage + awgCfg.userspacePackage + ]; + + boot.extraModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [ + awgCfg.kernelModulePackage + ]; + + systemd.services = lib.mkMerge [ + (lib.mapAttrs' ( + name: profile: lib.nameValuePair (serviceName name) (mkService name profile) + ) profiles) + (lib.mkIf cfg.proxy.tun.enable { + proxy-suite-tun.conflicts = map (name: "${name}.service") serviceNames; + }) + (lib.mkIf cfg.proxy.tproxy.enable { + proxy-suite-tproxy.conflicts = map (name: "${name}.service") serviceNames; + }) + ]; + + assertions = profileAssertions ++ [ + { + assertion = profiles != { }; + message = "proxy-suite: amneziaWg.enable requires at least one profile"; + } + { + assertion = builtins.length interfaceNames == builtins.length (lib.unique interfaceNames); + message = "proxy-suite: AmneziaWG profile interface names must be unique"; + } + { + assertion = builtins.length autostartProfiles <= 1; + message = "proxy-suite: at most one AmneziaWG profile may autostart"; + } + { + assertion = globalAutostartCount <= 1; + message = "proxy-suite: at most one AmneziaWG, TUN, or TProxy global mode may autostart"; + } + { + assertion = + !cfg.proxy.tun.enable + || builtins.all (interface: interface != cfg.proxy.tun.interface) interfaceNames; + message = "proxy-suite: AmneziaWG interfaces must differ from proxy.tun.interface"; + } + { + assertion = + !cfg.proxy.tun.perApp.enable + || builtins.all (interface: interface != cfg.proxy.tun.perApp.interface) interfaceNames; + message = "proxy-suite: AmneziaWG interfaces must differ from proxy.tun.perApp.interface"; + } + ]; +} diff --git a/modules/proxy-suite/default.nix b/modules/proxy-suite/default.nix index b38147d..33d15d4 100644 --- a/modules/proxy-suite/default.nix +++ b/modules/proxy-suite/default.nix @@ -47,7 +47,12 @@ in packages cfg ; - inherit (configs) tproxyFile tunFile perAppTunFile routeModeRulesFile; + inherit (configs) + tproxyFile + tunFile + perAppTunFile + routeModeRulesFile + ; inherit (nftr) nftablesRulesFile perAppTproxyRulesFile @@ -81,6 +86,17 @@ in } )) + (lib.mkIf cfg.amneziaWg.enable ( + import ./amnezia-wg.nix { + inherit + config + lib + pkgs + cfg + ; + } + )) + (lib.mkIf cfg.tray.enable ( import ./tray.nix { inherit diff --git a/modules/proxy-suite/options/amnezia-wg.nix b/modules/proxy-suite/options/amnezia-wg.nix new file mode 100644 index 0000000..dbb6813 --- /dev/null +++ b/modules/proxy-suite/options/amnezia-wg.nix @@ -0,0 +1,45 @@ +{ + config, + lib, + pkgs, + ... +}: + +let + inherit (lib) + mkEnableOption + mkOption + types + ; + awgTypes = import ./types/amnezia-wg.nix { inherit lib; }; + awgPackages = import ../../../pkgs/amneziawg.nix { inherit pkgs; }; +in +{ + options.services.proxy-suite.amneziaWg = { + enable = mkEnableOption "native AmneziaWG client profiles"; + + toolsPackage = mkOption { + type = types.package; + default = awgPackages.tools; + description = "AWG 3.1 package providing awg and awg-quick."; + }; + + userspacePackage = mkOption { + type = types.package; + default = awgPackages.userspace; + description = "AWG 3.1 userspace implementation used when the kernel interface is unavailable."; + }; + + kernelModulePackage = mkOption { + type = types.nullOr types.package; + default = awgPackages.kernelModule config.boot.kernelPackages; + description = "AWG 3.1 kernel module package. Set null to use userspace-only fallback."; + }; + + profiles = mkOption { + type = types.attrsOf awgTypes.profileType; + default = { }; + description = "Named AmneziaWG client profiles. Only one global profile can be active."; + }; + }; +} diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index 5a045ff..3df334a 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -3,6 +3,7 @@ { imports = [ ./other.nix + ./amnezia-wg.nix ./legacy-sing-box.nix ./sing-box.nix ./sing-box-outbounds.nix diff --git a/modules/proxy-suite/options/other.nix b/modules/proxy-suite/options/other.nix index 782c352..96a5a0c 100644 --- a/modules/proxy-suite/options/other.nix +++ b/modules/proxy-suite/options/other.nix @@ -70,7 +70,7 @@ let in { options.services.proxy-suite = { - enable = lib.mkEnableOption "proxy suite (proxy backend + zapret + tg-ws-proxy)"; + enable = lib.mkEnableOption "proxy suite (proxy backend + AmneziaWG + zapret + tg-ws-proxy)"; } // userControlOptions // trayOptions diff --git a/modules/proxy-suite/options/types/amnezia-wg.nix b/modules/proxy-suite/options/types/amnezia-wg.nix new file mode 100644 index 0000000..cbdf7c2 --- /dev/null +++ b/modules/proxy-suite/options/types/amnezia-wg.nix @@ -0,0 +1,299 @@ +# AmneziaWG profile option types. +{ lib }: + +let + inherit (lib) mkOption types; + optionalString = types.nullOr types.str; + optionalUnsigned = types.nullOr types.ints.unsigned; + rangeValue = types.oneOf [ + types.ints.unsigned + (types.strMatching "^([0-9]+|[0-9]+-[0-9]+|\\(off\\))$") + ]; + optionalRange = types.nullOr rangeValue; + + peerType = types.submodule { + options = { + publicKey = mkOption { + type = types.strMatching "[^[:space:]]+"; + description = "AmneziaWG peer public key."; + }; + presharedKey = mkOption { + type = optionalString; + default = null; + description = "Inline peer preshared key. Prefer presharedKeyFile for secrets."; + }; + presharedKeyFile = mkOption { + type = optionalString; + default = null; + description = "Runtime path containing the peer preshared key."; + }; + allowedIPs = mkOption { + type = types.listOf types.str; + description = "IP prefixes routed to and accepted from this peer."; + example = [ + "0.0.0.0/0" + "::/0" + ]; + }; + endpoint = mkOption { + type = optionalString; + default = null; + example = "vpn.example.com:51820"; + description = "Optional peer endpoint in host:port form."; + }; + persistentKeepalive = mkOption { + type = optionalRange; + default = null; + description = "Persistent keepalive seconds, optionally expressed as an AWG 3 range."; + }; + advancedSecurity = mkOption { + type = types.nullOr types.bool; + default = null; + description = "Optional AWG peer AdvancedSecurity setting."; + }; + }; + }; + + obfuscationType = types.submodule { + options = { + jc = mkOption { + type = optionalUnsigned; + default = null; + description = "Junk packet count (Jc)."; + }; + jmin = mkOption { + type = optionalUnsigned; + default = null; + description = "Minimum junk packet size (Jmin)."; + }; + jmax = mkOption { + type = optionalUnsigned; + default = null; + description = "Maximum junk packet size (Jmax)."; + }; + s1 = mkOption { + type = optionalUnsigned; + default = null; + description = "Handshake-init padding (S1)."; + }; + s2 = mkOption { + type = optionalUnsigned; + default = null; + description = "Handshake-response padding (S2)."; + }; + s3 = mkOption { + type = optionalUnsigned; + default = null; + description = "Cookie-reply padding (S3)."; + }; + s4 = mkOption { + type = optionalUnsigned; + default = null; + description = "Transport-message padding (S4)."; + }; + h1 = mkOption { + type = optionalRange; + default = null; + description = "Handshake-init header or range (H1)."; + }; + h2 = mkOption { + type = optionalRange; + default = null; + description = "Handshake-response header or range (H2)."; + }; + h3 = mkOption { + type = optionalRange; + default = null; + description = "Cookie-reply header or range (H3)."; + }; + h4 = mkOption { + type = optionalRange; + default = null; + description = "Transport-message header or range (H4)."; + }; + i1 = mkOption { + type = optionalString; + default = null; + description = "First custom signature packet (I1)."; + }; + i2 = mkOption { + type = optionalString; + default = null; + description = "Second custom signature packet (I2)."; + }; + i3 = mkOption { + type = optionalString; + default = null; + description = "Third custom signature packet (I3)."; + }; + i4 = mkOption { + type = optionalString; + default = null; + description = "Fourth custom signature packet (I4)."; + }; + i5 = mkOption { + type = optionalString; + default = null; + description = "Fifth custom signature packet (I5)."; + }; + headerProtectionKey = mkOption { + type = optionalString; + default = null; + description = "Inline AWG 3 header-protection key. Prefer headerProtectionKeyFile."; + }; + headerProtectionKeyFile = mkOption { + type = optionalString; + default = null; + description = "Runtime path containing the AWG 3 header-protection key."; + }; + contentPaddingAddition = mkOption { + type = optionalRange; + default = null; + description = "AWG 3 content-padding addition or range."; + }; + rekeyAfterTime = mkOption { + type = optionalRange; + default = null; + description = "AWG 3 rekey interval or range."; + }; + rekeyTimeout = mkOption { + type = optionalRange; + default = null; + description = "AWG 3 rekey timeout or range."; + }; + rejectAfterTime = mkOption { + type = optionalRange; + default = null; + description = "AWG 3 reject-after interval or range."; + }; + keepaliveTimeout = mkOption { + type = optionalRange; + default = null; + description = "AWG 3 keepalive timeout or range."; + }; + maxHandshakeAttempts = mkOption { + type = optionalRange; + default = null; + description = "AWG 3 maximum handshake attempts or range."; + }; + randomTrailers = mkOption { + type = types.nullOr types.bool; + default = null; + description = "AWG 3 random transport trailers (RandomTrailers)."; + }; + disableCookies = mkOption { + type = types.nullOr types.bool; + default = null; + description = "AWG 3 cookie suppression (DisableCookies)."; + }; + }; + }; + + settingsType = types.submodule { + options = { + addresses = mkOption { + type = types.listOf types.str; + default = [ ]; + description = "IP prefixes assigned to the AWG interface."; + example = [ "10.8.0.2/32" ]; + }; + dns = mkOption { + type = types.listOf types.str; + default = [ ]; + description = "DNS servers installed while this profile is active."; + }; + privateKey = mkOption { + type = optionalString; + default = null; + description = "Inline client private key. Prefer privateKeyFile."; + }; + privateKeyFile = mkOption { + type = optionalString; + default = null; + description = "Runtime path containing the client private key."; + }; + listenPort = mkOption { + type = types.nullOr types.port; + default = null; + description = "Optional local UDP listen port."; + }; + mtu = mkOption { + type = optionalUnsigned; + default = null; + description = "Optional interface MTU."; + }; + table = mkOption { + type = optionalString; + default = null; + description = "wg-quick routing table name/number, auto, or off."; + }; + obfuscation = mkOption { + type = obfuscationType; + default = { }; + description = "AmneziaWG 1.x through 3.x obfuscation parameters."; + }; + peers = mkOption { + type = types.listOf peerType; + default = [ ]; + description = "AmneziaWG peers."; + }; + }; + }; + + profileType = types.submodule ( + { name, ... }: + { + options = { + interfaceName = mkOption { + type = types.strMatching "^[A-Za-z0-9_.-]{1,15}$"; + default = "awg-${name}"; + description = "Linux interface name. It must fit Linux's 15-character limit."; + }; + autostart = mkOption { + type = types.bool; + default = false; + description = "Whether to start this profile at boot. At most one profile may autostart."; + }; + allowConfigHooks = mkOption { + type = types.bool; + default = false; + description = "Allow trusted imported configs to execute wg-quick hooks or use SaveConfig."; + }; + vpnContainer = mkOption { + type = optionalString; + default = null; + description = "AWG container/protocol identifier to select when a vpn:// bundle is ambiguous."; + }; + configFile = mkOption { + type = optionalString; + default = null; + description = "Runtime path to an AmneziaWG .conf file."; + }; + vpnFile = mkOption { + type = optionalString; + default = null; + description = "Runtime path containing a self-contained vpn:// export."; + }; + vpn = mkOption { + type = optionalString; + default = null; + description = "Inline self-contained vpn:// export. This value is stored in the Nix store."; + }; + settings = mkOption { + type = types.nullOr settingsType; + default = null; + description = "Typed declarative AmneziaWG client configuration."; + }; + }; + } + ); +in +{ + inherit + profileType + settingsType + peerType + obfuscationType + rangeValue + ; +} diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 33ae444..3a887e4 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -55,6 +55,9 @@ let headBin = "${pkgs.coreutils}/bin/head"; seqBin = "${pkgs.coreutils}/bin/seq"; findBin = "${pkgs.findutils}/bin/find"; + amneziaWgProfileNamesFile = pkgs.writeText "proxy-suite-awg-profiles.json" ( + builtins.toJSON (builtins.attrNames cfg.amneziaWg.profiles) + ); proxySuiteScriptsDir = ../../../scripts; parserScriptsPythonPath = proxySuiteScriptsDir; @@ -138,6 +141,7 @@ let ; inherit (scripts) subscriptionTagsFile subscriptionCacheDir; inherit (scripts) routeModeStateFile; + inherit amneziaWgProfileNamesFile; inherit (perAppRouting) perAppRoutingProfilesFile proxychainsConfigFile @@ -172,5 +176,6 @@ in scripts perAppRouting control + amneziaWgProfileNamesFile ; } diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 570f2ef..059352c 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -14,6 +14,7 @@ proxychainsConfigFile, proxychainsQuietArg, routeModeStateFile, + amneziaWgProfileNamesFile, }: { proxyCtl = packages.mkProxyCtl { @@ -26,6 +27,7 @@ proxychainsConfigFile proxychainsQuietArg routeModeStateFile + amneziaWgProfileNamesFile ; defaultRouteMode = if proxyCfg.proxyByDefault then "blacklist" else "whitelist"; perAppRoutingEnabled = if perAppRoutingCfg.enable then "1" else "0"; diff --git a/modules/proxy-suite/zapret.nix b/modules/proxy-suite/zapret.nix index b98cc80..6454429 100644 --- a/modules/proxy-suite/zapret.nix +++ b/modules/proxy-suite/zapret.nix @@ -14,6 +14,9 @@ let zapretCfg = cfg.zapret; perAppZapretCfg = zapretCfg.perApp; + awgServiceNames = map (name: "proxy-suite-awg-${name}.service") ( + builtins.attrNames cfg.amneziaWg.profiles + ); zapretPackages = import ./zapret/packages.nix { inherit lib @@ -84,6 +87,7 @@ in description = "zapret DPI bypass"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; + conflicts = awgServiceNames; wantedBy = [ "multi-user.target" ]; preStart = zapretCommonPreStart globalZapretPackage; runtimeDirectory = "proxy-suite-zapret"; @@ -102,7 +106,8 @@ in conflicts = [ "proxy-suite-tproxy.service" "proxy-suite-tun.service" - ]; + ] + ++ awgServiceNames; preStart = zapretCommonPreStart perAppZapretPackage; runtimeDirectory = "proxy-suite-per-app-zapret"; execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start"; @@ -118,6 +123,7 @@ in description = "Exempt CIDRs from zapret NFQUEUE"; after = [ "zapret-discord-youtube.service" ]; wants = [ "zapret-discord-youtube.service" ]; + conflicts = awgServiceNames; wantedBy = [ "multi-user.target" ]; execStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart; execStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop; diff --git a/nix/checks.nix b/nix/checks.nix index f903b5a..3752ebe 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -33,10 +33,16 @@ let controlModuleSource = builtins.readFile ../modules/proxy-suite/service/control.nix; }; moduleSuiteChecks = import ./checks/module-suite.nix { inherit pkgs checkLib; }; + amneziaWgRuntime = import ./checks/amnezia-wg-runtime.nix { + inherit pkgs nixpkgs proxySuiteModule; + }; in moduleSuiteChecks // { proxy-suite-tray-build = suitePkgs.proxy-suite-tray; } +// pkgs.lib.optionalAttrs (system == "x86_64-linux") { + amneziawg-runtime = amneziaWgRuntime; +} // parserChecks // repoChecks diff --git a/nix/checks/amnezia-wg-runtime.nix b/nix/checks/amnezia-wg-runtime.nix new file mode 100644 index 0000000..53083c0 --- /dev/null +++ b/nix/checks/amnezia-wg-runtime.nix @@ -0,0 +1,133 @@ +{ + pkgs, + nixpkgs, + proxySuiteModule, +}: + +let + keys = import "${nixpkgs}/nixos/tests/wireguard/snakeoil-keys.nix"; + awgPackages = import ../../pkgs/amneziawg.nix { inherit pkgs; }; + obfuscation = { + jc = 5; + jmin = 10; + jmax = 42; + s1 = 60; + s2 = 90; + }; + network = address: { + networking.useDHCP = false; + networking.interfaces.eth1.ipv4.addresses = [ + { + inherit address; + prefixLength = 24; + } + ]; + }; + client = + address: userspaceOnly: + { + imports = [ proxySuiteModule ]; + services.proxy-suite = { + enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = + if userspaceOnly then null else awgPackages.kernelModule pkgs.linuxPackages; + profiles.test = { + interfaceName = "awg-test"; + settings = { + addresses = [ "10.23.42.2/32" ]; + privateKey = keys.peer1.privateKey; + inherit obfuscation; + peers = [ + { + publicKey = keys.peer0.publicKey; + endpoint = "192.168.0.1:23542"; + allowedIPs = [ "10.23.42.1/32" ]; + persistentKeepalive = 5; + } + ]; + }; + }; + profiles.broken = { + interfaceName = "awg-broken"; + settings = { + addresses = [ "10.99.42.2/32" ]; + privateKey = keys.peer1.privateKey; + inherit obfuscation; + peers = [ + { + publicKey = keys.peer0.publicKey; + endpoint = "192.168.0.254:23542"; + allowedIPs = [ "10.99.42.1/32" ]; + } + ]; + }; + }; + }; + }; + } + // network address; +in +pkgs.testers.runNixOSTest { + name = "proxy-suite-amneziawg-runtime"; + + nodes = { + server = + { ... }: + { + imports = [ (network "192.168.0.1") ]; + networking.firewall.allowedUDPPorts = [ 23542 ]; + networking.wg-quick.interfaces.awg-server = { + type = "amneziawg"; + address = [ "10.23.42.1/32" ]; + listenPort = 23542; + privateKey = keys.peer0.privateKey; + extraOptions = { + Jc = obfuscation.jc; + Jmin = obfuscation.jmin; + Jmax = obfuscation.jmax; + S1 = obfuscation.s1; + S2 = obfuscation.s2; + }; + peers = [ + { + publicKey = keys.peer1.publicKey; + allowedIPs = [ "10.23.42.2/32" ]; + } + ]; + }; + }; + + kernel = client "192.168.0.2" false; + userspace = client "192.168.0.3" true; + }; + + testScript = '' + start_all() + server.wait_for_unit("wg-quick-awg-server.service") + + with subtest("packaged kernel module"): + kernel.succeed("systemctl start proxy-suite-awg-test.service") + kernel.succeed("ip -d link show awg-test | grep -q amneziawg") + kernel.succeed("ping -c 5 10.23.42.1") + kernel.succeed("test $(awg show awg-test latest-handshakes | awk '{print $2}') -gt 0") + kernel.succeed("systemctl stop proxy-suite-awg-test.service") + kernel.fail("ip link show awg-test") + + with subtest("automatic userspace fallback"): + userspace.fail("modprobe -n amneziawg") + userspace.succeed("systemctl start proxy-suite-awg-test.service") + userspace.succeed("test -r /sys/class/net/awg-test/tun_flags") + userspace.succeed("ping -c 5 10.23.42.1") + userspace.succeed("test $(awg show awg-test latest-handshakes | awk '{print $2}') -gt 0") + userspace.succeed("systemctl stop proxy-suite-awg-test.service") + userspace.fail("ip link show awg-test") + + with subtest("failed handshake rolls back userspace routing"): + userspace.fail("systemctl start proxy-suite-awg-broken.service") + userspace.fail("ip link show awg-broken") + userspace.fail("ip route show table all | grep -F awg-broken") + userspace.fail("ip -6 route show table all | grep -F awg-broken") + ''; +} diff --git a/nix/checks/amnezia-wg.nix b/nix/checks/amnezia-wg.nix new file mode 100644 index 0000000..22253bb --- /dev/null +++ b/nix/checks/amnezia-wg.nix @@ -0,0 +1,331 @@ +{ + pkgs, + evalProxySuite, + mkBadProxySuiteFixture, + mkFailingAssertions, + mkProxyCtlDerived, +}: + +let + generated = import ./read-generated.nix; + defaultPackages = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + amneziaWg = { + enable = true; + profiles.home.configFile = "/run/secrets/awg.conf"; + }; + }; + } + ]; + awgOnly = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles = { + home = { + autostart = true; + settings = { + addresses = [ "10.8.0.2/32" ]; + privateKeyFile = "/run/secrets/awg-private"; + obfuscation = { + s1 = 12; + s2 = 12; + s3 = 12; + s4 = 12; + h1 = "100-200"; + headerProtectionKeyFile = "/run/secrets/awg-header"; + rekeyAfterTime = "120-180"; + }; + peers = [ + { + publicKey = "public"; + presharedKeyFile = "/run/secrets/awg-psk"; + allowedIPs = [ + "0.0.0.0/0" + "::/0" + ]; + endpoint = "vpn.example.com:51820"; + persistentKeepalive = "20-30"; + advancedSecurity = true; + } + ]; + }; + }; + work = { + configFile = "/run/secrets/work-awg.conf"; + }; + }; + }; + }; + } + ]; + homeService = awgOnly.config.systemd.services.proxy-suite-awg-home; + workService = awgOnly.config.systemd.services.proxy-suite-awg-work; + ctl = mkProxyCtlDerived awgOnly; + + sourceFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles = { + conf.configFile = "/run/secrets/client.conf"; + file.vpnFile = "/run/secrets/client.vpn"; + inline.vpn = "vpn://ZW1iZWRkZWQ"; + nix.settings = { + addresses = [ "10.0.0.2/32" ]; + privateKey = "inline-private"; + peers = [ + { + publicKey = "public"; + allowedIPs = [ "10.0.0.1/32" ]; + } + ]; + }; + }; + }; + }; + } + ]; + + fakeTools = pkgs.writeShellScriptBin "awg-quick" "exit 0"; + fakeUserspace = pkgs.writeShellScriptBin "amneziawg-go" "exit 0"; + fakeKernelModule = pkgs.runCommand "fake-amneziawg-module" { } '' + mkdir -p "$out/lib/modules" + ''; + overrideFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + amneziaWg = { + enable = true; + toolsPackage = fakeTools; + userspacePackage = fakeUserspace; + kernelModulePackage = fakeKernelModule; + profiles.home.configFile = "/run/secrets/client.conf"; + }; + }; + } + ]; + + withGlobalTun = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + tun.enable = true; + tproxy.enable = true; + }; + zapret = { + enable = true; + perApp.enable = true; + }; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles.home.configFile = "/run/secrets/awg.conf"; + }; + }; + } + ]; + withGlobalAwgService = withGlobalTun.config.systemd.services.proxy-suite-awg-home; + withGlobalAwgStartPre = withGlobalAwgService.serviceConfig.ExecStartPre; + withGlobalAwgBypassUp = generated.readDerivation (builtins.elemAt withGlobalAwgStartPre 1); + withGlobalAwgBypassDown = generated.readDerivation withGlobalAwgService.serviceConfig.ExecStopPost; +in +{ + assertions = [ + ( + assert !awgOnly.config.services.proxy-suite.proxy.enable; + assert homeService.serviceConfig.RuntimeDirectoryMode == "0700"; + assert homeService.serviceConfig.UMask == "0077"; + assert builtins.elem "multi-user.target" homeService.wantedBy; + assert builtins.elem "proxy-suite-awg-work.service" homeService.conflicts; + assert builtins.elem "proxy-suite-tun.service" homeService.conflicts; + assert builtins.elem "proxy-suite-tproxy.service" homeService.conflicts; + assert builtins.elem "zapret-discord-youtube.service" homeService.conflicts; + assert builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts; + assert workService.wantedBy == [ ]; + assert homeService.serviceConfig.NoNewPrivileges; + assert builtins.length homeService.serviceConfig.ExecStartPre == 1; + assert !(homeService.serviceConfig ? ExecStopPost); + true + ) + ( + assert builtins.elem awgOnly.config.services.proxy-suite.amneziaWg.toolsPackage + awgOnly.config.environment.systemPackages; + assert builtins.elem awgOnly.config.services.proxy-suite.amneziaWg.userspacePackage + awgOnly.config.environment.systemPackages; + assert awgOnly.config.services.proxy-suite.amneziaWg.toolsPackage.version == "3.1.20260812"; + assert awgOnly.config.services.proxy-suite.amneziaWg.userspacePackage.version == "3.1.20260828"; + assert pkgs.lib.hasInfix "cmd_awg" ctl.script; + assert + ctl.awgProfiles == [ + "home" + "work" + ]; + true + ) + ( + assert defaultPackages.config.services.proxy-suite.amneziaWg.toolsPackage.version == "3.1.20260812"; + assert + defaultPackages.config.services.proxy-suite.amneziaWg.userspacePackage.version == "3.1.20260828"; + assert + defaultPackages.config.services.proxy-suite.amneziaWg.kernelModulePackage.version == "3.1.20260812"; + true + ) + ( + assert + sourceFixture.config.services.proxy-suite.amneziaWg.profiles.conf.configFile + == "/run/secrets/client.conf"; + assert + sourceFixture.config.services.proxy-suite.amneziaWg.profiles.file.vpnFile + == "/run/secrets/client.vpn"; + assert + sourceFixture.config.services.proxy-suite.amneziaWg.profiles.inline.vpn == "vpn://ZW1iZWRkZWQ"; + assert + sourceFixture.config.services.proxy-suite.amneziaWg.profiles.nix.settings.privateKey + == "inline-private"; + assert builtins.elem fakeTools overrideFixture.config.environment.systemPackages; + assert builtins.elem fakeUserspace overrideFixture.config.environment.systemPackages; + assert builtins.elem fakeKernelModule overrideFixture.config.boot.extraModulePackages; + assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" + awgOnly.config.security.polkit.extraConfig; + true + ) + ( + assert builtins.elem "proxy-suite-awg-home.service" + withGlobalTun.config.systemd.services.proxy-suite-tun.conflicts; + assert builtins.elem "proxy-suite-awg-home.service" + withGlobalTun.config.systemd.services.proxy-suite-tproxy.conflicts; + assert builtins.elem "proxy-suite-awg-home.service" + withGlobalTun.config.systemd.services.zapret-discord-youtube.conflicts; + assert builtins.elem "proxy-suite-awg-home.service" + withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts; + assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.after; + assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.wants; + assert builtins.length withGlobalAwgStartPre == 2; + assert pkgs.lib.hasInfix "rule add" withGlobalAwgBypassUp; + assert pkgs.lib.hasInfix "pref 8998" withGlobalAwgBypassUp; + assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassUp; + assert pkgs.lib.hasInfix "unable to install the AWG proxy-backend bypass rule" + withGlobalAwgBypassUp; + assert pkgs.lib.hasInfix "rule del" withGlobalAwgBypassDown; + assert pkgs.lib.hasInfix "pref 8998" withGlobalAwgBypassDown; + assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassDown; + true + ) + ] + ++ mkFailingAssertions mkBadProxySuiteFixture [ + { + enable = true; + amneziaWg.enable = true; + } + { + enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles.home = { + configFile = "/run/a.conf"; + vpnFile = "/run/a.vpn"; + }; + }; + } + { + enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles = { + one = { + autostart = true; + configFile = "/run/one.conf"; + }; + two = { + autostart = true; + configFile = "/run/two.conf"; + }; + }; + }; + } + { + enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles = { + one = { + interfaceName = "awg-shared"; + configFile = "/run/one.conf"; + }; + two = { + interfaceName = "awg-shared"; + configFile = "/run/two.conf"; + }; + }; + }; + } + { + enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles.home.settings = { + addresses = [ "10.8.0.2/32" ]; + peers = [ + { + publicKey = "public"; + allowedIPs = [ "0.0.0.0/0" ]; + } + ]; + }; + }; + } + { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + tun = { + enable = true; + autostart = true; + }; + }; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles.home = { + autostart = true; + configFile = "/run/home.conf"; + }; + }; + } + ]; +} diff --git a/nix/checks/lib.nix b/nix/checks/lib.nix index b6cc777..05d60ac 100644 --- a/nix/checks/lib.nix +++ b/nix/checks/lib.nix @@ -213,6 +213,7 @@ let profiles = builtins.fromJSON (generated.readDerivation metadata.perAppRoutingProfilesFile); subscriptionTags = builtins.fromJSON (generated.readDerivation metadata.subscriptionTagsFile); inherit (metadata) proxychainsConfigFile; + awgProfiles = builtins.fromJSON (generated.readDerivation metadata.amneziaWgProfileNamesFile); }; in { diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 3f0b157..881c340 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -126,6 +126,16 @@ let inherit mkBadProxySuiteFixture mkFailingAssertions; }; + amneziaWgChecks = import ./amnezia-wg.nix { + inherit + pkgs + evalProxySuite + mkBadProxySuiteFixture + mkFailingAssertions + mkProxyCtlDerived + ; + }; + globalProxyModeChecks = import ./global-proxy-modes.nix { inherit pkgs @@ -196,6 +206,7 @@ let ++ tgWsProxyChecks.assertions ++ xrayBackendChecks.assertions ++ outboundValidationChecks.assertions + ++ amneziaWgChecks.assertions ++ zapretChecks.assertions ++ globalProxyModeChecks.assertions ++ trayChecks.assertions diff --git a/nix/checks/parsers.nix b/nix/checks/parsers.nix index 97d6382..171b0c8 100644 --- a/nix/checks/parsers.nix +++ b/nix/checks/parsers.nix @@ -18,4 +18,13 @@ python ${../../scripts/test-fetch-subscription.py} touch "$out" ''; + + amneziawg-config-parser = + pkgs.runCommand "amneziawg-config-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; } + '' + export PYTHONDONTWRITEBYTECODE=1 + export PYTHONPATH=${../../scripts}:$PYTHONPATH + python ${../../scripts/test-amneziawg-config.py} + touch "$out" + ''; } diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index b7d6b43..776f035 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -87,6 +87,68 @@ touch "$out" ''; + proxy-ctl-amneziawg = + pkgs.runCommand "proxy-suite-proxy-ctl-amneziawg-check" + { + nativeBuildInputs = [ + pkgs.bash + pkgs.coreutils + pkgs.gnugrep + pkgs.jq + ]; + } + '' + proxy_ctl="$TMPDIR/proxy-ctl" + cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" + chmod +x "$proxy_ctl" + + mkdir -p bin + cat > bin/systemctl <<'SH' + #!${pkgs.bash}/bin/bash + case "$1" in + cat) exit 0 ;; + is-active) + if [ "''${3:-''${2:-}}" = "proxy-suite-awg-home" ] || [ "''${2:-}" = "proxy-suite-awg-home" ]; then + if [ "''${2:-}" != "--quiet" ]; then + echo active + fi + exit 0 + fi + if [ "''${2:-}" != "--quiet" ]; then + echo inactive + fi + exit 3 + ;; + start|stop|restart) + printf '%s %s\n' "$1" "$2" >> "$SYSTEMCTL_LOG" + ;; + esac + SH + chmod +x bin/systemctl + + printf '%s\n' '["home","work"]' > awg-profiles.json + export PATH="$PWD/bin:$PATH" + export SYSTEMCTL_LOG="$PWD/systemctl.log" + export AWG_PROFILES_FILE="$PWD/awg-profiles.json" + + bash "$proxy_ctl" awg list > list-output + grep -q 'home.*active' list-output + grep -q 'work.*inactive' list-output + test "$(bash "$proxy_ctl" awg status)" = home + bash "$proxy_ctl" awg on work + bash "$proxy_ctl" awg off home + bash "$proxy_ctl" awg restart home + grep -q '^start proxy-suite-awg-work$' "$SYSTEMCTL_LOG" + grep -q '^stop proxy-suite-awg-home$' "$SYSTEMCTL_LOG" + grep -q '^restart proxy-suite-awg-home$' "$SYSTEMCTL_LOG" + + if bash "$proxy_ctl" awg on missing 2> error-output; then + exit 1 + fi + grep -q 'Unknown AmneziaWG profile' error-output + touch "$out" + ''; + readme-doc-source = builtins.seq ( assert !(pkgs.lib.hasInfix "environment.systemPackages" readmeDocSource); assert !(pkgs.lib.hasInfix "packageByPattern" readmeDocSource); diff --git a/pkgs/amneziawg.nix b/pkgs/amneziawg.nix new file mode 100644 index 0000000..d871d8b --- /dev/null +++ b/pkgs/amneziawg.nix @@ -0,0 +1,50 @@ +{ pkgs }: + +let + # Tools and the kernel module currently publish 3.1.20260812, while the + # userspace implementation has follow-up 3.1 fixes through 20260828. + # nixpkgs itself still tracks AWG 3.0. + version = "3.1.20260812"; + userspaceVersion = "3.1.20260828"; + tools = pkgs.amneziawg-tools.overrideAttrs (old: { + inherit version; + src = pkgs.fetchFromGitHub { + owner = "amnezia-vpn"; + repo = "amneziawg-tools"; + tag = "v${version}"; + hash = "sha256-6GEb41ERhR0Hg3RbSyIHdXPSKaxugoFCmFS5S0UiZso="; + }; + patches = (old.patches or [ ]) ++ [ ./patches/amneziawg-tools-force-userspace.patch ]; + }); + userspace = pkgs.amneziawg-go.overrideAttrs (_: { + version = userspaceVersion; + src = pkgs.fetchFromGitHub { + owner = "amnezia-vpn"; + repo = "amneziawg-go"; + tag = "v${userspaceVersion}"; + hash = "sha256-vZb72SA+6v8FXZX247K05yiVEBWpLqAAIyw6bEE4eUQ="; + }; + patches = [ ./patches/amneziawg-go-random-trailers-transport.patch ]; + # The 3.1 releases keep the dependency set used by nixpkgs' 3.0 package. + vendorHash = "sha256-Y2dCwlKMVLrkzDcNKyCPxFJwMbCA2mQKkakvzwbamCY="; + }); + + kernelModule = kernelPackages: kernelPackages.amneziawg.overrideAttrs (_: { + inherit version; + src = pkgs.fetchFromGitHub { + owner = "amnezia-vpn"; + repo = "amneziawg-linux-kernel-module"; + tag = "v${version}"; + hash = "sha256-dJ7Au4J8iPlphSzTa3Gol/LMlroroSc2IUmXZfjA0k8="; + }; + }); +in +{ + inherit + version + userspaceVersion + tools + userspace + kernelModule + ; +} diff --git a/pkgs/default.nix b/pkgs/default.nix index 80a0b55..be791b6 100644 --- a/pkgs/default.nix +++ b/pkgs/default.nix @@ -1,5 +1,6 @@ { pkgs }: let + amneziaWg = import ./amneziawg.nix { inherit pkgs; }; mkTgWsProxy = _args: import ./tg-ws-proxy.nix { inherit pkgs; }; mkProxySuiteTray = args: import ./proxy-suite-tray.nix ({ inherit pkgs; } // args); mkProxyCtl = import ./proxy-ctl.nix { @@ -8,6 +9,9 @@ let }; in { + inherit amneziaWg; + amneziawg-tools = amneziaWg.tools; + amneziawg-go = amneziaWg.userspace; inherit mkTgWsProxy mkProxySuiteTray diff --git a/pkgs/patches/amneziawg-go-random-trailers-transport.patch b/pkgs/patches/amneziawg-go-random-trailers-transport.patch new file mode 100644 index 0000000..d2f545c --- /dev/null +++ b/pkgs/patches/amneziawg-go-random-trailers-transport.patch @@ -0,0 +1,68 @@ +diff --git a/device/receive.go b/device/receive.go +index d1901f8..8d709bf 100644 +--- a/device/receive.go ++++ b/device/receive.go +@@ -124,8 +124,18 @@ func (device *Device) RoutineReceiveIncoming( + cip.XORKeyStream(typeHash, typeHash) + } + +- // get message padding and type based on information from S1-S4 and H1-H4 +- msgSize, msgType, padding := device.DeterminePacketTypeAndPadding(packet, typeHash) ++ // A transport packet can also match a ranged H1-H3 value when random ++ // handshake trailers are enabled. Prefer an H4 candidate only when its ++ // decrypted receiver index belongs to this device; otherwise retain the ++ // normal handshake classification. This avoids silently sending valid ++ // transport packets to the handshake queue where MAC1 rejects them. ++ msgSize, msgType, padding := 0, uint32(MessageUnknownType), uint32(0) ++ if transportPadding, ok := device.DetermineTransportCandidate(packet); ok { ++ msgSize, msgType, padding = MessageTransportSize, MessageTransportType, transportPadding ++ } else { ++ // get message padding and type based on information from S1-S4 and H1-H4 ++ msgSize, msgType, padding = device.DeterminePacketTypeAndPadding(packet, typeHash) ++ } + + packet = packet[padding:] + if msgType != MessageTransportType { +@@ -590,6 +600,42 @@ func applyHash(dst, src, hash []byte) { + } + } + ++// DetermineTransportCandidate recognizes transport packets before the ranged ++// handshake classifier. A range match by itself is ambiguous, so also require ++// the decrypted receiver index to identify a keypair owned by this device. ++func (device *Device) DetermineTransportCandidate(packet []byte) (uint32, bool) { ++ padding := device.paddings.transport.Load() ++ if len(packet) < int(padding)+MessageTransportSize { ++ return 0, false ++ } ++ ++ header := make([]byte, MessageTransportHeaderSize) ++ copy(header, packet[padding:padding+MessageTransportHeaderSize]) ++ ++ cip, err := device.HeaderProtectionCipher(packet[:HeaderCipherNonceSize]) ++ if err != nil { ++ return 0, false ++ } ++ if cip != nil { ++ cip.XORKeyStream(header, header) ++ } ++ ++ transportHeader := device.headers.transport.Load() ++ if !transportHeader.Contains(binary.LittleEndian.Uint32(header[:4])) { ++ return 0, false ++ } ++ ++ receiver := binary.LittleEndian.Uint32( ++ header[MessageTransportOffsetReceiver:MessageTransportOffsetCounter], ++ ) ++ value := device.indexTable.Lookup(receiver) ++ if value.keypair == nil || value.peer == nil { ++ return 0, false ++ } ++ ++ return padding, true ++} ++ + func (device *Device) DeterminePacketTypeAndPadding(packet []byte, typeHash []byte) (int, uint32, uint32) { + var headerBytes [4]byte + var padding uint32 diff --git a/pkgs/patches/amneziawg-tools-force-userspace.patch b/pkgs/patches/amneziawg-tools-force-userspace.patch new file mode 100644 index 0000000..49e89b0 --- /dev/null +++ b/pkgs/patches/amneziawg-tools-force-userspace.patch @@ -0,0 +1,17 @@ +diff --git a/wg-quick/linux.bash b/wg-quick/linux.bash +index 20c820d..af0aef0 100755 +--- a/wg-quick/linux.bash ++++ b/wg-quick/linux.bash +@@ -87,7 +87,11 @@ auto_su() { + + add_if() { + local ret +- if ! cmd ip link add "$INTERFACE" type amneziawg; then ++ if [[ ${WG_QUICK_FORCE_USERSPACE_IMPLEMENTATION:-0} == 1 ]]; then ++ command -v "${WG_QUICK_USERSPACE_IMPLEMENTATION:-amneziawg-go}" >/dev/null || exit 1 ++ echo "[!] Using the userspace AmneziaWG implementation for this configuration." >&2 ++ cmd "${WG_QUICK_USERSPACE_IMPLEMENTATION:-amneziawg-go}" "$INTERFACE" ++ elif ! cmd ip link add "$INTERFACE" type amneziawg; then + ret=$? + [[ -e /sys/module/amneziawg ]] || ! command -v "${WG_QUICK_USERSPACE_IMPLEMENTATION:-amneziawg-go}" >/dev/null && exit $ret + echo "[!] Missing WireGuard (Amnezia VPN) kernel module. Falling back to slow userspace implementation." >&2 diff --git a/pkgs/proxy-ctl-lib.sh b/pkgs/proxy-ctl-lib.sh index f849a85..71c0bbe 100644 --- a/pkgs/proxy-ctl-lib.sh +++ b/pkgs/proxy-ctl-lib.sh @@ -7,6 +7,38 @@ ALL_SERVICES=( zapret-discord-youtube ) +_awg_service() { + printf 'proxy-suite-awg-%s' "$1" +} + +_awg_profile_exists() { + local wanted="$1" profile + for profile in "${AWG_PROFILES[@]}"; do + if [ "$profile" = "$wanted" ]; then + return 0 + fi + done + return 1 +} + +_require_awg_profile() { + local profile="$1" + if ! _awg_profile_exists "$profile"; then + echo "Unknown AmneziaWG profile: $profile" >&2 + exit 1 + fi +} + +_active_awg_profiles() { + local profile service + for profile in "${AWG_PROFILES[@]}"; do + service="$(_awg_service "$profile")" + if _svc_active "$service"; then + printf '%s\n' "$profile" + fi + done +} + _usage() { local status="${1:-1}" echo "Usage: proxy-ctl [args]" @@ -17,6 +49,10 @@ _usage() { echo " proxy on|off enable/disable the proxy backend stack" echo " tproxy on|off enable/disable TProxy transparent mode" echo " tun on|off enable/disable TUN mode" + echo " awg list|status [profile] list profiles or show AmneziaWG status" + echo " awg on start an AmneziaWG profile" + echo " awg off [profile] stop one or all active AmneziaWG profiles" + echo " awg restart [profile] restart one or all active AmneziaWG profiles" echo " route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" echo " set temporary routing override" echo " zapret on|off enable/disable zapret-discord-youtube" @@ -139,6 +175,9 @@ _status_tray() { printf 'route_mode_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)" printf 'route_mode=%s\n' "$(_route_mode_current)" printf 'default_route_mode=%s\n' "$(_route_mode_default)" + printf 'awg_available=%s\n' "$(_bool test "${#AWG_PROFILES[@]}" -gt 0)" + printf 'awg_active=%s\n' "$(_active_awg_profiles | head -n1)" + printf 'awg_profiles=%s\n' "$(IFS=,; echo "${AWG_PROFILES[*]}")" } _ensure_app_routing() { @@ -246,6 +285,9 @@ cmd_status() { for svc in "${ALL_SERVICES[@]}"; do _svc_status "$svc" done + for profile in "${AWG_PROFILES[@]}"; do + _svc_status "$(_awg_service "$profile")" + done if _svc_exists proxy-suite-socks; then echo "" echo "routing:" @@ -335,6 +377,80 @@ cmd_restart() { systemctl restart "$svc" fi done + local profile + for profile in "${AWG_PROFILES[@]}"; do + if _svc_active "$(_awg_service "$profile")"; then + systemctl restart "$(_awg_service "$profile")" + fi + done +} + +cmd_awg() { + local action="${1:-list}" profile service active + shift || true + + case "$action" in + list) + if [ "${#AWG_PROFILES[@]}" -eq 0 ]; then + echo "No AmneziaWG profiles configured." + return + fi + printf " %-24s %s\n" "PROFILE" "STATUS" + for profile in "${AWG_PROFILES[@]}"; do + service="$(_awg_service "$profile")" + active="$(systemctl is-active "$service" 2>/dev/null || true)" + printf " %-24s %s\n" "$profile" "${active:-unknown}" + done + ;; + status) + if [ "$#" -gt 0 ]; then + profile="$1" + _require_awg_profile "$profile" + systemctl is-active "$(_awg_service "$profile")" + else + _active_awg_profiles + fi + ;; + on) + profile="${1:?Usage: proxy-ctl awg on }" + _require_awg_profile "$profile" + systemctl start "$(_awg_service "$profile")" + ;; + off) + if [ "$#" -gt 0 ]; then + profile="$1" + _require_awg_profile "$profile" + systemctl stop "$(_awg_service "$profile")" + else + for profile in "${AWG_PROFILES[@]}"; do + service="$(_awg_service "$profile")" + if _svc_active "$service"; then + systemctl stop "$service" + fi + done + fi + ;; + restart) + if [ "$#" -gt 0 ]; then + profile="$1" + _require_awg_profile "$profile" + systemctl restart "$(_awg_service "$profile")" + else + active="$(_active_awg_profiles)" + if [ -z "$active" ]; then + echo "No AmneziaWG profile is active." >&2 + exit 1 + fi + while IFS= read -r profile; do + systemctl restart "$(_awg_service "$profile")" + done <<< "$active" + fi + ;; + *) + echo "Usage: proxy-ctl awg list|status [profile]|on |off [profile]|restart [profile]" >&2 + exit 1 + ;; + esac } cmd_outbounds() { diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 35afba8..9facef5 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -18,6 +18,7 @@ proxychainsQuietArg, routeModeStateFile, defaultRouteMode, + amneziaWgProfileNamesFile, }: let @@ -39,6 +40,7 @@ let PROXYCHAINS_QUIET_ARG = lib.removeSuffix " " proxychainsQuietArg; ROUTE_MODE_STATE_FILE = routeModeStateFile; DEFAULT_ROUTE_MODE = defaultRouteMode; + AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile; }; in pkgs.symlinkJoin { @@ -51,6 +53,7 @@ pkgs.symlinkJoin { subscriptionTagsFile perAppRoutingProfilesFile proxychainsConfigFile + amneziaWgProfileNamesFile ; script = unwrapped.drvAttrs.text; }; @@ -80,6 +83,7 @@ pkgs.symlinkJoin { --set PROXYCHAINS_CONFIG ${lib.escapeShellArg (toString proxychainsConfigFile)} \ --set PROXYCHAINS_QUIET_ARG ${lib.escapeShellArg (lib.removeSuffix " " proxychainsQuietArg)} \ --set ROUTE_MODE_STATE_FILE ${lib.escapeShellArg routeModeStateFile} \ - --set DEFAULT_ROUTE_MODE ${lib.escapeShellArg defaultRouteMode} + --set DEFAULT_ROUTE_MODE ${lib.escapeShellArg defaultRouteMode} \ + --set AWG_PROFILES_FILE ${lib.escapeShellArg (toString amneziaWgProfileNamesFile)} ''; } diff --git a/pkgs/proxy-ctl.sh b/pkgs/proxy-ctl.sh index ade2849..d92d627 100644 --- a/pkgs/proxy-ctl.sh +++ b/pkgs/proxy-ctl.sh @@ -2,13 +2,19 @@ set -euo pipefail # Wrapped binary provides runtime config through env vars. SUB_TAGS_FILE="${SUB_TAGS_FILE:-}" +AWG_PROFILES_FILE="${AWG_PROFILES_FILE:-}" PROXYCHAINS_QUIET_ARG="${PROXYCHAINS_QUIET_ARG:-}" SUB_TAGS=() +AWG_PROFILES=() if [ -n "$SUB_TAGS_FILE" ] && [ -f "$SUB_TAGS_FILE" ]; then mapfile -t SUB_TAGS < <(jq -r '.[]' "$SUB_TAGS_FILE") fi +if [ -n "$AWG_PROFILES_FILE" ] && [ -f "$AWG_PROFILES_FILE" ]; then + mapfile -t AWG_PROFILES < <(jq -r '.[]' "$AWG_PROFILES_FILE") +fi + cmd="${1:-status}" shift || true @@ -33,6 +39,10 @@ case "$cmd" in cmd_mode_toggle proxy-suite-tun on "${1:-}" ;; + awg) + cmd_awg "$@" + ;; + route-mode) cmd_route_mode "$@" ;; diff --git a/pkgs/proxy-suite-tray/main.c b/pkgs/proxy-suite-tray/main.c index 4e9fe12..66c556b 100644 --- a/pkgs/proxy-suite-tray/main.c +++ b/pkgs/proxy-suite-tray/main.c @@ -21,6 +21,7 @@ static GtkWidget *route_mode_item; static GtkWidget *route_mode_items[ROUTE_MODE_CHOICE_COUNT]; static GtkWidget *tproxy_item; static GtkWidget *tun_item; +static GtkWidget *awg_item; static GtkWidget *zapret_item; static GtkWidget *open_controls_item; static GtkWidget *controls_window; @@ -29,12 +30,18 @@ static GtkWidget *controls_core_status_label; static GtkWidget *controls_route_mode_status_label; static GtkWidget *controls_route_mode_combo; static GtkWidget *controls_traffic_status_label; +static GtkWidget *controls_awg_status_label; +static GtkWidget *controls_awg_combo; static GtkWidget *controls_zapret_status_label; static GtkWidget *controls_proxy_button; static GtkWidget *controls_tproxy_button; static GtkWidget *controls_tun_button; static GtkWidget *controls_zapret_button; static gboolean updating_route_mode_widgets = FALSE; +static gboolean updating_awg_widgets = FALSE; +static gchar **awg_profile_names; +static GtkWidget **awg_profile_items; +static gsize awg_profile_count; typedef enum { @@ -67,12 +74,15 @@ typedef struct gboolean socks_available; gboolean tproxy_available; gboolean tun_available; + gboolean awg_available; gboolean zapret_available; gboolean subscription_update_available; gboolean route_mode_available; gboolean socks; gboolean tproxy; gboolean tun; + gchar awg_active[64]; + gchar awg_profiles[1024]; gboolean zapret; RouteMode route_mode; RouteMode default_route_mode; @@ -201,6 +211,17 @@ static gboolean run_proxy_ctl(const char *arg1, const char *arg2) return proxy_ctl_command(arg1, arg2, NULL); } +static gboolean run_proxy_ctl3(const char *arg1, const char *arg2, const char *arg3) +{ + gchar *argv[] = { + (gchar *)PROXY_CTL_BIN, + (gchar *)arg1, + (gchar *)arg2, + (gchar *)arg3, + NULL}; + return command_succeeds(argv); +} + static gboolean parse_proxy_ctl_bool(const char *value) { return value && strcmp(value, "true") == 0; @@ -307,6 +328,18 @@ static ServiceState get_service_state(void) { state.tun = parse_proxy_ctl_bool(parts[1]); } + else if (strcmp(parts[0], "awg_available") == 0) + { + state.awg_available = parse_proxy_ctl_bool(parts[1]); + } + else if (strcmp(parts[0], "awg_active") == 0) + { + g_strlcpy(state.awg_active, parts[1], sizeof(state.awg_active)); + } + else if (strcmp(parts[0], "awg_profiles") == 0) + { + g_strlcpy(state.awg_profiles, parts[1], sizeof(state.awg_profiles)); + } else if (strcmp(parts[0], "zapret_available") == 0) { state.zapret_available = parse_proxy_ctl_bool(parts[1]); @@ -343,6 +376,10 @@ static ServiceState get_service_state(void) static const char *traffic_mode_label(const ServiceState *state) { + if (state->awg_active[0] != '\0') + { + return "AmneziaWG tunnel enabled"; + } if (state->tun) { return "TUN tunnel enabled"; @@ -408,13 +445,37 @@ static void sync_route_mode_widgets(RouteMode mode) updating_route_mode_widgets = FALSE; } +static void sync_awg_widgets(const char *active_profile) +{ + updating_awg_widgets = TRUE; + if (awg_profile_items) + { + gtk_check_menu_item_set_active( + GTK_CHECK_MENU_ITEM(awg_profile_items[0]), + !active_profile || active_profile[0] == '\0'); + for (gsize i = 0; i < awg_profile_count; ++i) + { + gtk_check_menu_item_set_active( + GTK_CHECK_MENU_ITEM(awg_profile_items[i + 1]), + active_profile && strcmp(active_profile, awg_profile_names[i]) == 0); + } + } + if (controls_awg_combo) + { + gtk_combo_box_set_active_id( + GTK_COMBO_BOX(controls_awg_combo), + active_profile && active_profile[0] != '\0' ? active_profile : "off"); + } + updating_awg_widgets = FALSE; +} + static const char *indicator_label_text(const ServiceState *state) { - if (state->socks && (state->tproxy || state->tun) && state->zapret) + if (state->socks && (state->tproxy || state->tun || state->awg_active[0] != '\0') && state->zapret) { return "Proxy + traffic + zapret"; } - if (state->socks && (state->tproxy || state->tun)) + if (state->socks && (state->tproxy || state->tun || state->awg_active[0] != '\0')) { return "Proxy + traffic"; } @@ -426,6 +487,10 @@ static const char *indicator_label_text(const ServiceState *state) { return "Proxy only"; } + if (state->awg_active[0] != '\0') + { + return "AmneziaWG"; + } if (state->zapret) { return "Zapret only"; @@ -500,6 +565,10 @@ static void update_status(void) { gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), "[Traffic] Mode: Unknown"); } + if (controls_awg_status_label) + { + gtk_label_set_text(GTK_LABEL(controls_awg_status_label), "[AmneziaWG] Profile: Unknown"); + } if (controls_route_mode_status_label) { gtk_label_set_text(GTK_LABEL(controls_route_mode_status_label), "[Routing] Mode: Unknown"); @@ -526,11 +595,14 @@ static void update_status(void) state.socks ? "Running" : "Stopped"); gchar *route_mode_text = g_strdup_printf("[Routing] Mode: %s", route_mode); gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic); + gchar *awg_text = g_strdup_printf( + "[AmneziaWG] Profile: %s", + state.awg_active[0] != '\0' ? state.awg_active : "Off"); gchar *zapret_text = g_strdup_printf( "[Zapret] zapret-discord-youtube: %s", zapret); - if (state.tproxy || state.tun) + if (state.tproxy || state.tun || state.awg_active[0] != '\0') { app_indicator_set_icon( indicator, @@ -582,6 +654,10 @@ static void update_status(void) { gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), traffic_text); } + if (controls_awg_status_label) + { + gtk_label_set_text(GTK_LABEL(controls_awg_status_label), awg_text); + } if (controls_zapret_status_label) { gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), zapret_text); @@ -619,6 +695,15 @@ static void update_status(void) gtk_menu_item_set_label(GTK_MENU_ITEM(tun_item), state.tun ? "[Traffic] Stop TUN Mode" : "[Traffic] Start TUN Mode"); } + if (awg_item) + { + gchar *label = g_strdup_printf( + "[Traffic] AmneziaWG: %s", + state.awg_active[0] != '\0' ? state.awg_active : "Off"); + gtk_menu_item_set_label(GTK_MENU_ITEM(awg_item), label); + g_free(label); + sync_awg_widgets(state.awg_active); + } if (controls_tun_button) { gtk_button_set_label(GTK_BUTTON(controls_tun_button), @@ -641,6 +726,7 @@ static void update_status(void) g_free(core_text); g_free(route_mode_text); g_free(traffic_text); + g_free(awg_text); g_free(zapret_text); } @@ -732,6 +818,44 @@ static void on_tun_toggle(GtkWidget *item, gpointer data) update_status(); } +static void set_awg_profile(const char *profile) +{ + if (profile && profile[0] != '\0' && strcmp(profile, "off") != 0) + { + run_proxy_ctl3("awg", "on", profile); + } + else + { + run_proxy_ctl("awg", "off"); + } +} + +static void on_awg_menu_toggled(GtkCheckMenuItem *item, gpointer data) +{ + if (updating_awg_widgets || !gtk_check_menu_item_get_active(item)) + { + return; + } + set_awg_profile((const char *)data); + update_status(); +} + +static void on_awg_combo_changed(GtkComboBox *combo, gpointer data) +{ + (void)data; + if (updating_awg_widgets) + { + return; + } + const gchar *profile = gtk_combo_box_get_active_id(combo); + if (!profile) + { + return; + } + set_awg_profile(profile); + update_status(); +} + static void on_zapret_toggle(GtkWidget *item, gpointer data) { (void)item; @@ -867,6 +991,25 @@ static void build_controls_window(void) gtk_box_pack_start(GTK_BOX(traffic_box), controls_tun_button, FALSE, FALSE, 0); } + if (initial_state.awg_available) + { + controls_awg_status_label = gtk_label_new("[AmneziaWG] Profile: Off"); + gtk_label_set_xalign(GTK_LABEL(controls_awg_status_label), 0.0f); + gtk_box_pack_start(GTK_BOX(traffic_box), controls_awg_status_label, FALSE, FALSE, 0); + + controls_awg_combo = gtk_combo_box_text_new(); + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_awg_combo), "off", "AmneziaWG Off"); + for (gsize i = 0; i < awg_profile_count; ++i) + { + gtk_combo_box_text_append( + GTK_COMBO_BOX_TEXT(controls_awg_combo), + awg_profile_names[i], + awg_profile_names[i]); + } + g_signal_connect(controls_awg_combo, "changed", G_CALLBACK(on_awg_combo_changed), NULL); + gtk_box_pack_start(GTK_BOX(traffic_box), controls_awg_combo, FALSE, FALSE, 0); + } + if (initial_state.zapret_available) { GtkWidget *zapret_frame = gtk_frame_new("[Zapret] DPI bypass"); @@ -971,6 +1114,40 @@ static void build_menu(void) gtk_menu_shell_append(GTK_MENU_SHELL(menu), tun_item); } + + if (initial_state.awg_available) + { + awg_item = gtk_menu_item_new_with_label("[Traffic] AmneziaWG: Off"); + GtkWidget *awg_menu = gtk_menu_new(); + GSList *awg_group = NULL; + awg_profile_items = g_new0(GtkWidget *, awg_profile_count + 1); + + awg_profile_items[0] = gtk_radio_menu_item_new_with_label(awg_group, "Off"); + g_signal_connect( + awg_profile_items[0], + "toggled", + G_CALLBACK(on_awg_menu_toggled), + (gpointer)""); + gtk_menu_shell_append(GTK_MENU_SHELL(awg_menu), awg_profile_items[0]); + awg_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(awg_profile_items[0])); + + for (gsize i = 0; i < awg_profile_count; ++i) + { + awg_profile_items[i + 1] = gtk_radio_menu_item_new_with_label( + awg_group, + awg_profile_names[i]); + g_signal_connect( + awg_profile_items[i + 1], + "toggled", + G_CALLBACK(on_awg_menu_toggled), + awg_profile_names[i]); + gtk_menu_shell_append(GTK_MENU_SHELL(awg_menu), awg_profile_items[i + 1]); + awg_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(awg_profile_items[i + 1])); + } + gtk_menu_item_set_submenu(GTK_MENU_ITEM(awg_item), awg_menu); + gtk_menu_shell_append(GTK_MENU_SHELL(menu), awg_item); + } + if (initial_state.zapret_available) { gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); @@ -1035,6 +1212,11 @@ int main(int argc, char *argv[]) app_indicator_set_status(indicator, APP_INDICATOR_STATUS_ACTIVE); initial_state = get_service_state(); + if (initial_state.awg_profiles[0] != '\0') + { + awg_profile_names = g_strsplit(initial_state.awg_profiles, ",", -1); + awg_profile_count = g_strv_length(awg_profile_names); + } build_menu(); build_controls_window(); app_indicator_set_menu(indicator, GTK_MENU(menu)); @@ -1045,5 +1227,7 @@ int main(int argc, char *argv[]) g_timeout_add_seconds(POLL_INTERVAL, on_timer, NULL); gtk_main(); + g_strfreev(awg_profile_names); + g_free(awg_profile_items); return 0; } diff --git a/scripts/amneziawg_config.py b/scripts/amneziawg_config.py new file mode 100644 index 0000000..c011edb --- /dev/null +++ b/scripts/amneziawg_config.py @@ -0,0 +1,560 @@ +#!/usr/bin/env python3 +"""Prepare a private AmneziaWG configuration for a proxy-suite profile.""" + +from __future__ import annotations + +import argparse +import base64 +import binascii +import ipaddress +import json +import os +import re +import tempfile +import zlib +from pathlib import Path +from typing import Any + + +MAX_INPUT_BYTES = 8 * 1024 * 1024 +MAX_DECOMPRESSED_BYTES = 8 * 1024 * 1024 +AWG3_SAFE_DEFAULT_MTU = 1280 +FORBIDDEN_WG_QUICK_KEYS = {"preup", "postup", "predown", "postdown", "saveconfig"} +AWG_PROTOCOL_KEYS = {"awg", "amnezia-awg", "amnezia-awg2", "amnezia-awg3"} +AWG3_INTERFACE_KEYS = { + "headerprotectionkey", + "contentpaddingaddition", + "rekeyaftertime", + "rekeytimeout", + "rejectaftertime", + "keepalivetimeout", + "maxhandshakeattempts", + "randomtrailers", + "disablecookies", +} +VPN_INTERFACE_FIELDS = { + "jc": "Jc", + "jmin": "Jmin", + "jmax": "Jmax", + "s1": "S1", + "s2": "S2", + "s3": "S3", + "s4": "S4", + "h1": "H1", + "h2": "H2", + "h3": "H3", + "h4": "H4", + "i1": "I1", + "i2": "I2", + "i3": "I3", + "i4": "I4", + "i5": "I5", + "headerprotectionkey": "HeaderProtectionKey", + "contentpaddingaddition": "ContentPaddingAddition", + "rekeyaftertime": "RekeyAfterTime", + "rekeytimeout": "RekeyTimeout", + "rejectaftertime": "RejectAfterTime", + "keepalivetimeout": "KeepaliveTimeout", + "maxhandshakeattempts": "MaxHandshakeAttempts", + "randomtrailers": "RandomTrailers", + "disablecookies": "DisableCookies", +} + + +class ConfigError(ValueError): + pass + + +def _read_limited(path: str) -> str: + with Path(path).open("rb") as handle: + data = handle.read(MAX_INPUT_BYTES + 1) + if len(data) > MAX_INPUT_BYTES: + raise ConfigError(f"input exceeds {MAX_INPUT_BYTES} bytes") + return data.decode("utf-8") + + +def _decode_json_value(value: Any, label: str) -> dict[str, Any]: + if isinstance(value, str): + try: + value = json.loads(value) + except json.JSONDecodeError as exc: + raise ConfigError(f"invalid {label} JSON: {exc}") from exc + if not isinstance(value, dict): + raise ConfigError(f"invalid {label}: expected an object") + return value + + +def decode_vpn_link(link: str) -> dict[str, Any]: + link = link.strip() + if not link.startswith("vpn://"): + raise ConfigError("expected a self-contained vpn:// link") + encoded = link[len("vpn://") :] + if not encoded or re.fullmatch(r"[A-Za-z0-9_-]+={0,2}", encoded) is None: + raise ConfigError("unsupported vpn:// link; API-backed text keys are not supported") + try: + raw = base64.b64decode( + encoded + "=" * (-len(encoded) % 4), altchars=b"-_", validate=True + ) + except (binascii.Error, ValueError) as exc: + raise ConfigError( + "unsupported vpn:// link; expected embedded base64 data, not an API-backed text key" + ) from exc + if len(raw) > MAX_INPUT_BYTES: + raise ConfigError(f"vpn:// payload exceeds {MAX_INPUT_BYTES} bytes") + + decoded = raw + if len(raw) >= 5: + expected_size = int.from_bytes(raw[:4], "big") + try: + decompressor = zlib.decompressobj() + candidate = decompressor.decompress(raw[4:], MAX_DECOMPRESSED_BYTES + 1) + if len(candidate) > MAX_DECOMPRESSED_BYTES or decompressor.unconsumed_tail: + raise ConfigError( + f"decompressed vpn:// payload exceeds {MAX_DECOMPRESSED_BYTES} bytes" + ) + candidate += decompressor.flush(MAX_DECOMPRESSED_BYTES + 1 - len(candidate)) + if decompressor.eof: + if len(candidate) > MAX_DECOMPRESSED_BYTES: + raise ConfigError( + f"decompressed vpn:// payload exceeds {MAX_DECOMPRESSED_BYTES} bytes" + ) + if len(candidate) != expected_size: + raise ConfigError("vpn:// qCompress length header does not match payload") + decoded = candidate + except zlib.error: + pass + + if len(decoded) > MAX_DECOMPRESSED_BYTES: + raise ConfigError(f"decoded vpn:// payload exceeds {MAX_DECOMPRESSED_BYTES} bytes") + # Amnezia clients also export a compact direct form where the payload is + # simply the URL-safe-base64 encoded .conf text. Normalize it to the + # same container shape as the JSON export so selection and validation stay + # identical. This is deliberately limited to a complete AWG config and + # never attempts to resolve short/API-backed keys. + try: + direct_config = decoded.decode("utf-8") + except UnicodeDecodeError: + direct_config = "" + if direct_config.lstrip().startswith("[Interface]") and "[Peer]" in direct_config: + return { + "defaultContainer": "amnezia-awg", + "containers": [ + { + "container": "amnezia-awg", + "config": direct_config, + } + ], + } + try: + result = json.loads(decoded.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ConfigError( + "unsupported vpn:// link; expected embedded qCompress/base64 JSON, not an API-backed key" + ) from exc + if not isinstance(result, dict): + raise ConfigError("invalid vpn:// configuration: expected a JSON object") + return result + + +def _candidate_payload(value: Any, key: str) -> tuple[dict[str, Any], str]: + payload = _decode_json_value(value, f"{key} protocol") + last = _decode_json_value(payload.get("last_config", payload), f"{key}.last_config") + config = last.get("config") + if not isinstance(config, str) or "[Interface]" not in config or "[Peer]" not in config: + raise ConfigError(f"{key} candidate does not contain an AmneziaWG config") + return last, config + + +def extract_vpn_config(data: dict[str, Any], requested_container: str | None = None) -> str: + containers = data.get("containers") + if not isinstance(containers, list): + raise ConfigError("vpn:// configuration has no containers list") + + candidates: list[dict[str, Any]] = [] + for index, item in enumerate(containers): + if not isinstance(item, dict): + continue + container_id = item.get("container") if isinstance(item.get("container"), str) else "" + protocols = [(key, item[key]) for key in item if key.lower() in AWG_PROTOCOL_KEYS] + if container_id.lower() in AWG_PROTOCOL_KEYS and not protocols and ( + "last_config" in item or "config" in item + ): + protocols = [(container_id, item)] + for key, value in protocols: + try: + last, config = _candidate_payload(value, key) + except ConfigError: + continue + candidates.append( + { + "id": container_id or key, + "key": key, + "index": index, + "last": last, + "config": config, + } + ) + + if not candidates: + raise ConfigError("vpn:// configuration contains no AmneziaWG client config") + + selected: list[dict[str, Any]] + if requested_container: + requested_lower = requested_container.lower() + selected = [ + candidate + for candidate in candidates + if requested_lower + in {str(candidate["id"]).lower(), str(candidate["key"]).lower()} + ] + if len(selected) != 1: + raise ConfigError( + f"vpnContainer '{requested_container}' matched {len(selected)} AmneziaWG configs" + ) + else: + default_container = data.get("defaultContainer") + default_matches = [ + candidate + for candidate in candidates + if isinstance(default_container, str) + and default_container.lower() + in {str(candidate["id"]).lower(), str(candidate["key"]).lower()} + ] + if len(default_matches) == 1: + selected = default_matches + elif len(candidates) == 1: + selected = candidates + else: + choices = ", ".join(str(candidate["id"]) for candidate in candidates) + raise ConfigError( + f"vpn:// configuration contains multiple AmneziaWG configs ({choices}); set vpnContainer" + ) + + candidate = selected[0] + config = candidate["config"] + dns1 = data.get("dns1") if isinstance(data.get("dns1"), str) else "" + dns2 = data.get("dns2") if isinstance(data.get("dns2"), str) else "" + if dns1: + config = config.replace("$PRIMARY_DNS", dns1) + if dns2: + config = config.replace("$SECONDARY_DNS", dns2) + if "$PRIMARY_DNS" in config or "$SECONDARY_DNS" in config: + raise ConfigError("vpn:// configuration contains unresolved DNS placeholders") + + last = candidate["last"] + normalized_last = { + re.sub(r"[^a-z0-9]", "", str(key).lower()): value for key, value in last.items() + } + for normalized, config_key in VPN_INTERFACE_FIELDS.items(): + value = normalized_last.get(normalized) + if value not in (None, ""): + if normalized in {"randomtrailers", "disablecookies"} and isinstance(value, bool): + value = "on" if value else "off" + config = _set_interface_value(config, config_key, str(value)) + if last.get("mtu") not in (None, ""): + config = _set_interface_value(config, "MTU", str(last["mtu"])) + if last.get("port") not in (None, ""): + config = _set_interface_value(config, "ListenPort", str(last["port"])) + return _apply_awg3_mtu_default(config) + + +def _set_interface_value(config: str, key: str, value: str) -> str: + lines = config.splitlines() + interface_index = next( + (index for index, line in enumerate(lines) if line.strip().lower() == "[interface]"), + None, + ) + if interface_index is None: + raise ConfigError("configuration has no [Interface] section") + end = next( + ( + index + for index in range(interface_index + 1, len(lines)) + if lines[index].strip().startswith("[") + ), + len(lines), + ) + pattern = re.compile(rf"^\s*{re.escape(key)}\s*=", re.IGNORECASE) + for index in range(interface_index + 1, end): + if pattern.match(lines[index]): + lines[index] = f"{key} = {value}" + break + else: + lines.insert(end, f"{key} = {value}") + return "\n".join(lines) + "\n" + + +def _interface_keys(config: str) -> set[str]: + keys: set[str] = set() + in_interface = False + for line in config.splitlines(): + stripped = line.split("#", 1)[0].split(";", 1)[0].strip() + if stripped.startswith("[") and stripped.endswith("]"): + in_interface = stripped.lower() == "[interface]" + continue + if in_interface and "=" in stripped: + key = stripped.split("=", 1)[0].strip() + keys.add(re.sub(r"[^a-z0-9]", "", key.lower())) + return keys + + +def _apply_awg3_mtu_default(config: str) -> str: + keys = _interface_keys(config) + if "mtu" in keys or not (AWG3_INTERFACE_KEYS & keys): + return config + # Amnezia exports rely on the official client's platform MTU default when + # they omit MTU. awg-quick would instead choose 1420, which is unsafe once + # AWG 3 per-packet padding is enabled and commonly black-holes larger TLS + # handshake/data packets. Match the conservative mobile client default. + return _set_interface_value(config, "MTU", str(AWG3_SAFE_DEFAULT_MTU)) + + +def _secret_value(inline: Any, path: Any, label: str) -> str: + values = int(inline is not None) + int(path is not None) + if values != 1: + raise ConfigError(f"set exactly one of {label} or {label}File") + value = str(inline) if inline is not None else _read_limited(str(path)).strip() + if not value or "\n" in value or "\r" in value: + raise ConfigError(f"{label} must be one non-empty line") + return value + + +def render_settings(settings: dict[str, Any]) -> str: + addresses = settings.get("addresses", []) + peers = settings.get("peers", []) + if not isinstance(addresses, list) or not addresses: + raise ConfigError("declarative settings require at least one address") + if not isinstance(peers, list) or not peers: + raise ConfigError("declarative settings require at least one peer") + + lines = ["[Interface]"] + private_key = _secret_value( + settings.get("privateKey"), settings.get("privateKeyFile"), "privateKey" + ) + lines.append(f"PrivateKey = {private_key}") + for address in addresses: + lines.append(f"Address = {address}") + dns = settings.get("dns", []) + if dns: + lines.append(f"DNS = {','.join(str(value) for value in dns)}") + field_map = { + "listenPort": "ListenPort", + "mtu": "MTU", + "table": "Table", + } + for source, target in field_map.items(): + if settings.get(source) is not None: + lines.append(f"{target} = {settings[source]}") + + obfuscation = settings.get("obfuscation", {}) + if not isinstance(obfuscation, dict): + raise ConfigError("obfuscation must be an object") + obfuscation_map = { + "jc": "Jc", + "jmin": "Jmin", + "jmax": "Jmax", + "s1": "S1", + "s2": "S2", + "s3": "S3", + "s4": "S4", + "h1": "H1", + "h2": "H2", + "h3": "H3", + "h4": "H4", + "i1": "I1", + "i2": "I2", + "i3": "I3", + "i4": "I4", + "i5": "I5", + "contentPaddingAddition": "ContentPaddingAddition", + "rekeyAfterTime": "RekeyAfterTime", + "rekeyTimeout": "RekeyTimeout", + "rejectAfterTime": "RejectAfterTime", + "keepaliveTimeout": "KeepaliveTimeout", + "maxHandshakeAttempts": "MaxHandshakeAttempts", + } + for source, target in obfuscation_map.items(): + if obfuscation.get(source) is not None: + lines.append(f"{target} = {obfuscation[source]}") + for source, target in { + "randomTrailers": "RandomTrailers", + "disableCookies": "DisableCookies", + }.items(): + if obfuscation.get(source) is not None: + lines.append(f"{target} = {'on' if obfuscation[source] else 'off'}") + if obfuscation.get("headerProtectionKey") is not None or obfuscation.get( + "headerProtectionKeyFile" + ) is not None: + value = _secret_value( + obfuscation.get("headerProtectionKey"), + obfuscation.get("headerProtectionKeyFile"), + "headerProtectionKey", + ) + lines.append(f"HeaderProtectionKey = {value}") + + for peer in peers: + if not isinstance(peer, dict): + raise ConfigError("peer must be an object") + public_key = peer.get("publicKey") + allowed_ips = peer.get("allowedIPs", []) + if not public_key or not allowed_ips: + raise ConfigError("each peer requires publicKey and allowedIPs") + lines.extend(["", "[Peer]", f"PublicKey = {public_key}"]) + if peer.get("presharedKey") is not None or peer.get("presharedKeyFile") is not None: + value = _secret_value( + peer.get("presharedKey"), peer.get("presharedKeyFile"), "presharedKey" + ) + lines.append(f"PresharedKey = {value}") + lines.append(f"AllowedIPs = {','.join(str(value) for value in allowed_ips)}") + if peer.get("endpoint") is not None: + lines.append(f"Endpoint = {peer['endpoint']}") + if peer.get("persistentKeepalive") is not None: + lines.append(f"PersistentKeepalive = {peer['persistentKeepalive']}") + if peer.get("advancedSecurity") is not None: + lines.append( + f"AdvancedSecurity = {'on' if peer['advancedSecurity'] else 'off'}" + ) + return "\n".join(lines) + "\n" + + +def validate_config(config: str, allow_hooks: bool = False) -> None: + lowered = config.lower() + if "[interface]" not in lowered or "[peer]" not in lowered: + raise ConfigError("configuration requires [Interface] and [Peer] sections") + if not allow_hooks: + for line in config.splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith(("#", ";")) or "=" not in stripped: + continue + key = stripped.split("=", 1)[0].strip().lower() + if key in FORBIDDEN_WG_QUICK_KEYS: + raise ConfigError( + f"configuration contains privileged wg-quick directive '{key}'; " + "set allowConfigHooks = true only for trusted input" + ) + + +def probe_address(config: str) -> str: + """Return an address covered by a peer route without exposing credentials.""" + networks: list[ipaddress.IPv4Network | ipaddress.IPv6Network] = [] + in_peer = False + for line in config.splitlines(): + stripped = line.split("#", 1)[0].split(";", 1)[0].strip() + if stripped.startswith("[") and stripped.endswith("]"): + in_peer = stripped.lower() == "[peer]" + continue + if not in_peer or "=" not in stripped: + continue + key, value = (part.strip() for part in stripped.split("=", 1)) + if key.lower() != "allowedips": + continue + for item in value.split(","): + try: + networks.append(ipaddress.ip_network(item.strip(), strict=False)) + except ValueError: + continue + + preferred = [ipaddress.ip_address("1.1.1.1"), ipaddress.ip_address("2606:4700:4700::1111")] + for address in preferred: + if any(address in network for network in networks): + return str(address) + for network in networks: + if network.num_addresses == 1: + return str(network.network_address) + return str(network.network_address + 1) + raise ConfigError("configuration has no usable peer AllowedIPs for a startup handshake probe") + + +def transport_implementation(config: str) -> str: + """Select userspace for the upstream RandomTrailers/ranged-header defect.""" + random_trailers = False + ranged_handshake_header = False + in_interface = False + for line in config.splitlines(): + stripped = line.split("#", 1)[0].split(";", 1)[0].strip() + if stripped.startswith("[") and stripped.endswith("]"): + in_interface = stripped.lower() == "[interface]" + continue + if not in_interface or "=" not in stripped: + continue + key, value = (part.strip() for part in stripped.split("=", 1)) + normalized_key = key.lower() + if normalized_key == "randomtrailers": + random_trailers = value.lower() in {"on", "true", "yes", "1"} + elif normalized_key in {"h1", "h2", "h3"}: + ranged_handshake_header |= re.fullmatch(r"[0-9]+\s*-\s*[0-9]+", value) is not None + return "userspace" if random_trailers and ranged_handshake_header else "auto" + + +def prepare(manifest: dict[str, Any]) -> str: + kind = manifest.get("kind") + if kind == "configFile": + config = _read_limited(str(manifest["path"])) + elif kind in {"vpnFile", "vpn"}: + link = _read_limited(str(manifest["path"])) + config = extract_vpn_config(decode_vpn_link(link), manifest.get("vpnContainer")) + elif kind == "settings": + config = render_settings(_decode_json_value(manifest.get("settings"), "settings")) + else: + raise ConfigError(f"unsupported manifest kind '{kind}'") + config = _apply_awg3_mtu_default(config) + validate_config(config, bool(manifest.get("allowConfigHooks", False))) + return config + + +def write_private(path: str, content: str) -> None: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + fd, temporary = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent) + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, destination) + except Exception: + try: + os.unlink(temporary) + except FileNotFoundError: + pass + raise + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--manifest") + parser.add_argument("--output") + parser.add_argument("--probe-address") + parser.add_argument("--transport-implementation") + args = parser.parse_args() + try: + if args.probe_address is not None: + if ( + args.manifest is not None + or args.output is not None + or args.transport_implementation is not None + ): + raise ConfigError("--probe-address cannot be combined with rendering options") + print(probe_address(_read_limited(args.probe_address))) + return 0 + if args.transport_implementation is not None: + if args.manifest is not None or args.output is not None: + raise ConfigError( + "--transport-implementation cannot be combined with rendering options" + ) + print(transport_implementation(_read_limited(args.transport_implementation))) + return 0 + if args.manifest is None or args.output is None: + raise ConfigError("--manifest and --output are required when rendering a configuration") + manifest = json.loads(_read_limited(args.manifest)) + if not isinstance(manifest, dict): + raise ConfigError("manifest must be a JSON object") + write_private(args.output, prepare(manifest)) + except (ConfigError, KeyError, OSError, json.JSONDecodeError) as exc: + parser.exit(1, f"amneziawg-config: {exc}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/test-amneziawg-config.py b/scripts/test-amneziawg-config.py new file mode 100644 index 0000000..bb36c78 --- /dev/null +++ b/scripts/test-amneziawg-config.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 + +import base64 +import json +import tempfile +import unittest +import zlib +from pathlib import Path + +from amneziawg_config import ( + ConfigError, + decode_vpn_link, + extract_vpn_config, + prepare, + probe_address, + render_settings, + transport_implementation, + validate_config, + write_private, +) + + +BASE_CONFIG = """[Interface] +PrivateKey = private +Address = 10.8.0.2/32 +DNS = $PRIMARY_DNS,$SECONDARY_DNS +Jc = 5 +S3 = 12 +S4 = 12 +HeaderProtectionKey = header +ContentPaddingAddition = 8-16 + +[Peer] +PublicKey = public +AllowedIPs = 0.0.0.0/0 +Endpoint = vpn.example.com:51820 +""" + + +def vpn_data(*entries): + return { + "defaultContainer": entries[0][0], + "dns1": "1.1.1.1", + "dns2": "8.8.8.8", + "containers": [ + { + "container": container, + key: { + "last_config": json.dumps( + {"config": config, "mtu": "1280", "port": 41111} + ) + }, + } + for container, key, config in entries + ], + } + + +def encode_vpn(data, compressed=True): + raw = json.dumps(data).encode() + if compressed: + raw = len(raw).to_bytes(4, "big") + zlib.compress(raw) + encoded = base64.urlsafe_b64encode(raw).decode().rstrip("=") + return f"vpn://{encoded}" + + +class AmneziaWgConfigTests(unittest.TestCase): + def test_qcompress_vpn_link(self): + data = decode_vpn_link(encode_vpn(vpn_data(("amnezia-awg", "awg", BASE_CONFIG)))) + config = extract_vpn_config(data) + self.assertIn("DNS = 1.1.1.1,8.8.8.8", config) + self.assertIn("MTU = 1280", config) + self.assertIn("ListenPort = 41111", config) + self.assertIn("HeaderProtectionKey = header", config) + + def test_uncompressed_vpn_link(self): + data = decode_vpn_link( + encode_vpn(vpn_data(("amnezia-awg2", "amnezia-awg", BASE_CONFIG)), False) + ) + self.assertIn("[Peer]", extract_vpn_config(data)) + + def test_uncompressed_direct_conf_vpn_link(self): + direct = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1,8.8.8.8") + link = "vpn://" + base64.urlsafe_b64encode(direct.encode()).decode() + data = decode_vpn_link(link) + config = extract_vpn_config(data) + self.assertIn("[Interface]", config) + self.assertIn("[Peer]", config) + self.assertIn("MTU = 1280", config) + + def test_awg3_vpn_mtu_fallback_preserves_explicit_values(self): + data = vpn_data(("amnezia-awg3", "awg", BASE_CONFIG)) + last = json.loads(data["containers"][0]["awg"]["last_config"]) + del last["mtu"] + data["containers"][0]["awg"]["last_config"] = last + self.assertIn("MTU = 1280", extract_vpn_config(data)) + + explicit = BASE_CONFIG.replace("Address =", "MTU = 1312\nAddress =") + data = vpn_data(("amnezia-awg3", "awg", explicit)) + last = json.loads(data["containers"][0]["awg"]["last_config"]) + del last["mtu"] + data["containers"][0]["awg"]["last_config"] = last + config = extract_vpn_config(data) + self.assertIn("MTU = 1312", config) + self.assertNotIn("MTU = 1280", config) + + def test_legacy_vpn_without_mtu_keeps_awg_quick_default(self): + legacy = BASE_CONFIG.replace("HeaderProtectionKey = header\n", "").replace( + "ContentPaddingAddition = 8-16\n", "" + ) + data = vpn_data(("amnezia-awg", "awg", legacy)) + last = json.loads(data["containers"][0]["awg"]["last_config"]) + del last["mtu"] + data["containers"][0]["awg"]["last_config"] = last + self.assertNotIn("MTU =", extract_vpn_config(data)) + + def test_legacy_direct_last_config_shape(self): + data = vpn_data(("amnezia-awg", "awg", BASE_CONFIG)) + last_config = data["containers"][0]["awg"]["last_config"] + data["containers"] = [ + {"container": "amnezia-awg", "last_config": last_config} + ] + self.assertIn("MTU = 1280", extract_vpn_config(data)) + + def test_awg3_fields_are_restored_from_last_config(self): + data = vpn_data(("amnezia-awg3", "awg", BASE_CONFIG)) + last = json.loads(data["containers"][0]["awg"]["last_config"]) + last.update( + { + "HeaderProtectionKey": "json-header", + "content_padding_addition": "20-40", + "RekeyAfterTime": "100-120", + "MaxHandshakeAttempts": "15-20", + "S4": 48, + } + ) + data["containers"][0]["awg"]["last_config"] = last + config = extract_vpn_config(data) + self.assertIn("HeaderProtectionKey = json-header", config) + self.assertIn("ContentPaddingAddition = 20-40", config) + self.assertIn("RekeyAfterTime = 100-120", config) + self.assertIn("MaxHandshakeAttempts = 15-20", config) + self.assertIn("S4 = 48", config) + + def test_awg3_boolean_fields_are_restored_from_last_config(self): + data = vpn_data(("amnezia-awg3", "awg", BASE_CONFIG)) + last = json.loads(data["containers"][0]["awg"]["last_config"]) + last.update({"RandomTrailers": "on", "DisableCookies": True}) + data["containers"][0]["awg"]["last_config"] = last + config = extract_vpn_config(data) + self.assertIn("RandomTrailers = on", config) + self.assertIn("DisableCookies = on", config) + + def test_explicit_container_resolves_ambiguity(self): + data = vpn_data( + ("amnezia-awg", "awg", BASE_CONFIG), + ("amnezia-awg2", "awg", BASE_CONFIG.replace("10.8.0.2", "10.9.0.2")), + ) + data["defaultContainer"] = "not-awg" + with self.assertRaisesRegex(ConfigError, "multiple AmneziaWG"): + extract_vpn_config(data) + selected = extract_vpn_config(data, "amnezia-awg2") + self.assertIn("10.9.0.2", selected) + + def test_default_protocol_key_resolves_ambiguity(self): + data = vpn_data( + ("client-a", "awg", BASE_CONFIG), + ("client-b", "amnezia-awg2", BASE_CONFIG.replace("10.8.0.2", "10.9.0.2")), + ) + data["defaultContainer"] = "awg" + self.assertIn("10.8.0.2", extract_vpn_config(data)) + + def test_api_backed_short_key_is_rejected(self): + with self.assertRaisesRegex(ConfigError, "API-backed"): + decode_vpn_link("vpn://short-key") + + def test_qcompress_length_is_checked(self): + raw = json.dumps(vpn_data(("amnezia-awg", "awg", BASE_CONFIG))).encode() + payload = (len(raw) + 1).to_bytes(4, "big") + zlib.compress(raw) + link = "vpn://" + base64.urlsafe_b64encode(payload).decode().rstrip("=") + with self.assertRaisesRegex(ConfigError, "length header"): + decode_vpn_link(link) + + def test_decompression_limit_is_enforced(self): + raw = b"{" + b" " * (8 * 1024 * 1024) + b"}" + payload = len(raw).to_bytes(4, "big") + zlib.compress(raw) + link = "vpn://" + base64.urlsafe_b64encode(payload).decode().rstrip("=") + with self.assertRaisesRegex(ConfigError, "exceeds"): + decode_vpn_link(link) + + def test_missing_and_malformed_candidates_fail_cleanly(self): + with self.assertRaisesRegex(ConfigError, "no containers"): + extract_vpn_config({}) + with self.assertRaisesRegex(ConfigError, "no AmneziaWG"): + extract_vpn_config({"containers": [{"container": "xray"}]}) + unresolved = vpn_data(("amnezia-awg", "awg", BASE_CONFIG)) + del unresolved["dns2"] + with self.assertRaisesRegex(ConfigError, "unresolved DNS"): + extract_vpn_config(unresolved) + + def test_hooks_rejected_by_default_and_allowed_explicitly(self): + hooked = BASE_CONFIG.replace("Address =", "PostUp = touch /root/pwned\nAddress =") + with self.assertRaisesRegex(ConfigError, "privileged"): + validate_config(hooked) + validate_config(hooked, allow_hooks=True) + + def test_declarative_awg3_and_secret_files(self): + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + private_key = directory / "private" + psk = directory / "psk" + header = directory / "header" + private_key.write_text("private-file\n") + psk.write_text("psk-file\n") + header.write_text("header-file\n") + config = render_settings( + { + "addresses": ["10.8.0.2/32"], + "dns": ["1.1.1.1"], + "privateKeyFile": str(private_key), + "obfuscation": { + "s1": 12, + "s2": 12, + "s3": 12, + "s4": 12, + "h1": "100-200", + "i1": "", + "headerProtectionKeyFile": str(header), + "rekeyAfterTime": "120-180", + "maxHandshakeAttempts": 10, + "randomTrailers": True, + "disableCookies": True, + }, + "peers": [ + { + "publicKey": "public", + "presharedKeyFile": str(psk), + "allowedIPs": ["0.0.0.0/0", "::/0"], + "endpoint": "vpn.example.com:51820", + "persistentKeepalive": "20-30", + "advancedSecurity": True, + } + ], + } + ) + self.assertIn("PrivateKey = private-file", config) + self.assertIn("HeaderProtectionKey = header-file", config) + self.assertIn("RekeyAfterTime = 120-180", config) + self.assertIn("RandomTrailers = on", config) + self.assertIn("DisableCookies = on", config) + self.assertIn("AdvancedSecurity = on", config) + + prepared = prepare({"kind": "settings", "settings": { + "addresses": ["10.8.0.2/32"], + "privateKeyFile": str(private_key), + "obfuscation": {"headerProtectionKeyFile": str(header)}, + "peers": [{"publicKey": "public", "allowedIPs": ["0.0.0.0/0"]}], + }}) + self.assertIn("MTU = 1280", prepared) + + def test_prepare_config_file_and_private_output(self): + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + source = directory / "source.conf" + output = directory / "runtime" / "awg.conf" + source.write_text(BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")) + config = prepare({"kind": "configFile", "path": str(source)}) + self.assertIn("MTU = 1280", config) + write_private(str(output), config) + self.assertEqual(output.stat().st_mode & 0o777, 0o600) + + def test_probe_address_prefers_public_address_covered_by_default_route(self): + config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1") + self.assertEqual(probe_address(config), "1.1.1.1") + + def test_probe_address_uses_host_inside_narrow_route(self): + config = BASE_CONFIG.replace( + "AllowedIPs = 0.0.0.0/0", "AllowedIPs = 10.23.42.0/24" + ) + self.assertEqual(probe_address(config), "10.23.42.1") + + def test_random_trailers_with_ranged_handshake_headers_forces_userspace(self): + config = BASE_CONFIG.replace( + "ContentPaddingAddition = 8-16", + "ContentPaddingAddition = 8-16\nH1 = 213818264-462596257\nRandomTrailers = on", + ) + self.assertEqual(transport_implementation(config), "userspace") + self.assertEqual( + transport_implementation(config.replace("RandomTrailers = on", "RandomTrailers = off")), + "auto", + ) + + +if __name__ == "__main__": + unittest.main()