diff --git a/README.md b/README.md index 24466e1..ba818f0 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Inspired by [Throne](https://github.com/throneproj/Throne) (formerly NekoRay), [ - AmneziaWG 1.x–3.x tunnels from `.conf`, `vpn://`, or Nix - Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel - Cloudflare WARP from a `wgcf` profile, as an outbound or an AWG VPN profile -- Server inbounds with share links, QR codes, per-user subscriptions and traffic stats +- Server inbounds (XRay protocols and multi-user AmneziaWG) with share links, QR codes, per-user subscriptions and traffic stats - Proxy Suite GUI (a desktop app with a tray icon), the `proxy-ctl` CLI, and the `proxy-tui` terminal UI ## Setup @@ -118,7 +118,7 @@ The same options work outside NixOS. Pick the module for the host; everything th | Server inbounds, share links, stats | ✓ | ✓ | ports ≥ 1024 | ports ≥ 1024 | | tg-ws-proxy, SSH proxy, WARP as a sing-box outbound | ✓ | ✓ | ✓ | ✓ | | AmneziaWG `asOutbound = "userspace"` | ✓ | ✓ | ✓ | ✓ | -| Global TUN/TProxy, per-app TUN/TProxy/zapret, zapret, AmneziaWG interfaces | ✓ | ✓ | ✗ | ✗ | +| Global TUN/TProxy, per-app TUN/TProxy/zapret, zapret, AmneziaWG interfaces and inbounds | ✓ | ✓ | ✗ | ✗ | | `userControl`, polkit | ✓ | ✓ | not needed | not needed | | GUI | ✓ | ✓ | ✓ | ✗ (`proxy-ctl`, `proxy-tui`) | @@ -132,7 +132,7 @@ modules = [ inputs.proxy-suite.systemManagerModules.default ]; ``` - Units, service users and the polkit rules (`/etc/polkit-1/rules.d/50-proxy-suite.rules`) are installed like on NixOS; the GUI's user unit goes to `/etc/systemd/user`. The service users come from `users.users`, so system-manager needs its user management. -- The host's firewall is left alone: open the inbound ports yourself. TUN, TProxy and zapret load their own nftables tables, which needs `nf_tables`, `nfnetlink_queue` and `tun` in the host kernel. +- The host's firewall is left alone: open the inbound ports yourself, and let AmneziaWG inbound interfaces (`awgi-*`) through the input chain and strict reverse-path filtering. TUN, TProxy, zapret and AmneziaWG inbounds load their own nftables tables, which needs `nf_tables`, `nfnetlink_queue`, `nft_tproxy` and `tun` in the host kernel. - AmneziaWG runs on its userspace implementation (`amneziaWg.kernelModulePackage` must stay `null`). DNS pushed by a VPN profile goes through `resolvectl` under systemd-resolved, `openresolv` otherwise. #### home-manager (any Linux, no root) @@ -226,6 +226,8 @@ Secrets and changes need root, or the userControl group. inbounds [list] server inbounds inbounds link [user] [--qr|--json] client share link, or the client's outbound JSON + inbounds link [user] --config [--qr] + an AmneziaWG client's .conf, or its QR code inbounds link --server-json the server's inbound JSON inbounds sub [user] [--qr] subscription users, or one user's URL inbounds stats [days] [--by user|inbound|outbound] diff --git a/docs/options/inbounds.md b/docs/options/inbounds.md index 4a32512..d40a1c8 100644 --- a/docs/options/inbounds.md +++ b/docs/options/inbounds.md @@ -10,6 +10,43 @@ Part of the [proxy-suite options reference](./index.md). - [listeners](#services-proxy-suite-inbounds-listeners) - `` - [address](#services-proxy-suite-inbounds-listeners-name-address) + - [amneziaWg](#services-proxy-suite-inbounds-listeners-name-amneziawg) + - [clientAllowedIPs](#services-proxy-suite-inbounds-listeners-name-amneziawg-clientallowedips) + - [dns](#services-proxy-suite-inbounds-listeners-name-amneziawg-dns) + - [interfaceName](#services-proxy-suite-inbounds-listeners-name-amneziawg-interfacename) + - [mode](#services-proxy-suite-inbounds-listeners-name-amneziawg-mode) + - [mtu](#services-proxy-suite-inbounds-listeners-name-amneziawg-mtu) + - [obfuscation](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation) + - [contentPaddingAddition](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-contentpaddingaddition) + - [disableCookies](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-disablecookies) + - [h1](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-h1) + - [h2](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-h2) + - [h3](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-h3) + - [h4](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-h4) + - [headerProtectionKey](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-headerprotectionkey) + - [headerProtectionKeyFile](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-headerprotectionkeyfile) + - [i1](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i1) + - [i2](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i2) + - [i3](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i3) + - [i4](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i4) + - [i5](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i5) + - [jc](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-jc) + - [jmax](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-jmax) + - [jmin](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-jmin) + - [keepaliveTimeout](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-keepalivetimeout) + - [maxHandshakeAttempts](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-maxhandshakeattempts) + - [randomTrailers](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-randomtrailers) + - [rejectAfterTime](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-rejectaftertime) + - [rekeyAfterTime](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-rekeyaftertime) + - [rekeyTimeout](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-rekeytimeout) + - [s1](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-s1) + - [s2](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-s2) + - [s3](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-s3) + - [s4](#services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-s4) + - [persistentKeepalive](#services-proxy-suite-inbounds-listeners-name-amneziawg-persistentkeepalive) + - [privateKeyFile](#services-proxy-suite-inbounds-listeners-name-amneziawg-privatekeyfile) + - [subnet](#services-proxy-suite-inbounds-listeners-name-amneziawg-subnet) + - [subnet6](#services-proxy-suite-inbounds-listeners-name-amneziawg-subnet6) - [flow](#services-proxy-suite-inbounds-listeners-name-flow) - [jsonFile](#services-proxy-suite-inbounds-listeners-name-jsonfile) - [method](#services-proxy-suite-inbounds-listeners-name-method) @@ -41,9 +78,13 @@ Part of the [proxy-suite options reference](./index.md). - [type](#services-proxy-suite-inbounds-listeners-name-type) - [users](#services-proxy-suite-inbounds-listeners-name-users) - item + - [address](#services-proxy-suite-inbounds-listeners-name-users-address) - [name](#services-proxy-suite-inbounds-listeners-name-users-name) - [password](#services-proxy-suite-inbounds-listeners-name-users-password) - [passwordFile](#services-proxy-suite-inbounds-listeners-name-users-passwordfile) + - [presharedKeyFile](#services-proxy-suite-inbounds-listeners-name-users-presharedkeyfile) + - [privateKeyFile](#services-proxy-suite-inbounds-listeners-name-users-privatekeyfile) + - [publicKey](#services-proxy-suite-inbounds-listeners-name-users-publickey) - [uuid](#services-proxy-suite-inbounds-listeners-name-users-uuid) - [uuidFile](#services-proxy-suite-inbounds-listeners-name-users-uuidfile) - [via](#services-proxy-suite-inbounds-listeners-name-via) @@ -119,7 +160,7 @@ attribute set of (submodule) *Example:* -```nix +````nix { vless-reality = { type = "vless"; @@ -134,9 +175,16 @@ attribute set of (submodule) shortIds = [ "0123abcd" ]; }; }; + # `proxy-ctl inbounds link home phone` prints a vpn:// link; add --config for the .conf. + home = { + type = "amneziawg"; + port = 51820; + users = [ { name = "phone"; } { name = "laptop"; } ]; + amneziaWg.mode = "lan"; + }; } -``` +```` ## services\.proxy-suite\.inbounds\.listeners\.\\.address @@ -158,6 +206,550 @@ string matching the pattern \[^\[:space:]]+ "127.0.0.1" ``` + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg + +The AmneziaWG server of a type = “amneziawg” listener\. + +*Type:* +submodule + +*Default:* + +```nix +{ } +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.clientAllowedIPs + +AllowedIPs in client configs: what clients send through the tunnel\. + +*Type:* +list of string + +*Default:* + +```nix +[ + "0.0.0.0/0" + "::/0" +] +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.dns + +DNS servers in client configs\. Queries leave like any other traffic\. + +*Type:* +list of string + +*Default:* + +```nix +[ + "1.1.1.1" + "1.0.0.1" +] +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.interfaceName + +Linux interface name\. It must fit Linux’s 15-character limit\. + +*Type:* +string matching the pattern ^\[A-Za-z0-9_\.-]+$ + +*Default:* + +```nix +"awgi-" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.mode + +What clients reach besides the internet, which they reach the listener’s ` via ` way either way: + + - “proxy”: nothing else\. This host, its private networks and the other peers are cut off\. + - “lan”: also this host, its private networks and the other peers, directly (masqueraded + behind this host), not through ` via `\. It turns on IP forwarding\. + Only TCP and UDP can follow ` via `: anything else to the internet (ping) is dropped\. + +*Type:* +one of “proxy”, “lan” + +*Default:* + +```nix +"proxy" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.mtu + +Interface MTU, on both ends\. Null leaves awg-quick’s (1280 with AWG 3 fields)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation + +Obfuscation parameters, shared with every client\. Jc, Jmin, Jmax, S1, S2 and H1-H4 left +null are generated once and kept in the state directory; the rest stay unset\. + +*Type:* +submodule + +*Default:* + +```nix +{ } +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.disableCookies + +AWG 3 cookie suppression (DisableCookies)\. + +*Type:* +null or boolean + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.headerProtectionKey + +Inline AWG 3 header-protection key\. Prefer headerProtectionKeyFile\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.headerProtectionKeyFile + +Runtime path containing the AWG 3 header-protection key\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.i1 + +First custom signature packet (I1)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.i2 + +Second custom signature packet (I2)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.i3 + +Third custom signature packet (I3)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.i4 + +Fourth custom signature packet (I4)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.i5 + +Fifth custom signature packet (I5)\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.jc + +Junk packet count (Jc)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.jmax + +Maximum junk packet size (Jmax)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.jmin + +Minimum junk packet size (Jmin)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.randomTrailers + +AWG 3 random transport trailers (RandomTrailers)\. + +*Type:* +null or boolean + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.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 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.s1 + +Handshake-init padding (S1)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.s2 + +Handshake-response padding (S2)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.s3 + +Cookie-reply padding (S3)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.obfuscation\.s4 + +Transport-message padding (S4)\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.persistentKeepalive + +PersistentKeepalive in client configs, which keeps NAT mappings open\. + +*Type:* +null or (unsigned integer, meaning >=0) + +*Default:* + +```nix +25 +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.privateKeyFile + +Runtime path to the server private key, instead of a generated one\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/awg-server-key" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.subnet + +Tunnel IPv4 subnet, private and unused elsewhere\. This host takes the first address, clients +the rest\. + +*Type:* +string matching the pattern \[0-9\.]+/\[0-9]+ + +*Default:* + +```nix +"10.66.0.0/24" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.amneziaWg\.subnet6 + +Tunnel IPv6 subnet (ULA), laid out as subnet\. Null keeps the tunnel IPv4-only\. With mode = “lan” +it turns on IPv6 forwarding, which stops this host configuring itself from router advertisements\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"fd66:66::/64" +``` + ## services\.proxy-suite\.inbounds\.listeners\.\\.flow @@ -698,10 +1290,12 @@ one of “raw”, “ws”, “grpc”, “httpupgrade”, “xhttp” ## services\.proxy-suite\.inbounds\.listeners\.\\.type -Protocol\. Set exactly one of type, xrayJson, or jsonFile\. +Protocol\. Set exactly one of type, xrayJson, or jsonFile\. “amneziawg” is an AmneziaWG +server on UDP port, with its own interface (see amneziaWg); its traffic is handed to XRay +and leaves like any other listener’s\. *Type:* -null or one of “vless”, “vmess”, “trojan”, “shadowsocks”, “socks”, “http” +null or one of “vless”, “vmess”, “trojan”, “shadowsocks”, “socks”, “http”, “amneziawg” *Default:* @@ -739,6 +1333,27 @@ list of (submodule) ] ``` + +## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.address + +AmneziaWG tunnel IPv4 address, inside amneziaWg\.subnet\. Null takes the lowest free one, which +the user keeps for as long as it exists\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"10.66.0.10" +``` + ## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.name @@ -799,6 +1414,67 @@ null "/run/secrets/proxy-inbound-password" ``` + +## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.presharedKeyFile + +Runtime path to the AmneziaWG preshared key, instead of a generated one\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/awg-phone-psk" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.privateKeyFile + +Runtime path to the AmneziaWG client private key, instead of a generated one\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/awg-phone-key" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.publicKey + +AmneziaWG public key of a peer that keeps its private key to itself\. It gets no client +config or link\. Null generates a key pair, kept in the state directory\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"jNXH..." +``` + ## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.uuid diff --git a/modules/proxy-suite/amnezia-wg-inbounds.nix b/modules/proxy-suite/amnezia-wg-inbounds.nix new file mode 100644 index 0000000..c8ad8e6 --- /dev/null +++ b/modules/proxy-suite/amnezia-wg-inbounds.nix @@ -0,0 +1,227 @@ +# AmneziaWG server listeners of services.proxy-suite.inbounds: one interface per listener, +# whose TCP and UDP is diverted by TProxy to the listener's loopback XRay inbound, so it +# leaves by the same routing as every other inbound. "lan" listeners also reach this host, +# its private networks and each other natively; "proxy" listeners reach nothing but that. +{ + lib, + pkgs, + cfg, + derived, + proxyInboundsSpecFile, + reservedIpBlock, + ip, + nft, +}: + +let + awgCfg = cfg.amneziaWg; + listeners = derived.proxyInboundsAwg; + inherit (derived.constants) awgInboundFwmark awgInboundRouteTable awgInboundRulePriority; + unitName = "proxy-suite-inbounds-awg"; + nftTable = "proxy_suite_awg_inbounds"; + ipv6 = lib.any (listener: listener.subnet6 != null) listeners; + lanListeners = builtins.filter (listener: listener.mode == "lan") listeners; + lanIPv6 = lib.any (listener: listener.subnet6 != null) lanListeners; + + scriptsDir = builtins.path { + name = "proxy-suite-scripts"; + path = ../../scripts; + }; + python3 = "${pkgs.python3}/bin/python3"; + awg = "${awgCfg.toolsPackage}/bin/awg"; + awgQuick = "${awgCfg.toolsPackage}/bin/awg-quick"; + + # Diverted packets are delivered locally; only "lan" listeners forward. + sysctl = + lib.optionalAttrs (lanListeners != [ ]) { + "net.ipv4.ip_forward" = 1; + } + // lib.optionalAttrs lanIPv6 { + "net.ipv6.conf.all.forwarding" = 1; + }; + + quote = value: ''"${value}"''; + + # Everything a listener's clients send that is not theirs to reach natively. + mkListenerChain = + index: listener: + let + verdict = if listener.mode == "lan" then "return" else "drop"; + port = toString listener.internalPort; + mark = toString awgInboundFwmark; + in + '' + chain listener_${toString index} { + fib daddr type { local, broadcast, multicast } ${verdict} + ip daddr $RESERVED_IP ${verdict} + # Not in RESERVED_IP, whose other users route it by the local subnets instead. + ip daddr 192.168.0.0/16 ${verdict} + ip6 daddr $RESERVED_IP6 ${verdict} + ip daddr ${listener.subnet} ${verdict} + ${lib.optionalString (listener.subnet6 != null) " ip6 daddr ${listener.subnet6} ${verdict}"} + meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:${port} meta mark set ${mark} accept + ${lib.optionalString ( + listener.subnet6 != null + ) " meta l4proto { tcp, udp } tproxy ip6 to [::1]:${port} meta mark set ${mark} accept"} + # Nothing else can follow the listener's routing (ICMP to the internet among it). + drop + } + ''; + + nftRulesFile = pkgs.writeText "proxy-suite-routing" '' + ${reservedIpBlock} + table inet ${nftTable} { + ${lib.concatStrings (lib.imap0 mkListenerChain listeners)} + chain prerouting { + # Ahead of TProxy and TUN capture, and of the reverse-path filter. + type filter hook prerouting priority mangle - 5; policy accept; + # The XRay inbounds only take what is diverted to them. + iifname != "lo" meta l4proto { tcp, udp } th dport { ${ + lib.concatMapStringsSep ", " (listener: toString listener.internalPort) listeners + } } fib daddr type local drop + ${lib.concatStrings ( + lib.imap0 (index: listener: '' + iifname ${quote listener.interface} jump listener_${toString index} + '') listeners + )} + } + ${lib.optionalString (lanListeners != [ ]) '' + # Private networks need no route back to the clients. + chain postrouting { + type nat hook postrouting priority srcnat; policy accept; + ${lib.concatMapStrings (listener: '' + ip saddr ${listener.subnet} oifname != ${quote listener.interface} masquerade + ${lib.optionalString ( + listener.subnet6 != null + ) "ip6 saddr ${listener.subnet6} oifname != ${quote listener.interface} masquerade"} + '') lanListeners} + } + ''} + } + ''; + + routingDown = + lib.concatMapStrings + (family: '' + while ${ip} ${family} rule del pref ${toString awgInboundRulePriority} 2>/dev/null; do :; done + ${ip} ${family} route flush table ${toString awgInboundRouteTable} 2>/dev/null || true + '') + [ + "-4" + "-6" + ]; + + # The interfaces run with Table=off and no DNS, so deleting them undoes awg-quick. + interfacesDown = lib.concatMapStrings (listener: '' + ${ip} link del dev ${lib.escapeShellArg listener.interface} 2>/dev/null || true + '') listeners; + + stop = pkgs.writeShellScript unitName '' + set +e + ${nft} delete table inet ${nftTable} 2>/dev/null + ${routingDown} + ${interfacesDown} + true + ''; + + start = pkgs.writeShellScript unitName '' + set -Eeuo pipefail + trap ${stop} ERR + + ${lib.optionalString (awgCfg.kernelModulePackage != null) '' + ${pkgs.kmod}/bin/modprobe amneziawg 2>/dev/null || true + ''} + + ${stop} + + PYTHONPATH=${scriptsDir} ${python3} ${scriptsDir}/awg_inbound.py prepare \ + --spec ${proxyInboundsSpecFile} --awg ${awg} --runtime-dir "$RUNTIME_DIRECTORY" \ + > "$RUNTIME_DIRECTORY/interfaces" + + while read -r _interface implementation config; do + # The 3.1 kernel module drops RandomTrailers packets with ranged H1-H3; userspace does not. + if [[ "$implementation" == userspace ]]; then + WG_QUICK_FORCE_USERSPACE_IMPLEMENTATION=1 \ + WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ + ${awgQuick} up "$config" + else + WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \ + ${awgQuick} up "$config" + fi + done < "$RUNTIME_DIRECTORY/interfaces" + + ${lib.concatStrings ( + lib.mapAttrsToList (name: value: '' + ${pkgs.procps}/bin/sysctl -q -w ${name}=${toString value} + '') sysctl + )} + + # Diverted packets are for the local XRay sockets, whatever their destination. + ${lib.concatMapStrings (family: '' + ${ip} ${family} route replace local default dev lo table ${toString awgInboundRouteTable} + ${ip} ${family} rule add pref ${toString awgInboundRulePriority} fwmark ${toString awgInboundFwmark} table ${toString awgInboundRouteTable} + '') ([ "-4" ] ++ lib.optional ipv6 "-6")} + + ${nft} -f ${nftRulesFile} + ''; +in +{ + services.proxy-suite.internal = { + nftables = true; + packages = [ + awgCfg.toolsPackage + awgCfg.userspacePackage + ]; + kernelModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [ + awgCfg.kernelModulePackage + ]; + inherit sysctl; + firewall = { + # Past the host firewall: diverted packets reach input with their original destination, + # and "proxy" listeners already drop the rest in prerouting. + trustedInterfaces = map (listener: listener.interface) listeners; + # Diverted packets carry a mark whose table has no route back. + extraReversePathFilterRules = lib.concatMapStrings (listener: '' + iifname "${listener.interface}" accept + '') listeners; + }; + + services.${unitName} = { + description = "proxy-suite AmneziaWG inbound interfaces"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + path = [ + awgCfg.toolsPackage + awgCfg.userspacePackage + pkgs.coreutils + pkgs.iproute2 + pkgs.kmod + pkgs.nftables + ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + RuntimeDirectory = unitName; + RuntimeDirectoryMode = "0700"; + StateDirectory = "proxy-suite"; + UMask = "0077"; + ExecStart = start; + ExecStop = stop; + LockPersonality = true; + ProtectClock = true; + ProtectControlGroups = true; + ProtectHostname = true; + ProtectKernelLogs = true; + RestrictRealtime = true; + RestrictSUIDSGID = true; + }; + }; + + # Client configs and links are rendered from the state this unit keeps. + services.proxy-suite-inbounds = { + after = [ "${unitName}.service" ]; + wants = [ "${unitName}.service" ]; + }; + }; +} diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 45dc7a5..79520f8 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -40,25 +40,51 @@ let proxyInboundsSpec = { serverAddress = derived.proxyInboundsCfg.serverAddress; shareLinks = derived.proxyInboundsCfg.shareLinks; - listeners = map (ib: { - inherit (ib) tag; - inherit (ib.listener) - type - port - sharePort - users - flow - method - serverPassword - serverPasswordFile - transport - tls - reality - xrayJson - jsonFile - ; - listen = ib.listener.address; - }) derived.proxyInbounds; + listeners = map ( + ib: + { + inherit (ib) tag; + inherit (ib.listener) + type + port + sharePort + users + flow + method + serverPassword + serverPasswordFile + transport + tls + reality + xrayJson + jsonFile + ; + listen = ib.listener.address; + } + # Only on AmneziaWG listeners: the defaults of the others need not type-check. + // lib.optionalAttrs (ib.listener.type == "amneziawg") { + amneziaWg = + let + runtime = lib.findFirst (awg: awg.tag == ib.tag) null derived.proxyInboundsAwg; + in + { + inherit (ib.listener.amneziaWg) + mode + interfaceName + subnet + subnet6 + privateKeyFile + obfuscation + dns + mtu + persistentKeepalive + clientAllowedIPs + ; + inherit (runtime) internalPort internalListen stateFile; + fwmark = cfg.proxy.tproxy.proxyMark; + }; + } + ) derived.proxyInbounds; }; selectedTemplates = if derived.pureXrayEnabled then xrayTemplates else singBoxTemplates; diff --git a/modules/proxy-suite/core.nix b/modules/proxy-suite/core.nix index d9542fc..cc1c2da 100644 --- a/modules/proxy-suite/core.nix +++ b/modules/proxy-suite/core.nix @@ -157,6 +157,19 @@ in } )) + (lib.mkIf (derived.proxyInboundsEnabled && derived.proxyInboundsAwg != [ ]) ( + import ./amnezia-wg-inbounds.nix { + inherit + lib + pkgs + cfg + derived + ; + inherit (configs) proxyInboundsSpecFile; + inherit (nftr) reservedIpBlock ip nft; + } + )) + (lib.mkIf cfg.amneziaWg.enable ( import ./amnezia-wg.nix { inherit diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 9791aca..bb0c8d9 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -130,7 +130,28 @@ let ob: builtins.elem ob.tag proxyInboundViaChain ) proxyCfg.outbounds; + # AmneziaWG listeners: the interface's TCP and UDP is diverted to a loopback XRay inbound, + # one port per listener above the AmneziaWG outbound tunnels (awgTunnelBasePort). + awgInboundBasePort = 18700; + proxyInboundsAwg = lib.imap0 ( + index: ib: + let + awg = ib.listener.amneziaWg; + in + { + inherit (ib) tag via; + inherit (ib.listener) port; + inherit (awg) mode subnet subnet6; + interface = awg.interfaceName; + internalPort = awgInboundBasePort + index; + # Dual-stack when the clients have IPv6, so one inbound takes both families. + internalListen = if awg.subnet6 != null then "::" else "127.0.0.1"; + stateFile = "${stateDir}/awg-inbounds/${ib.tag}/state.json"; + } + ) (builtins.filter (ib: ib.listener.type == "amneziawg") proxyInbounds); + proxyInboundUdpTypes = [ + "amneziawg" "shadowsocks" "socks" ]; @@ -151,7 +172,9 @@ let l: l.type != null && l.transport.type == "xhttp" && l.tls.enable && l.tls.alpn == [ "h3" ]; proxyInboundFirewallPorts = lib.unique ( map (ib: ib.listener.port) ( - builtins.filter (ib: !proxyInboundIsH3Only ib.listener) proxyInboundsPublic + builtins.filter ( + ib: !proxyInboundIsH3Only ib.listener && ib.listener.type != "amneziawg" + ) proxyInboundsPublic ) ); # A raw-JSON listener could serve anything, so open both protocols for it. @@ -285,6 +308,11 @@ let outboundInventoryFile = "${runtimeDir}/proxy-suite-socks/outbounds.json"; inboundStatsApiPort = 18536; + # Mark and table sending the AmneziaWG listeners' diverted packets to the local stack, + # clear of proxy.tproxy's and perAppRouting's (asserted). + awgInboundFwmark = 20; + awgInboundRouteTable = 103; + awgInboundRulePriority = 8990; # sing-box's fake IP caches, one per TUN config; the start script hands it to the backend. fakeIpCacheDir = "${stateDir}/fakeip"; # Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches. @@ -380,6 +408,7 @@ in proxyInboundsCfg proxyInboundsEnabled proxyInbounds + proxyInboundsAwg proxyInboundsNeedLocalProxy proxyInboundsResolveInSingBox proxyInboundsGuardPrivate diff --git a/modules/proxy-suite/hosts/nixos.nix b/modules/proxy-suite/hosts/nixos.nix index 06a8022..c536ea3 100644 --- a/modules/proxy-suite/hosts/nixos.nix +++ b/modules/proxy-suite/hosts/nixos.nix @@ -59,9 +59,11 @@ in allowedTCPPorts = forward internal.firewall.allowedTCPPorts; allowedUDPPorts = forward internal.firewall.allowedUDPPorts; extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules; + trustedInterfaces = forward internal.firewall.trustedInterfaces; }; boot.extraModulePackages = forward internal.kernelModulePackages; + boot.kernel.sysctl = lib.mapAttrs (_: lib.mkDefault) cfg.internal.sysctl; }) # Off by default since nixpkgs 26.11, and always there before, where the option does diff --git a/modules/proxy-suite/inbound-stats-add.jq b/modules/proxy-suite/inbound-stats-add.jq index f1d019f..b188405 100644 --- a/modules/proxy-suite/inbound-stats-add.jq +++ b/modules/proxy-suite/inbound-stats-add.jq @@ -7,6 +7,11 @@ # back. $online is `statsonlineiplist -all`: each online user's last seen time is kept # in .seen, so an offline user still shows when they were last connected. The last 366 # days are kept. +# +# $awg lists the AmneziaWG listeners' peers ({interface, key, tag, user, rx, tx, handshake, +# endpoint}) with raw interface counters: what grew since the last reading, kept in +# .awgCounters, is added to the user (a counter below the last one restarted with its +# interface). The newest handshake counts as seen, and .awgPeers keeps each user's latest. reduce ($q.stat // [])[] as $s (.; ($s.name | split(">>>")) as $n | if ($n | length) == 4 and ($n[0] | IN("user", "inbound", "outbound")) and $n[2] == "traffic" then @@ -14,5 +19,19 @@ reduce ($q.stat // [])[] as $s (.; else . end) | reduce ($online.users // [])[] as $u (.; .seen[$u.email] = ([.seen[$u.email] // 0, ($u.ips // [])[].lastSeen] | max)) +| (.awgCounters // {}) as $last +| .awgCounters = {} +| .awgPeers = {} +| reduce ($awg // [])[] as $p (.; + ($last[$p.interface][$p.key] // {rx: 0, tx: 0}) as $l + | .days[$day].user[$p.user].up += (if $p.rx >= $l.rx then $p.rx - $l.rx else $p.rx end) + | .days[$day].user[$p.user].down += (if $p.tx >= $l.tx then $p.tx - $l.tx else $p.tx end) + | .awgCounters[$p.interface][$p.key] = {rx: $p.rx, tx: $p.tx} + | if $p.handshake > 0 then + .seen[$p.user] = ([.seen[$p.user] // 0, $p.handshake] | max) + | if $p.handshake >= (.awgPeers[$p.user].handshake // 0) then + .awgPeers[$p.user] = {tag: $p.tag, handshake: $p.handshake, endpoint: $p.endpoint} + else . end + else . end) | .at = $now | .days = ((.days // {}) | with_entries(select(.key >= ($now - 366 * 86400 | strftime("%Y-%m-%d"))))) diff --git a/modules/proxy-suite/nftables.nix b/modules/proxy-suite/nftables.nix index 042d2cb..a773307 100644 --- a/modules/proxy-suite/nftables.nix +++ b/modules/proxy-suite/nftables.nix @@ -163,6 +163,7 @@ let in { inherit + reservedIpBlock nftablesRulesFile perAppTproxyRulesFile perAppZapretRulesFile diff --git a/modules/proxy-suite/options/host.nix b/modules/proxy-suite/options/host.nix index 6bedb6c..201c664 100644 --- a/modules/proxy-suite/options/host.nix +++ b/modules/proxy-suite/options/host.nix @@ -68,7 +68,10 @@ in allowedTCPPorts = internalOption (types.listOf types.port) [ ]; allowedUDPPorts = internalOption (types.listOf types.port) [ ]; extraReversePathFilterRules = internalOption types.lines ""; + trustedInterfaces = internalOption (types.listOf types.str) [ ]; }; + # Kernel parameters the services also set when they start. + sysctl = internalOption (types.attrsOf types.int) { }; kernelModulePackages = internalOption (types.listOf types.package) [ ]; }; } diff --git a/modules/proxy-suite/options/inbounds.nix b/modules/proxy-suite/options/inbounds.nix index 0b0d358..cc02b08 100644 --- a/modules/proxy-suite/options/inbounds.nix +++ b/modules/proxy-suite/options/inbounds.nix @@ -104,6 +104,13 @@ in shortIds = [ "0123abcd" ]; }; }; + # `proxy-ctl inbounds link home phone` prints a vpn:// link; add --config for the .conf. + home = { + type = "amneziawg"; + port = 51820; + users = [ { name = "phone"; } { name = "laptop"; } ]; + amneziaWg.mode = "lan"; + }; } ''; }; diff --git a/modules/proxy-suite/options/types/amnezia-wg.nix b/modules/proxy-suite/options/types/amnezia-wg.nix index 3a5a265..22032a5 100644 --- a/modules/proxy-suite/options/types/amnezia-wg.nix +++ b/modules/proxy-suite/options/types/amnezia-wg.nix @@ -330,5 +330,5 @@ let ); in { - inherit profileType; + inherit profileType obfuscationType; } diff --git a/modules/proxy-suite/options/types/inbounds.nix b/modules/proxy-suite/options/types/inbounds.nix index 01ed0a4..5b22fda 100644 --- a/modules/proxy-suite/options/types/inbounds.nix +++ b/modules/proxy-suite/options/types/inbounds.nix @@ -2,6 +2,7 @@ let inherit (lib) mkOption types; + inherit (import ./amnezia-wg.nix { inherit lib; }) obfuscationType; nullStr = description: example: mkOption { @@ -22,9 +23,104 @@ let uuidFile = nullStr "Runtime path to the UUID." "/run/secrets/proxy-inbound-uuid"; password = nullStr "Password (trojan, shadowsocks, socks, http). Ends up in the Nix store; prefer passwordFile." "hunter2"; passwordFile = nullStr "Runtime path to the password." "/run/secrets/proxy-inbound-password"; + + publicKey = nullStr '' + AmneziaWG public key of a peer that keeps its private key to itself. It gets no client + config or link. Null generates a key pair, kept in the state directory. + '' "jNXH..."; + privateKeyFile = nullStr "Runtime path to the AmneziaWG client private key, instead of a generated one." "/run/secrets/awg-phone-key"; + presharedKeyFile = nullStr "Runtime path to the AmneziaWG preshared key, instead of a generated one." "/run/secrets/awg-phone-psk"; + address = nullStr '' + AmneziaWG tunnel IPv4 address, inside amneziaWg.subnet. Null takes the lowest free one, which + the user keeps for as long as it exists. + '' "10.66.0.10"; }; }; + # The listener's tag names the default interface; a submodule's own name is its option's. + mkAmneziaWgType = + tag: + types.submodule { + options = { + mode = mkOption { + type = types.enum [ + "proxy" + "lan" + ]; + default = "proxy"; + description = '' + What clients reach besides the internet, which they reach the listener's `via` way either way: + - "proxy": nothing else. This host, its private networks and the other peers are cut off. + - "lan": also this host, its private networks and the other peers, directly (masqueraded + behind this host), not through `via`. It turns on IP forwarding. + Only TCP and UDP can follow `via`: anything else to the internet (ping) is dropped. + ''; + }; + + interfaceName = mkOption { + type = types.strMatching "^[A-Za-z0-9_.-]+$"; + default = "awgi-${tag}"; + defaultText = lib.literalExpression ''"awgi-"''; + description = "Linux interface name. It must fit Linux's 15-character limit."; + }; + + subnet = mkOption { + type = types.strMatching "[0-9.]+/[0-9]+"; + default = "10.66.0.0/24"; + description = '' + Tunnel IPv4 subnet, private and unused elsewhere. This host takes the first address, clients + the rest. + ''; + }; + + subnet6 = nullStr '' + Tunnel IPv6 subnet (ULA), laid out as subnet. Null keeps the tunnel IPv4-only. With mode = "lan" + it turns on IPv6 forwarding, which stops this host configuring itself from router advertisements. + '' "fd66:66::/64"; + + privateKeyFile = nullStr "Runtime path to the server private key, instead of a generated one." "/run/secrets/awg-server-key"; + + obfuscation = mkOption { + type = obfuscationType; + default = { }; + description = '' + Obfuscation parameters, shared with every client. Jc, Jmin, Jmax, S1, S2 and H1-H4 left + null are generated once and kept in the state directory; the rest stay unset. + ''; + }; + + dns = mkOption { + type = types.listOf types.str; + default = [ + "1.1.1.1" + "1.0.0.1" + ]; + description = "DNS servers in client configs. Queries leave like any other traffic."; + }; + + mtu = mkOption { + type = types.nullOr types.ints.unsigned; + default = null; + description = "Interface MTU, on both ends. Null leaves awg-quick's (1280 with AWG 3 fields)."; + }; + + persistentKeepalive = mkOption { + type = types.nullOr types.ints.unsigned; + default = 25; + description = "PersistentKeepalive in client configs, which keeps NAT mappings open."; + }; + + clientAllowedIPs = mkOption { + type = types.listOf types.str; + default = [ + "0.0.0.0/0" + "::/0" + ]; + description = "AllowedIPs in client configs: what clients send through the tunnel."; + }; + }; + }; + transportType = types.submodule { options = { type = mkOption { @@ -154,101 +250,115 @@ let }; }; - inboundType = types.submodule { - options = { - type = mkOption { - type = types.nullOr ( - types.enum [ - "vless" - "vmess" - "trojan" - "shadowsocks" - "socks" - "http" - ] - ); - default = null; - description = "Protocol. Set exactly one of type, xrayJson, or jsonFile."; - example = "vless"; - }; + inboundType = types.submodule ( + { name, ... }: + { + options = { + type = mkOption { + type = types.nullOr ( + types.enum [ + "vless" + "vmess" + "trojan" + "shadowsocks" + "socks" + "http" + "amneziawg" + ] + ); + default = null; + description = '' + Protocol. Set exactly one of type, xrayJson, or jsonFile. "amneziawg" is an AmneziaWG + server on UDP port, with its own interface (see amneziaWg); its traffic is handed to XRay + and leaves like any other listener's. + ''; + example = "vless"; + }; - port = mkOption { - type = types.port; - default = 443; - description = "Bound port. A raw-JSON listener's port must match it: the firewall and the port checks go by this one."; - }; + port = mkOption { + type = types.port; + default = 443; + description = "Bound port. A raw-JSON listener's port must match it: the firewall and the port checks go by this one."; + }; - sharePort = mkOption { - type = types.nullOr types.port; - default = null; - description = "Port share links advertise, when something in front owns the public port. Null uses port."; - example = 443; - }; + sharePort = mkOption { + type = types.nullOr types.port; + default = null; + description = "Port share links advertise, when something in front owns the public port. Null uses port."; + example = 443; + }; - address = mkOption { - type = types.strMatching "[^[:space:]]+"; - default = "::"; - description = "Bound address. A loopback address keeps the port closed in the firewall."; - example = "127.0.0.1"; - }; + address = mkOption { + type = types.strMatching "[^[:space:]]+"; + default = "::"; + description = "Bound address. A loopback address keeps the port closed in the firewall."; + example = "127.0.0.1"; + }; - via = nullStr "Egress, as in inbounds.routing.via. Null inherits it." "nl-vps"; + via = nullStr "Egress, as in inbounds.routing.via. Null inherits it." "nl-vps"; - users = mkOption { - type = types.listOf userType; - default = [ ]; - description = "Accepted accounts."; - example = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]; - }; + users = mkOption { + type = types.listOf userType; + default = [ ]; + description = "Accepted accounts."; + example = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]; + }; - flow = mkOption { - type = types.nullOr (types.enum [ "xtls-rprx-vision" ]); - default = null; - description = "VLESS flow; raw transport only."; - example = "xtls-rprx-vision"; - }; + flow = mkOption { + type = types.nullOr (types.enum [ "xtls-rprx-vision" ]); + default = null; + description = "VLESS flow; raw transport only."; + example = "xtls-rprx-vision"; + }; - method = mkOption { - type = types.str; - default = "2022-blake3-aes-128-gcm"; - description = "Shadowsocks cipher. 2022 ciphers take a base64 key of matching length as password; more than one user needs a 2022-blake3-aes cipher and serverPassword."; - example = "aes-128-gcm"; - }; + method = mkOption { + type = types.str; + default = "2022-blake3-aes-128-gcm"; + description = "Shadowsocks cipher. 2022 ciphers take a base64 key of matching length as password; more than one user needs a 2022-blake3-aes cipher and serverPassword."; + example = "aes-128-gcm"; + }; - serverPassword = nullStr "Server key of a multi-user shadowsocks 2022 listener, shared by its users. Ends up in the Nix store; prefer serverPasswordFile." "c2VydmVyLWtleS0xNmJ5dGU="; - serverPasswordFile = nullStr "Runtime path to the server key." "/run/secrets/proxy-inbound-ss-server-key"; + serverPassword = nullStr "Server key of a multi-user shadowsocks 2022 listener, shared by its users. Ends up in the Nix store; prefer serverPasswordFile." "c2VydmVyLWtleS0xNmJ5dGU="; + serverPasswordFile = nullStr "Runtime path to the server key." "/run/secrets/proxy-inbound-ss-server-key"; - transport = mkOption { - type = transportType; - default = { }; - description = "Stream transport."; - }; + transport = mkOption { + type = transportType; + default = { }; + description = "Stream transport."; + }; - tls = mkOption { - type = tlsType; - default = { }; - description = "TLS termination."; - }; + tls = mkOption { + type = tlsType; + default = { }; + description = "TLS termination."; + }; - reality = mkOption { - type = realityType; - default = { }; - description = "REALITY."; - }; + reality = mkOption { + type = realityType; + default = { }; + description = "REALITY."; + }; - xrayJson = mkOption { - type = types.nullOr types.attrs; - default = null; - description = "Raw XRay inbound, built into the store; tag is overridden and port, if left out, filled in."; - example = { - protocol = "dokodemo-door"; - settings.port = 8080; + xrayJson = mkOption { + type = types.nullOr types.attrs; + default = null; + description = "Raw XRay inbound, built into the store; tag is overridden and port, if left out, filled in."; + example = { + protocol = "dokodemo-door"; + settings.port = 8080; + }; + }; + + jsonFile = nullStr "Runtime path to a raw XRay inbound (no share link); tag is overridden and port, if left out, filled in." "/run/secrets/proxy-inbound-vless.json"; + + amneziaWg = mkOption { + type = mkAmneziaWgType name; + default = { }; + description = ''The AmneziaWG server of a type = "amneziawg" listener.''; }; }; - - jsonFile = nullStr "Runtime path to a raw XRay inbound (no share link); tag is overridden and port, if left out, filled in." "/run/secrets/proxy-inbound-vless.json"; - }; - }; + } + ); in { inherit inboundType; diff --git a/modules/proxy-suite/rules/proxy-inbounds.nix b/modules/proxy-suite/rules/proxy-inbounds.nix index 092aeba..88e2fe5 100644 --- a/modules/proxy-suite/rules/proxy-inbounds.nix +++ b/modules/proxy-suite/rules/proxy-inbounds.nix @@ -36,9 +36,10 @@ let # Only the ports clients dial there: the rest of this host (wildcard services the # firewall keeps from the internet) must not be reachable through it. serverAddressPorts = lib.unique ( - map ( - ib: if ib.listener.sharePort != null then ib.listener.sharePort else ib.listener.port - ) proxyInbounds + map (ib: if ib.listener.sharePort != null then ib.listener.sharePort else ib.listener.port) ( + # AmneziaWG is UDP to the interface, never relayed through XRay. + builtins.filter (ib: ib.listener.type != "amneziawg") proxyInbounds + ) ++ lib.optionals proxyInboundsCfg.subscriptions.enable [ 80 443 diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 6bc9a63..a5aef6b 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -71,7 +71,10 @@ let ++ lib.concatMap (ob: [ ob.tunnelPort ob.directPort - ]) derived.awgTunnelOutbounds; + ]) derived.awgTunnelOutbounds + ++ lib.optionals derived.proxyInboundsEnabled ( + map (listener: listener.internalPort) derived.proxyInboundsAwg + ); # A rootless host (home-manager, nix-on-droid) runs everything as the user: nothing # that programs routing, firewalls or interfaces, and no privileged ports. @@ -392,10 +395,11 @@ let !proxyInboundsEnabled || !lib.any (port: builtins.elem port derived.proxyInboundPorts) ( [ derived.constants.inboundStatsApiPort ] + ++ map (listener: listener.internalPort) derived.proxyInboundsAwg ++ builtins.attrValues derived.constants.xrayDnsBridgePorts ) ) - "proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the inbounds' stats API on ${toString derived.constants.inboundStatsApiPort}, or 18533-18535)" + "proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the inbounds' stats API on ${toString derived.constants.inboundStatsApiPort}, the AmneziaWG listeners' loopback inbounds from 18700, or 18533-18535)" ) # The prober opens one loopback listener per exit from probeBasePort; the WARP # and AmneziaWG tunnels open two each from their own bases. They all bind @@ -531,6 +535,142 @@ let ] ) proxyInbounds; + # AmneziaWG listeners run an interface each and give their clients addresses in a subnet. + awgListeners = builtins.filter (ib: ib.listener.type == "amneziawg") proxyInbounds; + awgListenersEnabled = proxyInboundsEnabled && awgListeners != [ ]; + + # "a.b.c.d/n" as { base; size; } (base is the address itself, not yet masked), or null. + parseIPv4 = + value: + let + match = builtins.match "([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})(/([0-9]{1,2}))?" value; + octets = map lib.toInt (lib.take 4 match); + prefix = if builtins.elemAt match 5 == null then 32 else lib.toInt (builtins.elemAt match 5); + in + if match == null || lib.any (octet: octet > 255) octets || prefix > 32 then + null + else + { + base = lib.foldl (acc: octet: acc * 256 + octet) 0 octets; + size = lib.foldl (acc: _: acc * 2) 1 (lib.range 1 (32 - prefix)); + }; + # Same network once both are cut down to the larger of the two. + ipv4Overlap = + a: b: + let + size = lib.max a.size b.size; + in + a.base / size == b.base / size; + + awgInterfaces = + map (ib: ib.listener.amneziaWg.interfaceName) awgListeners + ++ lib.optionals cfg.amneziaWg.enable ( + lib.mapAttrsToList (_: profile: profile.interfaceName) cfg.amneziaWg.profiles + ); + otherInterfaces = + lib.optional (proxyEnabled && globalTun.enable) globalTun.interface + ++ lib.optional (perAppRoutingCfg.enable && perAppRoutingTun.enable) perAppRoutingTun.interface; + + awgInboundAssertions = [ + (rootlessForbids awgListenersEnabled "an AmneziaWG listener in inbounds.listeners") + (uniqueValues awgListenersEnabled awgInterfaces + "proxy-suite: AmneziaWG inbounds listeners and amneziaWg.profiles must each use a distinct interfaceName" + ) + (mkAssertion (!awgListenersEnabled || !lib.any (name: builtins.elem name otherInterfaces) awgInterfaces) + "proxy-suite: an AmneziaWG inbounds listener's interfaceName is taken by proxy.tun or perAppRouting.tun" + ) + (mkAssertion + ( + !awgListenersEnabled + || lib.all ( + ib: + lib.all (other: ib.tag == other.tag || !ipv4Overlap ib.subnet other.subnet) awgSubnets + ) awgSubnets + ) + "proxy-suite: AmneziaWG inbounds listeners must each use a subnet of their own" + ) + (mkAssertion + ( + !awgListenersEnabled + || !builtins.elem derived.constants.awgInboundFwmark ( + [ + globalTproxy.fwmark + globalTproxy.proxyMark + ] + ++ lib.optional perAppRoutingTun.enable perAppRoutingTun.fwmark + ++ lib.optional perAppRoutingTproxy.enable perAppRoutingTproxy.fwmark + ++ lib.optional tgWsProxyCfg.enable tgWsProxyCfg.fwmark + ) + ) + "proxy-suite: AmneziaWG inbounds listeners mark their diverted packets with ${toString derived.constants.awgInboundFwmark}, which a proxy.tproxy, perAppRouting or tgWsProxy fwmark also uses" + ) + (mkAssertion + ( + !awgListenersEnabled + || !builtins.elem derived.constants.awgInboundRouteTable ( + [ + globalTproxy.routeTable + derived.constants.tunAutoRouteTableIndex + ] + ++ lib.optional perAppRoutingTun.enable perAppRoutingTun.routeTable + ++ lib.optional perAppRoutingTproxy.enable perAppRoutingTproxy.routeTable + ) + ) + "proxy-suite: AmneziaWG inbounds listeners route with table ${toString derived.constants.awgInboundRouteTable}, which proxy.tproxy.routeTable or a perAppRouting routeTable also uses" + ) + ] + ++ lib.concatMap ( + ib: + let + l = ib.listener; + awg = l.amneziaWg; + prefix = "proxy-suite: inbounds listener '${ib.tag}'"; + subnet = parseIPv4 awg.subnet; + addresses = builtins.filter (address: address != null) (map (user: user.address) l.users); + inSubnet = + address: + let + parsed = parseIPv4 address; + offset = parsed.base - parsed.base / subnet.size * subnet.size; + in + parsed != null + && parsed.size == 1 + && ipv4Overlap parsed subnet + && !builtins.elem offset [ + 0 + 1 + (subnet.size - 1) + ]; + in + lib.optionals (proxyInboundsEnabled && l.type == "amneziawg") [ + (mkAssertion (lib.all (user: user.name != "") l.users) + "${prefix}: AmneziaWG users each need a name, which their keys and address are kept under" + ) + (mkAssertion ( + builtins.stringLength awg.interfaceName <= 15 + ) "${prefix}: amneziaWg.interfaceName '${awg.interfaceName}' is longer than the kernel's 15 characters") + (mkAssertion ( + !l.tls.enable && !l.reality.enable && l.flow == null && l.transport.type == "raw" + ) "${prefix}: AmneziaWG takes no tls, reality, flow or transport") + (mkAssertion (subnet != null && subnet.size >= 4) + "${prefix}: amneziaWg.subnet '${awg.subnet}' must be an IPv4 CIDR of /30 or wider" + ) + (mkAssertion (subnet == null || lib.all inSubnet addresses) + "${prefix}: each user address must be a host address inside amneziaWg.subnet, other than its first (this host's)" + ) + (uniqueValues true addresses "${prefix}: users must each have a distinct address") + (mkAssertion (lib.all ( + user: user.publicKey == null || user.privateKeyFile == null + ) l.users) "${prefix}: a user sets publicKey or privateKeyFile, not both") + ] + ) awgListeners; + awgSubnets = builtins.filter (entry: entry.subnet != null) ( + map (ib: { + inherit (ib) tag; + subnet = parseIPv4 ib.listener.amneziaWg.subnet; + }) awgListeners + ); + subscriptionAssertions = lib.concatMap (sub: [ (exactlyOneOf proxyEnabled [ sub.urlFile @@ -796,6 +936,7 @@ rootlessAssertions ++ secretAssertions ++ outboundAssertions ++ proxyInboundAssertions +++ awgInboundAssertions ++ subscriptionAssertions ++ collisionAssertions ++ positiveNumberAssertions diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 64f3bb4..d04e304 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -53,6 +53,7 @@ let awgOutbounds proxyInboundsCfg proxyInboundsEnabled + proxyInboundsAwg proxyInboundsNeedLocalProxy proxyInboundsGuardPrivate proxyInboundViaOutbounds @@ -70,6 +71,7 @@ let headBin = "${pkgs.coreutils}/bin/head"; seqBin = "${pkgs.coreutils}/bin/seq"; findBin = "${pkgs.findutils}/bin/find"; + awgBin = "${cfg.amneziaWg.toolsPackage}/bin/awg"; # `proxy-ctl awg` toggles global profiles; outbound ones always run and show up with the proxy. amneziaWgProfileNamesFile = pkgs.writeText "proxy-suite-core" ( builtins.toJSON ( @@ -130,6 +132,8 @@ let ; inherit proxyInboundsCfg + proxyInboundsAwg + awgBin proxyInboundsNeedLocalProxy proxyInboundsGuardPrivate proxyInboundViaOutbounds diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index 64b1453..6b74083 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -5,6 +5,8 @@ pkgs, proxyCfg, proxyInboundsCfg, + proxyInboundsAwg, + awgBin, proxyInboundsNeedLocalProxy, proxyInboundViaOutbounds, userControlCfg, @@ -29,8 +31,10 @@ let subscriptionsFile = "${runtimeDir}/subscriptions.json"; subsCfg = proxyInboundsCfg.subscriptions; xray = "${proxyInboundsCfg.package}/bin/xray"; - # Only listeners: no marks, no transparent sockets. - runXray = constants.runAsServiceUser pkgs [ "net_bind_service" ]; + # Only listeners, and for AmneziaWG listeners transparent sockets (IP_TRANSPARENT). + runXray = constants.runAsServiceUser pkgs ( + [ "net_bind_service" ] ++ lib.optional (proxyInboundsAwg != [ ]) "net_admin" + ); needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled; @@ -216,9 +220,18 @@ let [ -n "$reading" ] || reading='{}' online=$(${xray} api statsonlineiplist "$api" -all 2> /dev/null) || online="" [ -n "$online" ] || online='{}' + ${ + if proxyInboundsAwg != [ ] then + '' + awg=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${parserScriptsPythonPath}/awg_inbound.py peers \ + --spec ${proxyInboundsSpecFile} --awg ${awgBin}) || awg='[]' + '' + else + "awg='[]'" + } [ -s "$file" ] || echo '{}' > "$file" tmp=$(${pkgs.coreutils}/bin/mktemp "$file.XXXXXX") - ${jq} --argjson q "$reading" --argjson online "$online" \ + ${jq} --argjson q "$reading" --argjson online "$online" --argjson awg "$awg" \ --arg day "$(${pkgs.coreutils}/bin/date +%F)" \ --argjson now "$(${pkgs.coreutils}/bin/date +%s)" \ -f ${ diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 2f5e251..9b707aa 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -29,6 +29,8 @@ perAppTunFile, routeModeRulesFile, proxyInboundsCfg, + proxyInboundsAwg, + awgBin, proxyInboundsNeedLocalProxy, proxyInboundsGuardPrivate, proxyInboundViaOutbounds, @@ -198,6 +200,8 @@ let pkgs proxyCfg proxyInboundsCfg + proxyInboundsAwg + awgBin proxyInboundsNeedLocalProxy proxyInboundViaOutbounds userControlCfg diff --git a/nix/checks.nix b/nix/checks.nix index 10d3a85..57b7960 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -52,6 +52,9 @@ let proxyInboundsRuntime = import ./checks/proxy-inbounds-runtime.nix { inherit pkgs proxySuiteModule; }; + amneziaWgInboundsRuntime = import ./checks/amnezia-wg-inbound-runtime.nix { + inherit pkgs proxySuiteModule; + }; in moduleSuiteChecks // { @@ -62,6 +65,7 @@ moduleSuiteChecks // pkgs.lib.optionalAttrs (system == "x86_64-linux") { amneziawg-runtime = amneziaWgRuntime; proxy-inbounds-runtime = proxyInboundsRuntime; + amneziawg-inbounds-runtime = amneziaWgInboundsRuntime; } // parserChecks // repoChecks diff --git a/nix/checks/amnezia-wg-inbound-runtime.nix b/nix/checks/amnezia-wg-inbound-runtime.nix new file mode 100644 index 0000000..659fbf7 --- /dev/null +++ b/nix/checks/amnezia-wg-inbound-runtime.nix @@ -0,0 +1,213 @@ +{ + pkgs, + proxySuiteModule, +}: + +let + # Clients reach the server on VLAN 1, and nothing else but through it. Public addresses: + # private destinations never reach XRay. + serverAddress = "11.0.0.1"; + # VLAN 2: the internet, as seen from the server, and the server's LAN in one. + serverUplink = "11.0.1.1"; + outsideAddress = "11.0.1.3"; + serverLanAddress = "192.168.2.1"; + lanAddress = "192.168.2.2"; + + # Forced: the test driver's own 192.168.. addresses would share subnets. + network = interface: addresses: { + networking.useDHCP = false; + networking.interfaces.${interface}.ipv4.addresses = pkgs.lib.mkForce ( + map (address: { + inherit address; + prefixLength = 24; + }) addresses + ); + }; + + users = names: map (name: { inherit name; }) names; + + # Each client imports what the server hands out: the .conf, or the vpn:// link. + client = + address: + { ... }: + { + imports = [ + proxySuiteModule + (network "eth1" [ address ]) + ]; + services.proxy-suite = { + enable = true; + amneziaWg = { + enable = true; + # The server covers the kernel module. + kernelModulePackage = null; + profiles.home = { + interfaceName = "awg-home"; + configFile = "/run/awg/home.conf"; + }; + profiles.roam = { + interfaceName = "awg-roam"; + vpnFile = "/run/awg/roam.vpn"; + }; + }; + }; + }; +in +pkgs.testers.runNixOSTest { + name = "proxy-suite-amneziawg-inbounds-runtime"; + + nodes = { + server = + { ... }: + { + imports = [ + proxySuiteModule + (network "eth1" [ serverAddress ]) + (network "eth2" [ + serverUplink + serverLanAddress + ]) + ]; + virtualisation.vlans = [ + 1 + 2 + ]; + + services.proxy-suite = { + enable = true; + proxy.enable = false; + inbounds = { + enable = true; + inherit serverAddress; + routing.via = "direct"; + openFirewall = true; + listeners.home = { + type = "amneziawg"; + port = 51820; + users = users [ + "phone" + "laptop" + ]; + amneziaWg = { + mode = "lan"; + subnet6 = "fd66:66::/64"; + dns = [ ]; + }; + }; + listeners.roam = { + type = "amneziawg"; + port = 51821; + users = users [ + "tablet" + "watch" + ]; + amneziaWg = { + subnet = "10.67.0.0/24"; + dns = [ ]; + }; + }; + }; + }; + environment.systemPackages = [ pkgs.jq ]; + }; + + # The internet and the server's LAN in one: a web server answering with the caller's address. + outside = + { ... }: + { + imports = [ + (network "eth1" [ + outsideAddress + lanAddress + ]) + ]; + virtualisation.vlans = [ 2 ]; + services.nginx = { + enable = true; + virtualHosts.default = { + default = true; + locations."/".return = "200 '$remote_addr'"; + }; + }; + networking.firewall.allowedTCPPorts = [ 80 ]; + }; + + alice = client "11.0.0.2"; + bob = client "11.0.0.4"; + }; + + testScript = '' + start_all() + server.wait_for_unit("proxy-suite-inbounds-awg.service") + server.wait_for_unit("proxy-suite-inbounds.service") + outside.wait_for_unit("nginx.service") + + def import_profiles(machine, home_user, roam_user): + home = server.succeed(f"proxy-ctl inbounds link home {home_user} --config") + roam = server.succeed(f"proxy-ctl inbounds link roam {roam_user}").strip() + assert roam.startswith("vpn://"), roam + machine.succeed("mkdir -p -m 700 /run/awg") + machine.succeed(f"cat > /run/awg/home.conf <<'EOF'\n{home}\nEOF") + machine.succeed(f"echo '{roam}' > /run/awg/roam.vpn") + + def fetch(machine, host): + return machine.succeed(f"curl -sS --fail --max-time 10 http://{host}/").strip() + + # XRay dials out, so the web server sees the server. + def through_server(machine, timeout=60): + machine.wait_until_succeeds( + "test \"$(curl -sS --fail --max-time 10 http://${outsideAddress}/)\" = ${serverUplink}", + timeout=timeout, + ) + + with subtest("state and links are generated"): + server.succeed("test $(stat -c %a /var/lib/proxy-suite/awg-inbounds/home/state.json) = 600") + server.succeed("ip link show awgi-home") + server.succeed("ip link show awgi-roam") + server.succeed("nft list table inet proxy_suite_awg_inbounds") + server.succeed("test $(jq '[.[] | select(.type == \"amneziawg\")] | length' /run/proxy-suite-inbounds/links.json) = 4") + server.succeed("test -n \"$(proxy-ctl inbounds link home phone --config --qr)\"") + import_profiles(alice, "phone", "tablet") + import_profiles(bob, "laptop", "watch") + + with subtest("lan: the internet through the listener's routing"): + for machine in (alice, bob): + machine.succeed("systemctl start proxy-suite-awg-home.service") + through_server(alice) + # Nothing but TCP and UDP can follow via. + alice.fail("ping -c 2 -W 2 ${outsideAddress}") + + with subtest("lan: this host, its LAN and the other peers"): + alice.succeed("ping -c 2 -W 2 10.66.0.1") + alice.succeed("ping -c 2 -W 2 ${serverLanAddress}") + # Masqueraded, so the LAN needs no route back. + assert fetch(alice, "${lanAddress}") == "${serverLanAddress}" + bob_address = bob.succeed("ip -4 -o addr show awg-home | awk '{print $4}' | cut -d/ -f1").strip() + alice.succeed(f"ping -c 2 -W 2 {bob_address}") + alice.succeed("ping -6 -c 2 -W 2 fd66:66::1") + + with subtest("usage and presence are recorded"): + server.succeed("proxy-ctl inbounds online | grep phone | grep -q online") + server.succeed("proxy-ctl inbounds online | grep laptop | grep -q online") + server.succeed("proxy-ctl inbounds stats --by user | grep -q phone") + + with subtest("proxy: nothing but the internet"): + for machine in (alice, bob): + machine.succeed("systemctl start proxy-suite-awg-roam.service") + machine.fail("ip link show awg-home") + through_server(alice) + alice.fail("ping -c 2 -W 2 10.67.0.1") + alice.fail("curl -sS --fail --max-time 5 http://${lanAddress}/") + alice.fail("ping -c 2 -W 2 ${serverLanAddress}") + bob_address = bob.succeed("ip -4 -o addr show awg-roam | awk '{print $4}' | cut -d/ -f1").strip() + alice.fail(f"ping -c 2 -W 2 {bob_address}") + server.succeed("proxy-ctl inbounds online | grep tablet | grep -q online") + + with subtest("keys survive a restart"): + before = server.succeed("jq -S .users /var/lib/proxy-suite/awg-inbounds/roam/state.json") + server.succeed("systemctl restart proxy-suite-inbounds-awg.service") + server.wait_for_unit("proxy-suite-inbounds.service") + assert server.succeed("jq -S .users /var/lib/proxy-suite/awg-inbounds/roam/state.json") == before + through_server(alice, timeout=90) + ''; +} diff --git a/nix/checks/parsers.nix b/nix/checks/parsers.nix index dc25910..17049b6 100644 --- a/nix/checks/parsers.nix +++ b/nix/checks/parsers.nix @@ -45,4 +45,13 @@ python ${../../scripts/test-amneziawg-config.py} touch "$out" ''; + + awg-inbound-state = + pkgs.runCommand "awg-inbound-state-check" { nativeBuildInputs = [ pkgs.python3 ]; } + '' + export PYTHONDONTWRITEBYTECODE=1 + export PYTHONPATH=${../../scripts}:$PYTHONPATH + python ${../../scripts/test-awg-inbound.py} + touch "$out" + ''; } diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index bb6ee95..1e8c52f 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -173,6 +173,59 @@ let listeners.vless-in = realityListener; }; + awgListener = { + type = "amneziawg"; + port = 51820; + users = [ + { name = "phone"; } + { name = "laptop"; } + ]; + }; + awgFixture = mkInbounds { + listeners.vless-in = realityListener; + listeners.home = awgListener // { + amneziaWg = { + mode = "lan"; + subnet6 = "fd66:66::/64"; + }; + }; + listeners.roam = awgListener // { + port = 51821; + amneziaWg.subnet = "10.67.0.0/24"; + }; + }; + awgSpec = mkInboundsSpec awgFixture; + awgSpecListener = tag: lib.head (builtins.filter (l: l.tag == tag) awgSpec.listeners); + awgProxyFixture = mkInbounds { + listeners.roam = awgListener; + }; + readInboundsStart = + fixture: (import ./read-generated.nix).readDerivation (service fixture).serviceConfig.ExecStart; + awgService = fixture: fixture.config.systemd.services."proxy-suite-inbounds-awg"; + awgStartScript = + fixture: (import ./read-generated.nix).readDerivation (awgService fixture).serviceConfig.ExecStart; + # The nft rules file is a writeText the start script names; a writeText that returns its text + # puts the rules into the script itself, readable without import-from-derivation. + awgRules = + fixture: + let + cfg = fixture.config.services.proxy-suite; + nftr = import ../../modules/proxy-suite/nftables.nix { inherit lib pkgs cfg; }; + module = import ../../modules/proxy-suite/amnezia-wg-inbounds.nix { + inherit lib cfg; + pkgs = pkgs // { + writeText = _: text: text; + }; + derived = import ../../modules/proxy-suite/derived.nix { inherit lib cfg; }; + proxyInboundsSpecFile = "/spec.json"; + inherit (nftr) reservedIpBlock; + ip = "ip"; + nft = "nft"; + }; + in + (import ./read-generated.nix).readDerivation + module.services.proxy-suite.internal.services."proxy-suite-inbounds-awg".serviceConfig.ExecStart; + ruleTags = config: map (rule: rule.ruleTag) config.routing.rules; ruleByTag = config: tag: builtins.head (builtins.filter (rule: rule.ruleTag == tag) config.routing.rules); @@ -417,6 +470,43 @@ let }) "collides with proxy.listener.port" ) + + # AmneziaWG listeners. + (mkRejectsListener (awgListener // { tls.enable = true; }) "AmneziaWG takes no tls") + # A long tag makes a long default name. + (mkRejects ( + baseProxy + // { + inbounds = { + enable = true; + listeners.far-too-long = awgListener; + }; + } + ) "is longer than the kernel's 15 characters") + (mkRejectsListener (awgListener // { users = [ { } ]; }) "users each need a name") + (mkRejectsListener ( + awgListener + // { + users = [ + { + name = "a"; + address = "10.66.1.2"; + } + ]; + } + ) "must be a host address inside amneziaWg.subnet") + (mkRejects ( + baseProxy + // { + inbounds = { + enable = true; + listeners.one = awgListener; + listeners.two = awgListener // { + port = 51821; + }; + }; + } + ) "must each use a subnet of their own") ]; assertions = [ @@ -585,6 +675,82 @@ let true ) + # AmneziaWG: the spec carries each listener's loopback inbound, in listener order. + (assert (awgSpecListener "home").amneziaWg.internalPort == 18700; true) + (assert (awgSpecListener "roam").amneziaWg.internalPort == 18701; true) + (assert (awgSpecListener "home").amneziaWg.internalListen == "::"; true) + (assert (awgSpecListener "roam").amneziaWg.internalListen == "127.0.0.1"; true) + (assert (awgSpecListener "home").amneziaWg.fwmark == 2; true) + (assert (awgSpecListener "home").amneziaWg.interfaceName == "awgi-home"; true) + ( + assert + (awgSpecListener "roam").amneziaWg.stateFile == "/var/lib/proxy-suite/awg-inbounds/roam/state.json"; + true + ) + (assert !((awgSpecListener "vless-in") ? amneziaWg); true) + # UDP only, and the interfaces past the host firewall. + (assert awgFixture.config.networking.firewall.allowedTCPPorts == [ 443 ]; true) + ( + assert + lib.sort lib.lessThan awgFixture.config.networking.firewall.allowedUDPPorts == [ + 51820 + 51821 + ]; + true + ) + ( + assert builtins.elem "awgi-home" awgFixture.config.networking.firewall.trustedInterfaces; + assert builtins.elem "awgi-roam" awgFixture.config.networking.firewall.trustedInterfaces; + true + ) + ( + assert + lib.hasInfix ''iifname "awgi-home" accept'' awgFixture.config.networking.firewall.extraReversePathFilterRules; + true + ) + # The interfaces come up before XRay renders their links. + (assert builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).after; true) + (assert builtins.elem "proxy-suite-inbounds-awg.service" (service awgFixture).wants; true) + (assert !(relayFixture.config.systemd.services ? "proxy-suite-inbounds-awg"); true) + ( + assert lib.hasInfix "rule add pref 8990 fwmark 20 table 103" (awgStartScript awgFixture); + assert lib.hasInfix "awg_inbound.py prepare" (awgStartScript awgFixture); + true + ) + # IPv6 routing only where a listener has IPv6. + (assert lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgFixture); true) + (assert !lib.hasInfix "-6 rule add pref 8990" (awgStartScript awgProxyFixture); true) + # Transparent sockets only where there is something to divert. + ( + assert lib.hasInfix "net_admin" (readInboundsStart awgFixture); + assert !lib.hasInfix "net_admin" (readInboundsStart relayFixture); + true + ) + # Forwarding only for "lan" listeners. + (assert awgFixture.config.boot.kernel.sysctl."net.ipv4.ip_forward" == 1; true) + (assert awgFixture.config.boot.kernel.sysctl."net.ipv6.conf.all.forwarding" == 1; true) + (assert !(awgProxyFixture.config.services.proxy-suite.internal.sysctl ? "net.ipv4.ip_forward"); true) + # "lan" clients reach private networks and each other natively, "proxy" clients nothing but via. + ( + let + rules = awgRules awgFixture; + in + assert lib.hasInfix "ip daddr $RESERVED_IP return" rules; + assert lib.hasInfix "ip daddr 192.168.0.0/16 return" rules; + assert lib.hasInfix "ip daddr 192.168.0.0/16 drop" rules; + assert lib.hasInfix "ip daddr 10.67.0.0/24 drop" rules; + assert lib.hasInfix "ip6 daddr fd66:66::/64 return" rules; + assert lib.hasInfix "tproxy ip to 127.0.0.1:18700 meta mark set 20 accept" rules; + assert lib.hasInfix "tproxy ip6 to [::1]:18700 meta mark set 20 accept" rules; + assert !lib.hasInfix "tproxy ip6 to [::1]:18701" rules; + assert lib.hasInfix ''iifname "awgi-roam" jump listener_1'' rules; + assert lib.hasInfix "th dport { 18700, 18701 } fib daddr type local drop" rules; + assert lib.hasInfix ''ip saddr 10.66.0.0/24 oifname != "awgi-home" masquerade'' rules; + assert !lib.hasInfix "10.67.0.0/24 oifname" rules; + true + ) + (assert !lib.hasInfix "masquerade" (awgRules awgProxyFixture); true) + ] ++ failing; in diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index d5bfcdb..dba44ad 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -640,7 +640,7 @@ '' add=${../../modules/proxy-suite/inbound-stats-add.jq} now=1789135690 # 2026-09-11 - a() { jq -c --argjson q "$1" --argjson online "''${3:-{\}}" --arg day 2026-09-11 --argjson now "$now" -f "$add" <<<"$2"; } + a() { jq -c --argjson q "$1" --argjson online "''${3:-{\}}" --argjson awg "''${4:-[]}" --arg day 2026-09-11 --argjson now "$now" -f "$add" <<<"$2"; } # XRay gives values as strings and leaves a zero counter without one. r='{"stat":[{"name":"user>>>fufsob>>>traffic>>>downlink","value":"3000000"}, @@ -665,6 +665,20 @@ old="$(jq -c '.days["2024-01-01"] = {user: {fufsob: {up: 1}}}' <<<"$s")" jq -e '.days["2024-01-01"] == null' <<<"$(a '{}' "$old")" > /dev/null + # AmneziaWG peers come with raw interface counters, of which only the growth is added. + p() { echo '[{"interface":"awgi-home","key":"K","tag":"home","user":"tablet","rx":'"$1"',"tx":'"$2"',"handshake":'"$3"',"endpoint":"203.0.113.9:4000"}]'; } + s="$(a '{}' "$s" '{}' "$(p 1000 5000 1789135500)")" + jq -e '.days["2026-09-11"].user.tablet == {up: 1000, down: 5000} and .seen.tablet == 1789135500 + and .awgPeers.tablet == {tag: "home", handshake: 1789135500, endpoint: "203.0.113.9:4000"}' <<<"$s" > /dev/null + s="$(a '{}' "$s" '{}' "$(p 1500 5200 1789135600)")" + jq -e '.days["2026-09-11"].user.tablet == {up: 1500, down: 5200} and .seen.tablet == 1789135600' <<<"$s" > /dev/null + # A counter below the last one restarted with its interface. + s="$(a '{}' "$s" '{}' "$(p 100 100 0)")" + jq -e '.days["2026-09-11"].user.tablet == {up: 1600, down: 5300} and .seen.tablet == 1789135600 + and .awgPeers == {}' <<<"$s" > /dev/null + # A peer gone from the listeners leaves no counters behind. + jq -e '.awgCounters == {}' <<<"$(a '{}' "$s")" > /dev/null + touch "$out" ''; diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 5ab4e93..1853132 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -102,6 +102,8 @@ Secrets and changes need root, or the userControl group. inbounds [list] server inbounds inbounds link [user] [--qr|--json] client share link, or the client's outbound JSON + inbounds link [user] --config [--qr] + an AmneziaWG client's .conf, or its QR code inbounds link --server-json the server's inbound JSON inbounds sub [user] [--qr] subscription users, or one user's URL inbounds stats [days] [--by user|inbound|outbound] @@ -494,7 +496,12 @@ COMPLETE = { "inbounds stats": {"flags": {"--by": "user, inbound or outbound"}}, "inbounds link": { "args": _inbound_link_choices, - "flags": {"--qr": "print a QR code", "--json": "the client's outbound JSON", "--server-json": "the server's inbound JSON"}, + "flags": { + "--qr": "print a QR code", + "--json": "the client's outbound JSON", + "--config": "an AmneziaWG client's .conf", + "--server-json": "the server's inbound JSON", + }, }, "inbounds sub": { "args": lambda: _names(_s(x["user"]) for x in read_json(env("INBOUNDS_SUBS_FILE"))), @@ -2536,11 +2543,16 @@ def _inbound_link_for(tag, user="", *_, field="link"): for x in matches: print(f" {_s(x.get('user'))}", file=sys.stderr) sys.exit(1) + entry = matches[0] if field == "link": - return _s(matches[0].get("link")) - if matches[0].get(field) is None: - die(f"No client JSON for {tag}: proxy-suite cannot parse its link.") - return matches[0][field] + return _s(entry.get("link")) + if entry.get(field) is not None: + return entry[field] + if field == "config": + die(f"No client config for {tag}: only AmneziaWG listeners have one - use the link.") + if entry.get("type") == "amneziawg": + die(f"No client JSON for {tag}: AmneziaWG clients take a config - use --config.") + die(f"No client JSON for {tag}: proxy-suite cannot parse its link.") def _human_bytes(b): @@ -2608,6 +2620,9 @@ def _inbound_stats(*args): print(total.format(name, _human_bytes(down), _human_bytes(up))) +AWG_ONLINE_SECONDS = 180 + + def _inbound_presence(): """user -> (state, addresses): "online", "seen