feat: awg inbounds

This commit is contained in:
FUFSoB committed 2026-09-17 15:19:30 +05:00
1 parent 3b568bb54e
commit ffc7816289
31 files changed
+2876 -133

No files matched your search

+5 -3
View File
@@ -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 <tag> [user] [--qr|--json]
client share link, or the client's outbound JSON
inbounds link <tag> [user] --config [--qr]
an AmneziaWG client's .conf, or its QR code
inbounds link <tag> --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]
+680 -4
View File
@@ -10,6 +10,43 @@ Part of the [proxy-suite options reference](./index.md).
- [listeners](#services-proxy-suite-inbounds-listeners)
- `<name>`
- [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";
};
}
```
````
<a id="services-proxy-suite-inbounds-listeners-name-address"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.address
@@ -158,6 +206,550 @@ string matching the pattern \[^\[:space:]]+
"127.0.0.1"
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg
The AmneziaWG server of a type = “amneziawg” listener\.
*Type:*
submodule
*Default:*
```nix
{ }
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-clientallowedips"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.clientAllowedIPs
AllowedIPs in client configs: what clients send through the tunnel\.
*Type:*
list of string
*Default:*
```nix
[
"0.0.0.0/0"
"::/0"
]
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-dns"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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"
]
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-interfacename"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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-<tag>"
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-mode"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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"
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-mtu"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
{ }
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-contentpaddingaddition"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-disablecookies"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.disableCookies
AWG 3 cookie suppression (DisableCookies)\.
*Type:*
null or boolean
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-h1"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-h2"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-h3"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-h4"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-headerprotectionkey"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.headerProtectionKey
Inline AWG 3 header-protection key\. Prefer headerProtectionKeyFile\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-headerprotectionkeyfile"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.headerProtectionKeyFile
Runtime path containing the AWG 3 header-protection key\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i1"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.i1
First custom signature packet (I1)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i2"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.i2
Second custom signature packet (I2)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i3"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.i3
Third custom signature packet (I3)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i4"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.i4
Fourth custom signature packet (I4)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-i5"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.i5
Fifth custom signature packet (I5)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-jc"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.jc
Junk packet count (Jc)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-jmax"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.jmax
Maximum junk packet size (Jmax)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-jmin"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.jmin
Minimum junk packet size (Jmin)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-keepalivetimeout"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-maxhandshakeattempts"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-randomtrailers"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.randomTrailers
AWG 3 random transport trailers (RandomTrailers)\.
*Type:*
null or boolean
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-rejectaftertime"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-rekeyaftertime"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-rekeytimeout"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-s1"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.s1
Handshake-init padding (S1)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-s2"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.s2
Handshake-response padding (S2)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-s3"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.s3
Cookie-reply padding (S3)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-obfuscation-s4"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.obfuscation\.s4
Transport-message padding (S4)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-persistentkeepalive"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.amneziaWg\.persistentKeepalive
PersistentKeepalive in client configs, which keeps NAT mappings open\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
25
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-privatekeyfile"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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"
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-subnet"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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"
```
<a id="services-proxy-suite-inbounds-listeners-name-amneziawg-subnet6"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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"
```
<a id="services-proxy-suite-inbounds-listeners-name-flow"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.flow
@@ -698,10 +1290,12 @@ one of “raw”, “ws”, “grpc”, “httpupgrade”, “xhttp”
<a id="services-proxy-suite-inbounds-listeners-name-type"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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)
]
```
<a id="services-proxy-suite-inbounds-listeners-name-users-address"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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"
```
<a id="services-proxy-suite-inbounds-listeners-name-users-name"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.users\.\*\.name
@@ -799,6 +1414,67 @@ null
"/run/secrets/proxy-inbound-password"
```
<a id="services-proxy-suite-inbounds-listeners-name-users-presharedkeyfile"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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"
```
<a id="services-proxy-suite-inbounds-listeners-name-users-privatekeyfile"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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"
```
<a id="services-proxy-suite-inbounds-listeners-name-users-publickey"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.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..."
```
<a id="services-proxy-suite-inbounds-listeners-name-users-uuid"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.users\.\*\.uuid
+227
View File
@@ -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" ];
};
};
}
+45 -19
View File
@@ -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;
+13
View File
@@ -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
+30 -1
View File
@@ -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
+2
View File
@@ -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
+19
View File
@@ -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")))))
+1
View File
@@ -163,6 +163,7 @@ let
in
{
inherit
reservedIpBlock
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
+3
View File
@@ -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) [ ];
};
}
+7
View File
@@ -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";
};
}
'';
};
@@ -330,5 +330,5 @@ let
);
in
{
inherit profileType;
inherit profileType obfuscationType;
}
+191 -81
View File
@@ -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-<tag>"'';
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;
+4 -3
View File
@@ -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
+143 -2
View File
@@ -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
+4
View File
@@ -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
@@ -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 ${
+4
View File
@@ -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
+4
View File
@@ -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
+213
View File
@@ -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.<vlan>.<node> 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)
'';
}
+9
View File
@@ -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"
'';
}
+166
View File
@@ -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
+15 -1
View File
@@ -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"
'';
+44 -13
View File
@@ -102,6 +102,8 @@ Secrets and changes need root, or the userControl group.
inbounds [list] server inbounds
inbounds link <tag> [user] [--qr|--json]
client share link, or the client's outbound JSON
inbounds link <tag> [user] --config [--qr]
an AmneziaWG client's .conf, or its QR code
inbounds link <tag> --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 <time>" or "never seen"; dies when the stats API is silent."""
status, out = _run(
@@ -2621,12 +2636,24 @@ def _inbound_presence():
online = {_s(u.get("email")): u.get("ips") or [] for u in json.loads(out or "{}").get("users") or []}
except (ValueError, AttributeError):
die("Unexpected answer from the inbounds' stats API.")
# As the timer last wrote it: the API already told who is online now.
path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
seen = (read_json(path).get("seen") or {}) if readable(path) else {}
# Users nobody has seen yet, when the links say who exists.
path = env("INBOUNDS_LINKS_FILE")
known = {_s(x.get("user")) for x in read_json(path) if x.get("user")} if readable(path) else set()
links = read_json(path) if readable(path) else []
known = {_s(x.get("user")) for x in links if x.get("user")}
# AmneziaWG peers are only known by their last handshake, which the collector reads;
# the XRay API already told who else is online now.
if any(x.get("type") == "amneziawg" for x in links):
systemctl("--no-ask-password", "start", "proxy-suite-inbound-stats.service", quiet=True)
path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
stats = read_json(path) if readable(path) else {}
seen = stats.get("seen") or {}
now = time.time()
for user, peer in (stats.get("awgPeers") or {}).items():
handshake = (peer or {}).get("handshake") or 0
endpoint = _s((peer or {}).get("endpoint") or "")
# A live peer handshakes every two minutes.
if handshake and now - handshake < AWG_ONLINE_SECONDS and endpoint:
online.setdefault(_s(user), []).append({"ip": endpoint.rsplit(":", 1)[0].strip("[]")})
def when(ts):
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
@@ -2652,8 +2679,9 @@ def _inbound_online():
print(row.format(user, state, addresses))
sys.stdout.flush()
print(
"A user counts as online while a connection is open. Behind a web server that needs the "
"listener's transport.trustedXForwardedFor, or everyone reads as never seen.",
"A user counts as online while a connection is open, or for AmneziaWG within three minutes "
"of a handshake. Behind a web server that needs the listener's transport.trustedXForwardedFor, "
"or everyone reads as never seen.",
file=sys.stderr,
)
@@ -2707,13 +2735,16 @@ def cmd_inbounds(verb="list", *args):
elif verb in ("link", "qr"):
rest = [a for a in args if not a.startswith("--")]
if not rest:
usage("inbounds link <tag> [user] [--qr|--json|--server-json]")
usage("inbounds link <tag> [user] [--qr|--json|--config|--server-json]")
qr = verb == "qr" or "--qr" in args
if "--server-json" in args:
_inbound_server_json(rest[0])
elif "--json" in args:
print(_json_text(_inbound_link_for(*rest, field="outbound")))
elif "--config" in args:
_emit(_inbound_link_for(*rest, field="config").rstrip("\n"), qr)
else:
_emit(_inbound_link_for(*rest), verb == "qr" or "--qr" in args)
_emit(_inbound_link_for(*rest), qr)
elif verb == "stats":
_inbound_stats(*args)
elif verb == "online":
+8 -1
View File
@@ -352,6 +352,11 @@ def _link(row, *extra):
return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *extra]
def _amneziawg(row):
# AmneziaWG clients take a .conf (or its vpn:// link), not an outbound JSON.
return row["type"] == "amneziawg"
def _kind(*kinds):
return lambda row: row["kind"] in kinds
@@ -512,7 +517,9 @@ TABS = [
# Without subscriptions.baseUrl there is only a file path, with a hint after it: nothing to encode or copy.
Action("S", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=_sub_url, mode="dialog"),
Action("y", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=_sub_url, mode="copy"),
Action("J", "client's outbound JSON", lambda r, *_: _link(r, "--json"), when=ROW, mode="dialog"),
Action("J", "client's outbound JSON", lambda r, *_: _link(r, "--json"), when=lambda r: not _amneziawg(r), mode="dialog"),
Action("w", "client config", lambda r, *_: _link(r, "--config"), when=_amneziawg, mode="dialog"),
Action("W", "client config as QR", lambda r, *_: _link(r, "--config", "--qr"), when=_amneziawg, mode="dialog"),
Action("V", "server's inbound JSON", lambda r, *_: ["inbounds", "link", r["tag"], "--server-json"], when=ROW, mode="dialog"),
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
Action("I", "traffic per inbound", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"),
+51
View File
@@ -474,6 +474,35 @@ class InboundsTest(EnvTest):
self.patch("_run", lambda *a, **kw: (1, ""))
self.assertNotEqual(run(ctl._inbound_online)[0], 0)
def test_online_amneziawg(self):
answer = {"users": [{"email": "fufsob", "ips": [{"ip": "203.0.113.7", "lastSeen": 1789471207}]}]}
self.patch("_run", lambda *a, **kw: (0, json.dumps(answer)))
started = []
self.patch("systemctl", lambda *a, **kw: started.append(a))
now = 1789471300
self.patch("time", mock.Mock(time=lambda: now))
os.environ["INBOUNDS_STATS_FILE"] = self.write(
"stats.json",
{
"seen": {"phone": now - 600, "laptop": now - 30},
"awgPeers": {
"phone": {"tag": "awg", "handshake": now - 600, "endpoint": "198.51.100.2:5000"},
"laptop": {"tag": "awg", "handshake": now - 30, "endpoint": "[2001:db8::5]:51820"},
"tablet": {"tag": "awg", "handshake": 0, "endpoint": None},
},
},
)
os.environ["INBOUNDS_LINKS_FILE"] = self.write(
"links.json", [{"tag": "a", "user": "fufsob", "type": "vless"}, {"tag": "awg", "user": "tablet", "type": "amneziawg"}]
)
out = ok(ctl._inbound_online)
# The collector reads the handshakes first.
self.assertEqual(started, [("--no-ask-password", "start", "proxy-suite-inbound-stats.service")])
self.assertRegex(out, r"(?m)^ fufsob +online +203\.0\.113\.7$")
self.assertRegex(out, r"(?m)^ laptop +online +2001:db8::5$")
self.assertRegex(out, r"(?m)^ phone +seen ")
self.assertRegex(out, r"(?m)^ tablet +never seen")
def test_subscriptions(self):
os.environ["INBOUNDS_SUBS_FILE"] = self.write("subs.json", [{"user": "fufsob", "token": "aaa"}, {"user": "teri", "token": "bbb"}])
os.environ["INBOUNDS_SUB_BASE_URL"] = "https://vpn.example/sub/"
@@ -688,6 +717,28 @@ class ShareTest(EnvTest):
self.assertEqual(json.loads(ok(ctl.cmd_inbounds, "link", "in", "--json")), {"type": "vless"})
self.assertEqual(json.loads(ok(ctl.cmd_inbounds, "link", "in", "--server-json"))["protocol"], "vless")
def test_inbound_amneziawg_config(self):
config = "[Interface]\nPrivateKey = k\n\n[Peer]\nEndpoint = h:51820\n"
self.write(
"inbounds/links.json",
[
{"tag": "in", "user": "u", "type": "vless", "link": "vless://x@h:443", "outbound": {"type": "vless"}},
{"tag": "awg", "user": "u", "type": "amneziawg", "link": "vpn://abc", "config": config, "outbound": None},
],
)
emitted = []
self.patch("_run", lambda cmd, **kw: (emitted.append((cmd, kw.get("stdin"))), (0, ""))[1])
self.assertEqual(ok(ctl.cmd_inbounds, "link", "awg", "u"), "vpn://abc\n")
self.assertEqual(ok(ctl.cmd_inbounds, "link", "awg", "--config"), config)
ok(ctl.cmd_inbounds, "link", "awg", "u", "--config", "--qr")
self.assertEqual(emitted[-1], (["qrencode", "-t", "ANSIUTF8"], config.rstrip("\n")))
status, _, err = run(ctl.cmd_inbounds, "link", "awg", "--json")
self.assertNotEqual(status, 0)
self.assertIn("use --config", err)
status, _, err = run(ctl.cmd_inbounds, "link", "in", "--config")
self.assertNotEqual(status, 0)
self.assertIn("only AmneziaWG", err)
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
def test_unreadable(self):
os.chmod(self.share, 0)
+10
View File
@@ -79,6 +79,16 @@ class ModelTest(unittest.TestCase):
self.assertEqual(model.toggle_argv(row), ["awg", "on", "warp"]) # a global profile named warp
self.assertIn("ctrl+r", keys())
def test_inbound_amneziawg_actions(self):
tab = next(t for t in model.TABS if t.id == "inbounds")
actions = {a.key: a for a in tab.actions}
awg = {"key": "awg/u", "tag": "awg", "user": "u", "type": "amneziawg", "port": "51820"}
vless = {"key": "in/u", "tag": "in", "user": "u", "type": "vless", "port": "443"}
self.assertEqual(actions["w"].argv(awg), ["inbounds", "link", "awg", "u", "--config"])
self.assertEqual(actions["W"].argv(awg), ["inbounds", "link", "awg", "u", "--config", "--qr"])
self.assertTrue(actions["w"].when(awg) and actions["W"].when(awg) and actions["J"].when(vless))
self.assertFalse(actions["w"].when(vless) or actions["W"].when(vless) or actions["J"].when(awg))
def test_inbound_rows_carry_no_presence(self):
"""XRay keys the online map by user, not by inbound, so a per-listener row
could only repeat one verdict per listener; it must not claim to have one."""
+59
View File
@@ -156,6 +156,65 @@ def decode_vpn_link(link: str) -> dict[str, Any]:
return result
def encode_vpn_link(
config: str,
host: str,
description: str,
client_public_key: str | None = None,
) -> str:
"""A self-contained vpn:// link carrying a client .conf, as AmneziaVPN exports one.
The payload is qCompress'd JSON (a 4-byte big-endian length, then zlib), in URL-safe
base64. Everything but host and the client's public key is read from the config.
"""
interface = {key: value for name, pairs in conf_sections(config) if name == "interface" for key, value in pairs}
peer = {key: value for name, pairs in conf_sections(config) if name == "peer" for key, value in pairs}
endpoint = peer.get("endpoint", "")
port = endpoint.rsplit(":", 1)[1] if ":" in endpoint else ""
dns = [item.strip() for item in interface.get("dns", "").split(",") if item.strip()]
last: dict[str, Any] = {
"config": config,
"hostName": host,
"port": int(port) if port.isdigit() else port,
"client_ip": interface.get("address", "").split(",")[0].strip().split("/")[0],
"client_priv_key": interface.get("privatekey", ""),
"server_pub_key": peer.get("publickey", ""),
"psk_key": peer.get("presharedkey", ""),
"allowed_ips": [item.strip() for item in peer.get("allowedips", "").split(",") if item.strip()],
"persistent_keep_alive": peer.get("persistentkeepalive", ""),
}
if client_public_key:
last["client_pub_key"] = client_public_key
if interface.get("mtu"):
last["mtu"] = interface["mtu"]
protocol: dict[str, Any] = {}
for normalized, key in VPN_INTERFACE_FIELDS.items():
if normalized in interface:
last[key] = interface[normalized]
protocol[key] = interface[normalized]
protocol.update(
{
"last_config": json.dumps(last, separators=(",", ":")),
"port": str(port),
"transport_proto": "udp",
"isThirdPartyConfig": True,
}
)
data = {
"containers": [{"container": "amnezia-awg", "awg": protocol}],
"defaultContainer": "amnezia-awg",
"description": description,
"hostName": host,
}
if dns:
data["dns1"] = dns[0]
if len(dns) > 1:
data["dns2"] = dns[1]
payload = json.dumps(data, separators=(",", ":")).encode("utf-8")
compressed = len(payload).to_bytes(4, "big") + zlib.compress(payload, 8)
return "vpn://" + base64.urlsafe_b64encode(compressed).decode("ascii").rstrip("=")
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")
+442
View File
@@ -0,0 +1,442 @@
#!/usr/bin/env python3
"""AmneziaWG server listeners of services.proxy-suite.inbounds.
Keys, preshared keys, tunnel addresses and generated obfuscation live in one state file per
listener, so they survive restarts; users gone from the spec are dropped from it, which
revokes them. Values declared in the spec (key files, addresses, obfuscation fields) win
over the state and are not stored in it. The state is read back by proxy_inbound.py to
render client configs and links.
"""
from __future__ import annotations
import argparse
import fcntl
import ipaddress
import json
import os
import random
import subprocess
import sys
from pathlib import Path
from typing import Any
from amneziawg_config import (
ConfigError,
_apply_awg3_mtu_default,
_set_interface_value,
encode_vpn_link,
render_settings,
transport_implementation,
write_private,
)
STATE_VERSION = 1
# AWG 1.x fields: every AmneziaWG client understands them.
GENERATED_OBFUSCATION = ("jc", "jmin", "jmax", "s1", "s2", "h1", "h2", "h3", "h4")
# Size of a WireGuard handshake initiation minus a response: S1 + 56 == S2 would make the
# padded messages the same size again.
HANDSHAKE_SIZE_DIFFERENCE = 56
def _random() -> random.Random:
return random.SystemRandom()
def generate_obfuscation(declared: dict[str, Any], stored: dict[str, Any]) -> dict[str, int]:
"""Generated values for the AWG 1.x fields the spec leaves null.
Stored values are kept unless they no longer fit around the declared ones.
"""
rng = _random()
values = {key: declared[key] for key in GENERATED_OBFUSCATION if declared.get(key) is not None}
generated: dict[str, int] = {}
def pick(key: str, valid, make) -> None:
if key in values:
return
current = stored.get(key)
if not (type(current) is int and valid(current)):
current = make()
while not valid(current):
current = make()
values[key] = generated[key] = current
pick("jc", lambda v: 3 <= v <= 10, lambda: rng.randint(3, 10))
# Junk packets go out ahead of every handshake: kept small, as AmneziaVPN's own are.
jmax_declared = values.get("jmax") if type(values.get("jmax")) is int else None
jmin_high = 50 if jmax_declared is None else max(0, min(50, jmax_declared - 1))
jmin_low = min(8, jmin_high)
pick("jmin", lambda v: jmin_low <= v <= jmin_high, lambda: rng.randint(jmin_low, jmin_high))
jmin = values["jmin"] if type(values["jmin"]) is int else 0
pick("jmax", lambda v: jmin + 8 <= v <= max(jmin + 8, 250), lambda: rng.randint(jmin + 8, max(jmin + 8, 250)))
pick("s1", lambda v: 15 <= v <= 150, lambda: rng.randint(15, 150))
s1 = values["s1"] if isinstance(values["s1"], int) else None
pick(
"s2",
lambda v: 15 <= v <= 150 and (s1 is None or s1 + HANDSHAKE_SIZE_DIFFERENCE != v),
lambda: rng.randint(15, 150),
)
for key in ("h1", "h2", "h3", "h4"):
others = {values[other] for other in ("h1", "h2", "h3", "h4") if other != key and other in values}
pick(key, lambda v, others=others: 5 <= v <= 2**31 - 1 and v not in others, lambda: rng.randint(5, 2**31 - 1))
return generated
def _read_key(path: str, what: str) -> str:
try:
value = Path(path).read_text(encoding="utf-8").strip()
except OSError as exc:
raise ConfigError(f"cannot read {what} file '{path}': {exc.strerror}") from None
if not value or "\n" in value:
raise ConfigError(f"{what} file '{path}' must hold one non-empty line")
return value
class Keys:
"""`awg genkey`, `pubkey` and `genpsk`."""
def __init__(self, awg: str):
self.awg = awg
def _run(self, *args: str, stdin: str | None = None) -> str:
result = subprocess.run(
[self.awg, *args], input=stdin, capture_output=True, text=True, check=False
)
if result.returncode != 0 or not result.stdout.strip():
raise ConfigError(f"awg {args[0]} failed")
return result.stdout.strip()
def private(self) -> str:
return self._run("genkey")
def public(self, private: str) -> str:
return self._run("pubkey", stdin=private + "\n")
def preshared(self) -> str:
return self._run("genpsk")
def _host(network: ipaddress._BaseNetwork, offset: int) -> ipaddress._BaseAddress:
return network.network_address + offset
def allocate_addresses(awg: dict, users: list[dict], stored: dict[str, dict]) -> dict[str, int]:
"""Host offset in the subnet of each user by name: declared, kept, then the lowest free.
This host has offset 1.
"""
tag = awg["tag"]
network = ipaddress.ip_network(awg["subnet"], strict=False)
last = network.num_addresses - (1 if network.prefixlen < 31 else 0)
offsets: dict[str, int] = {}
taken = {1}
for user in users:
if user.get("address") is None:
continue
address = ipaddress.ip_address(user["address"])
offset = int(address) - int(network.network_address)
if address not in network or not 1 < offset < last:
raise ConfigError(f"listener '{tag}': address {address} of user '{user['name']}' is not a client address in {network}")
if offset in taken:
raise ConfigError(f"listener '{tag}': address {address} is taken twice")
offsets[user["name"]] = offset
taken.add(offset)
for user in users:
name = user["name"]
offset = stored.get(name, {}).get("offset")
if name not in offsets and type(offset) is int and 1 < offset < last and offset not in taken:
offsets[name] = offset
taken.add(offset)
free = (offset for offset in range(2, last) if offset not in taken)
for user in users:
if user["name"] not in offsets:
offset = next(free, None)
if offset is None:
raise ConfigError(f"listener '{tag}': subnet {network} has no free address for user '{user['name']}'")
offsets[user["name"]] = offset
taken.add(offset)
return offsets
def update_state(listener: dict, state: dict, keys: Keys) -> dict:
"""The state after this spec: generated values filled in, departed users dropped."""
awg = {**listener["amneziaWg"], "tag": listener["tag"]}
stored_users = state.get("users", {}) if state.get("version") == STATE_VERSION else {}
stored_server = state.get("server", {}) if state.get("version") == STATE_VERSION else {}
stored_obfuscation = state.get("obfuscation", {}) if state.get("version") == STATE_VERSION else {}
server: dict[str, str] = {}
if awg.get("privateKeyFile") is not None:
server["publicKey"] = keys.public(_read_key(awg["privateKeyFile"], "server private key"))
else:
private = stored_server.get("privateKey")
if private and stored_server.get("publicKey"):
server = {"privateKey": private, "publicKey": stored_server["publicKey"]}
else:
private = private or keys.private()
server = {"privateKey": private, "publicKey": keys.public(private)}
offsets = allocate_addresses(awg, listener["users"], stored_users)
users: dict[str, dict] = {}
for user in listener["users"]:
name = user["name"]
stored = stored_users.get(name, {})
entry: dict[str, Any] = {"offset": offsets[name]}
if user.get("publicKey") is not None:
entry["publicKey"] = user["publicKey"]
elif user.get("privateKeyFile") is not None:
entry["publicKey"] = keys.public(_read_key(user["privateKeyFile"], f"private key of user '{name}'"))
else:
private = stored.get("privateKey") or keys.private()
entry["privateKey"] = private
entry["publicKey"] = (
stored["publicKey"] if stored.get("privateKey") == private and stored.get("publicKey") else keys.public(private)
)
# A peer holding its own private key brings its own preshared key, if any.
if user.get("presharedKeyFile") is None and user.get("publicKey") is None:
entry["presharedKey"] = stored.get("presharedKey") or keys.preshared()
users[name] = entry
obfuscation = generate_obfuscation(awg.get("obfuscation") or {}, stored_obfuscation)
return {"version": STATE_VERSION, "server": server, "obfuscation": obfuscation, "users": users}
def _obfuscation(awg: dict, state: dict) -> dict[str, Any]:
declared = {key: value for key, value in (awg.get("obfuscation") or {}).items() if value is not None}
return {**state.get("obfuscation", {}), **declared}
def _addresses(awg: dict, offset: int, prefix: bool) -> list[str]:
result = []
for key in ("subnet", "subnet6"):
if awg.get(key) is None:
continue
network = ipaddress.ip_network(awg[key], strict=False)
length = network.prefixlen if prefix else network.max_prefixlen
result.append(f"{_host(network, offset)}/{length}")
return result
def _user_private_key(user: dict, entry: dict) -> str | None:
if user.get("privateKeyFile") is not None:
return _read_key(user["privateKeyFile"], f"private key of user '{user['name']}'")
return entry.get("privateKey")
def _user_preshared_key(user: dict, entry: dict) -> str | None:
if user.get("presharedKeyFile") is not None:
return _read_key(user["presharedKeyFile"], f"preshared key of user '{user['name']}'")
return entry.get("presharedKey")
def render_server_config(listener: dict, state: dict) -> str:
awg = listener["amneziaWg"]
peers = []
for user in listener["users"]:
entry = state["users"][user["name"]]
peer: dict[str, Any] = {
"publicKey": entry["publicKey"],
"allowedIPs": _addresses(awg, entry["offset"], prefix=False),
}
preshared = _user_preshared_key(user, entry)
if preshared is not None:
peer["presharedKey"] = preshared
peers.append(peer)
settings: dict[str, Any] = {
"addresses": _addresses(awg, 1, prefix=True),
"listenPort": listener["port"],
"mtu": awg.get("mtu"),
# Traffic is steered by proxy-suite's own rules, not by AllowedIPs routes.
"table": "off",
"obfuscation": _obfuscation(awg, state),
"peers": peers,
}
if awg.get("privateKeyFile") is not None:
settings["privateKeyFile"] = awg["privateKeyFile"]
else:
settings["privateKey"] = state["server"]["privateKey"]
config = _apply_awg3_mtu_default(render_settings(settings))
if awg.get("fwmark") is not None:
# Replies to clients get past TUN and TProxy capture, as an outbound interface's packets.
config = _set_interface_value(config, "FwMark", str(awg["fwmark"]))
return config
def render_client_config(listener: dict, state: dict, user: dict, server_address: str, port: int) -> str | None:
"""A user's .conf, or None for a peer that keeps its private key."""
awg = listener["amneziaWg"]
entry = state["users"][user["name"]]
private = _user_private_key(user, entry)
if private is None:
return None
host = f"[{server_address}]" if ":" in server_address else server_address
peer: dict[str, Any] = {
"publicKey": state["server"]["publicKey"],
"allowedIPs": awg["clientAllowedIPs"],
"endpoint": f"{host}:{port}",
"persistentKeepalive": awg.get("persistentKeepalive"),
}
preshared = _user_preshared_key(user, entry)
if preshared is not None:
peer["presharedKey"] = preshared
obfuscation = _obfuscation(awg, state)
# The header-protection key is the server's secret too; the client gets its value.
settings = {
"addresses": _addresses(awg, entry["offset"], prefix=False),
"dns": awg.get("dns") or [],
"privateKey": private,
"mtu": awg.get("mtu"),
"obfuscation": obfuscation,
"peers": [peer],
}
return _apply_awg3_mtu_default(render_settings(settings))
def client_entries(listener: dict, server_address: str, port: int) -> list[dict]:
"""{user, config, link} for each user with a config, from the prepared state.
Nothing when the state is missing: the AmneziaWG unit has not prepared it yet.
"""
path = listener["amneziaWg"]["stateFile"]
try:
state = json.loads(Path(path).read_text(encoding="utf-8"))
except FileNotFoundError:
print(f"proxy-suite: listener '{listener['tag']}' has no AmneziaWG state yet; no links", file=sys.stderr)
return []
entries = []
for user in listener["users"]:
if user["name"] not in state.get("users", {}):
continue
config = render_client_config(listener, state, user, server_address, port)
if config is None:
continue
link = encode_vpn_link(
config,
server_address,
f"{listener['tag']} ({user['name']})",
state["users"][user["name"]].get("publicKey"),
)
entries.append({"user": user["name"], "config": config, "link": link})
return entries
def prepare(spec: dict, awg_binary: str, runtime_dir: str) -> list[dict]:
"""Update every AmneziaWG listener's state and write its server config.
Returns {tag, interface, config, implementation} for each; implementation is what
awg-quick should run the interface with, "auto" or "userspace".
"""
keys = Keys(awg_binary)
prepared = []
for listener in spec["listeners"]:
if listener.get("type") != "amneziawg":
continue
awg = listener["amneziaWg"]
state_path = Path(awg["stateFile"])
state_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
with open(state_path.parent / ".lock", "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
try:
state = json.loads(state_path.read_text(encoding="utf-8"))
except FileNotFoundError:
state = {}
state = update_state(listener, state, keys)
write_private(str(state_path), json.dumps(state, indent=2) + "\n")
config_path = os.path.join(runtime_dir, f"{awg['interfaceName']}.conf")
config = render_server_config(listener, state)
write_private(config_path, config)
prepared.append(
{
"tag": listener["tag"],
"interface": awg["interfaceName"],
"config": config_path,
"implementation": transport_implementation(config),
}
)
return prepared
def peer_names(spec: dict) -> dict[str, dict]:
"""By interface: the listener's tag and its users' names by public key."""
result: dict[str, dict] = {}
for listener in spec["listeners"]:
if listener.get("type") != "amneziawg":
continue
awg = listener["amneziaWg"]
try:
state = json.loads(Path(awg["stateFile"]).read_text(encoding="utf-8"))
except FileNotFoundError:
continue
result[awg["interfaceName"]] = {
"tag": listener["tag"],
"users": {entry["publicKey"]: name for name, entry in state.get("users", {}).items()},
}
return result
def parse_dump(dump: str) -> list[dict]:
"""Peers of `awg show <interface> dump`; its first line is the interface itself."""
peers = []
for line in dump.splitlines()[1:]:
fields = line.split("\t")
if len(fields) < 7:
continue
endpoint = fields[2]
peers.append(
{
"key": fields[0],
"endpoint": None if endpoint == "(none)" else endpoint,
"handshake": int(fields[4]),
"rx": int(fields[5]),
"tx": int(fields[6]),
}
)
return peers
def peer_counters(spec: dict, awg_binary: str) -> list[dict]:
"""Every known peer's raw transfer counters, latest handshake and endpoint, with its
listener and user; interfaces that are down are left out."""
result = []
for interface, listener in peer_names(spec).items():
completed = subprocess.run(
[awg_binary, "show", interface, "dump"], capture_output=True, text=True, check=False
)
if completed.returncode != 0:
continue
for peer in parse_dump(completed.stdout):
user = listener["users"].get(peer["key"])
if user is not None:
result.append({**peer, "interface": interface, "tag": listener["tag"], "user": user})
return result
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
prepare_parser = commands.add_parser("prepare", help="update the state and write the server configs")
prepare_parser.add_argument("--spec", required=True)
prepare_parser.add_argument("--awg", required=True, help="path to the awg tool")
prepare_parser.add_argument("--runtime-dir", required=True)
peers_parser = commands.add_parser("peers", help="print every peer's counters, with its listener and user")
peers_parser.add_argument("--spec", required=True)
peers_parser.add_argument("--awg", required=True, help="path to the awg tool")
args = parser.parse_args()
with open(args.spec, encoding="utf-8") as handle:
spec = json.load(handle)
try:
if args.command == "prepare":
# One line per listener, for the start script to read.
for entry in prepare(spec, args.awg, args.runtime_dir):
print(entry["interface"], entry["implementation"], entry["config"])
else:
print(json.dumps(peer_counters(spec, args.awg)))
except (ConfigError, ValueError, OSError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+47 -1
View File
@@ -13,6 +13,7 @@ import hashlib
import json
import urllib.parse
from awg_inbound import client_entries
from proxy_parsing import build_outbound
UUID_TYPES = ("vless", "vmess")
@@ -314,14 +315,46 @@ def build_share_link(listener: dict, server_address: str, user_index: int = 0) -
return f"{listener_type}://{secret}@{endpoint}?{query}#{fragment}"
def render_amneziawg_inbound(listener: dict) -> dict:
"""The XRay side of an AmneziaWG listener: a transparent inbound on loopback that the
interface's TCP and UDP is diverted to, so it leaves by the same rules as every other."""
awg = listener["amneziaWg"]
return {
"tag": listener["tag"],
"listen": awg["internalListen"],
"port": awg["internalPort"],
"protocol": "tunnel",
"settings": {"allowedNetwork": "tcp,udp", "followRedirect": True},
"streamSettings": {"sockopt": {"tproxy": "tproxy"}},
# routeOnly: the client already resolved, so XRay dials the address it asked for.
"sniffing": {
"enabled": True,
"destOverride": ["http", "tls", "quic"],
"routeOnly": True,
},
}
def build_listener(listener: dict, server_address: str, share_links: bool) -> dict:
"""Render one listener into its inbound object and, when possible, a link.
Raw-JSON listeners are passed through untouched apart from the tag, and get
no share link: proxy-suite does not know what they serve.
no share link: proxy-suite does not know what they serve. An AmneziaWG listener
has no share links but client configs, each with a vpn:// link, under "configs".
"""
tag = listener["tag"]
if listener.get("type") == "amneziawg":
port = _share_port(listener)
return {
"tag": tag,
"type": "amneziawg",
"port": port,
"inbound": render_amneziawg_inbound(listener),
"links": [],
"configs": client_entries(listener, server_address, port) if share_links else [],
}
raw = listener.get("xrayJson")
if listener.get("jsonFile") is not None:
with open(listener["jsonFile"], encoding="utf-8") as handle:
@@ -394,6 +427,19 @@ def build_inbounds(spec: dict, server_address: str) -> dict:
entry = by_user.setdefault(name, {"links": [], "secrets": []})
entry["links"].append(link)
entry["secrets"].append(_user_secret(user, listener["type"], rendered["tag"]))
# Not in subscriptions: the clients reading those do not speak vpn://.
for entry in rendered.get("configs", []):
links.append(
{
"tag": rendered["tag"],
"user": entry["user"],
"type": rendered["type"],
"port": rendered["port"],
"link": entry["link"],
"config": entry["config"],
"outbound": None,
}
)
subscriptions = [
{
"user": name,
+413
View File
@@ -0,0 +1,413 @@
#!/usr/bin/env python3
import base64
import hashlib
import json
import os
import stat
import sys
import tempfile
import textwrap
import unittest
import awg_inbound
from amneziawg_config import conf_sections, decode_vpn_link, extract_vpn_config
from proxy_inbound import build_inbounds
# Stands in for `awg`: keys are random, a public key is a hash of its private key, and
# `show <interface> dump` prints $AWG_DUMP_<interface, dashes as underscores>.
STUB_AWG = f"#!{sys.executable}\n" + textwrap.dedent(
"""\
import base64, hashlib, os, sys
command = sys.argv[1]
if command in ("genkey", "genpsk"):
print(base64.b64encode(os.urandom(32)).decode())
elif command == "pubkey":
print(base64.b64encode(hashlib.sha256(sys.stdin.read().strip().encode()).digest()).decode())
elif command == "show":
dump = os.environ.get("AWG_DUMP_" + sys.argv[2].replace("-", "_"))
if dump is None:
sys.exit(1)
sys.stdout.write(dump)
else:
sys.exit(2)
"""
)
def public_of(private: str) -> str:
return base64.b64encode(hashlib.sha256(private.encode()).digest()).decode()
OBFUSCATION_FIELDS = (
"jc jmin jmax s1 s2 s3 s4 h1 h2 h3 h4 i1 i2 i3 i4 i5 headerProtectionKey headerProtectionKeyFile "
"randomTrailers contentPaddingAddition disableCookies keepaliveTimeout maxHandshakeAttempts "
"rejectAfterTime rekeyAfterTime rekeyTimeout"
).split()
def user(name, **overrides):
entry = {
"name": name,
"address": None,
"publicKey": None,
"privateKeyFile": None,
"presharedKeyFile": None,
"uuid": None,
"uuidFile": None,
"password": None,
"passwordFile": None,
}
entry.update(overrides)
return entry
class Fixture(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.dir = self.tmp.name
self.awg = os.path.join(self.dir, "awg")
with open(self.awg, "w", encoding="utf-8") as handle:
handle.write(STUB_AWG)
os.chmod(self.awg, stat.S_IRWXU)
self.runtime = os.path.join(self.dir, "run")
os.mkdir(self.runtime)
self.keys = awg_inbound.Keys(self.awg)
def tearDown(self):
self.tmp.cleanup()
def listener(self, tag="awg-in", users=None, **awg_overrides):
awg = {
"mode": "proxy",
"interfaceName": f"awgi-{tag}",
"subnet": "10.66.0.0/24",
"subnet6": None,
"privateKeyFile": None,
"obfuscation": {field: None for field in OBFUSCATION_FIELDS},
"dns": ["1.1.1.1", "1.0.0.1"],
"mtu": None,
"persistentKeepalive": 25,
"clientAllowedIPs": ["0.0.0.0/0", "::/0"],
"internalPort": 18700,
"internalListen": "127.0.0.1",
"stateFile": os.path.join(self.dir, "state", tag, "state.json"),
"fwmark": 2,
}
awg.update(awg_overrides)
return {
"tag": tag,
"type": "amneziawg",
"port": 51820,
"sharePort": None,
"listen": "::",
"users": users if users is not None else [user("alice"), user("bob")],
"amneziaWg": awg,
}
def spec(self, *listeners):
return {"serverAddress": "vpn.example.com", "shareLinks": True, "listeners": list(listeners)}
def state(self, listener):
with open(listener["amneziaWg"]["stateFile"], encoding="utf-8") as handle:
return json.load(handle)
def secret_file(self, name, value):
path = os.path.join(self.dir, name)
with open(path, "w", encoding="utf-8") as handle:
handle.write(value + "\n")
return path
class ObfuscationTests(unittest.TestCase):
def test_generated_values_are_valid(self):
for _ in range(200):
values = awg_inbound.generate_obfuscation({}, {})
self.assertEqual(set(values), set(awg_inbound.GENERATED_OBFUSCATION))
self.assertTrue(3 <= values["jc"] <= 10)
self.assertTrue(values["jmin"] + 8 <= values["jmax"] <= 250)
self.assertNotEqual(values["s1"] + 56, values["s2"])
headers = [values[key] for key in ("h1", "h2", "h3", "h4")]
self.assertEqual(len(set(headers)), 4)
self.assertTrue(all(5 <= header < 2**31 for header in headers))
def test_stored_values_are_kept(self):
first = awg_inbound.generate_obfuscation({}, {})
self.assertEqual(awg_inbound.generate_obfuscation({}, first), first)
def test_declared_values_are_not_generated(self):
values = awg_inbound.generate_obfuscation({"jc": 4, "h1": 7, "jmax": 20}, {})
self.assertNotIn("jc", values)
self.assertNotIn("h1", values)
self.assertTrue(values["jmin"] < 20)
self.assertNotIn(7, [values[key] for key in ("h2", "h3", "h4")])
class StateTests(Fixture):
def test_prepare_creates_private_state_and_server_config(self):
listener = self.listener()
prepared = awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
self.assertEqual(len(prepared), 1)
self.assertEqual(prepared[0]["interface"], "awgi-awg-in")
self.assertIn(prepared[0]["implementation"], ("auto", "userspace"))
state_path = listener["amneziaWg"]["stateFile"]
self.assertEqual(stat.S_IMODE(os.stat(state_path).st_mode), 0o600)
state = self.state(listener)
self.assertEqual(state["server"]["publicKey"], public_of(state["server"]["privateKey"]))
self.assertEqual(state["users"]["alice"]["offset"], 2)
self.assertEqual(state["users"]["bob"]["offset"], 3)
with open(prepared[0]["config"], encoding="utf-8") as handle:
config = handle.read()
self.assertEqual(stat.S_IMODE(os.stat(prepared[0]["config"]).st_mode), 0o600)
sections = conf_sections(config)
interface = dict(sections[0][1])
self.assertEqual(interface["address"], "10.66.0.1/24")
self.assertEqual(interface["listenport"], "51820")
self.assertEqual(interface["table"], "off")
self.assertEqual(interface["fwmark"], "2")
self.assertEqual(interface["privatekey"], state["server"]["privateKey"])
peers = [dict(values) for name, values in sections if name == "peer"]
self.assertEqual(
{peer["publickey"]: peer["allowedips"] for peer in peers},
{
state["users"]["alice"]["publicKey"]: "10.66.0.2/32",
state["users"]["bob"]["publicKey"]: "10.66.0.3/32",
},
)
self.assertTrue(all("presharedkey" in peer for peer in peers))
def test_state_is_stable_across_runs_and_reorders(self):
listener = self.listener()
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
before = self.state(listener)
listener["users"].reverse()
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
self.assertEqual(self.state(listener), before)
def test_departed_users_are_pruned_and_their_address_reused(self):
listener = self.listener()
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
alice = self.state(listener)["users"]["alice"]
listener["users"] = [user("bob")]
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
self.assertNotIn("alice", self.state(listener)["users"])
listener["users"] = [user("bob"), user("carol"), user("alice")]
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
state = self.state(listener)
self.assertEqual(state["users"]["bob"]["offset"], 3)
self.assertEqual(state["users"]["carol"]["offset"], 2)
self.assertEqual(state["users"]["alice"]["offset"], 4)
self.assertNotEqual(state["users"]["alice"]["privateKey"], alice["privateKey"])
def test_declared_address_wins(self):
listener = self.listener()
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
listener["users"] = [user("alice"), user("bob", address="10.66.0.2")]
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
state = self.state(listener)
self.assertEqual(state["users"]["bob"]["offset"], 2)
self.assertEqual(state["users"]["alice"]["offset"], 3)
def test_invalid_addresses_are_rejected(self):
for address in ("10.67.0.5", "10.66.0.1", "10.66.0.255", "10.66.0.0"):
with self.subTest(address=address):
listener = self.listener(users=[user("alice", address=address)])
with self.assertRaises(awg_inbound.ConfigError):
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
listener = self.listener(users=[user("alice", address="10.66.0.5"), user("bob", address="10.66.0.5")])
with self.assertRaises(awg_inbound.ConfigError):
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
def test_full_subnet_is_rejected(self):
listener = self.listener(subnet="10.66.0.0/30", users=[user("alice"), user("bob")])
with self.assertRaises(awg_inbound.ConfigError):
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
def test_ipv6_subnet_adds_addresses(self):
listener = self.listener(subnet6="fd00:66::/64")
prepared = awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
with open(prepared[0]["config"], encoding="utf-8") as handle:
sections = conf_sections(handle.read())
interface = sections[0][1]
addresses = ",".join(value for key, value in interface if key == "address")
self.assertIn("10.66.0.1/24", addresses)
self.assertIn("fd00:66::1/64", addresses)
peer = dict(sections[1][1])
self.assertIn("fd00:66::2/128", peer["allowedips"])
def test_key_overrides(self):
server_private = "c2VydmVyLXByaXZhdGUta2V5LXNlcnZlci1wcml2YXRlLWs="
user_private = "dXNlci1wcml2YXRlLWtleS11c2VyLXByaXZhdGUta2V5LXU="
psk = "cHNrLXBzay1wc2stcHNrLXBzay1wc2stcHNrLXBzay1wc2s="
listener = self.listener(
privateKeyFile=self.secret_file("server.key", server_private),
users=[
user("alice", privateKeyFile=self.secret_file("alice.key", user_private)),
user("bob", publicKey="Ym9iLXB1YmxpYy1rZXktYm9iLXB1YmxpYy1rZXktYm9iLXA="),
user("carol", presharedKeyFile=self.secret_file("carol.psk", psk)),
],
)
prepared = awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
state = self.state(listener)
# Declared secrets stay out of the state.
self.assertEqual(state["server"], {"publicKey": public_of(server_private)})
self.assertEqual(state["users"]["alice"], {"offset": 2, "publicKey": public_of(user_private), "presharedKey": state["users"]["alice"]["presharedKey"]})
self.assertEqual(
state["users"]["bob"],
{"offset": 3, "publicKey": "Ym9iLXB1YmxpYy1rZXktYm9iLXB1YmxpYy1rZXktYm9iLXA="},
)
self.assertNotIn("presharedKey", state["users"]["carol"])
self.assertNotIn(psk, json.dumps(state))
with open(prepared[0]["config"], encoding="utf-8") as handle:
config = handle.read()
self.assertIn(server_private, config)
self.assertIn(psk, config)
entries = awg_inbound.client_entries(listener, "vpn.example.com", 51820)
self.assertEqual([entry["user"] for entry in entries], ["alice", "carol"])
self.assertIn(user_private, entries[0]["config"])
self.assertIn(psk, entries[1]["config"])
def test_switching_server_key_to_generated_derives_its_public_key(self):
listener = self.listener(privateKeyFile=self.secret_file("server.key", "c2VydmVy"))
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
listener["amneziaWg"]["privateKeyFile"] = None
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
server = self.state(listener)["server"]
self.assertEqual(server["publicKey"], public_of(server["privateKey"]))
def test_declared_obfuscation_wins(self):
listener = self.listener()
listener["amneziaWg"]["obfuscation"]["jc"] = 7
listener["amneziaWg"]["obfuscation"]["i1"] = "<b 0xf6ab3267fa><c><t><r 10>"
prepared = awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
self.assertNotIn("jc", self.state(listener)["obfuscation"])
with open(prepared[0]["config"], encoding="utf-8") as handle:
interface = dict(conf_sections(handle.read())[0][1])
self.assertEqual(interface["jc"], "7")
self.assertEqual(interface["i1"], "<b 0xf6ab3267fa><c><t><r 10>")
config = awg_inbound.client_entries(listener, "vpn.example.com", 51820)[0]["config"]
self.assertEqual(dict(conf_sections(config)[0][1])["jc"], "7")
class ClientTests(Fixture):
def test_client_config_matches_server(self):
listener = self.listener(subnet6="fd00:66::/64", mtu=1280)
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
state = self.state(listener)
entries = awg_inbound.client_entries(listener, "2001:db8::1", 443)
self.assertEqual([entry["user"] for entry in entries], ["alice", "bob"])
sections = conf_sections(entries[1]["config"])
interface = dict(sections[0][1])
peer = dict(sections[1][1])
addresses = [value for key, value in sections[0][1] if key == "address"]
self.assertEqual(interface["privatekey"], state["users"]["bob"]["privateKey"])
self.assertIn("10.66.0.3/32", ",".join(addresses))
self.assertIn("fd00:66::3/128", ",".join(addresses))
self.assertIn("1.1.1.1", interface["dns"])
self.assertEqual(interface["mtu"], "1280")
for key in ("jc", "jmin", "jmax", "s1", "s2", "h1", "h2", "h3", "h4"):
self.assertEqual(interface[key], str(state["obfuscation"][key]))
self.assertEqual(peer["publickey"], state["server"]["publicKey"])
self.assertEqual(peer["presharedkey"], state["users"]["bob"]["presharedKey"])
self.assertEqual(peer["endpoint"], "[2001:db8::1]:443")
self.assertEqual(peer["persistentkeepalive"], "25")
self.assertNotIn("fwmark", interface)
self.assertNotIn("table", interface)
def test_vpn_link_round_trip(self):
listener = self.listener()
awg_inbound.prepare(self.spec(listener), self.awg, self.runtime)
for entry in awg_inbound.client_entries(listener, "vpn.example.com", 51820):
with self.subTest(user=entry["user"]):
self.assertTrue(entry["link"].startswith("vpn://"))
data = decode_vpn_link(entry["link"])
self.assertEqual(data["hostName"], "vpn.example.com")
self.assertEqual(data["dns1"], "1.1.1.1")
self.assertEqual(data["containers"][0]["container"], "amnezia-awg")
decoded = extract_vpn_config(data)
def without_listen_port(config):
return [
(name, sorted((key, value) for key, value in values if key != "listenport"))
for name, values in conf_sections(config)
]
self.assertEqual(without_listen_port(decoded), without_listen_port(entry["config"]))
def test_missing_state_yields_no_entries(self):
listener = self.listener()
self.assertEqual(awg_inbound.client_entries(listener, "vpn.example.com", 51820), [])
def test_build_inbounds(self):
listener = self.listener()
listener["sharePort"] = 443
other = {
"tag": "vless-in",
"type": "vless",
"port": 8443,
"sharePort": None,
"listen": "::",
"users": [user("alice", uuid="11111111-1111-1111-1111-111111111111")],
"flow": None,
"method": "2022-blake3-aes-128-gcm",
"transport": {"type": "raw", "path": "/", "host": None, "mode": None, "serviceName": "", "trustedXForwardedFor": []},
"tls": {"enable": False, "certificateFile": None, "keyFile": None, "serverName": None},
"reality": {"enable": False, "dest": "", "serverNames": [], "privateKey": None, "privateKeyFile": None, "publicKey": None, "shortIds": [""]},
"xrayJson": None,
"jsonFile": None,
}
spec = self.spec(listener, other)
awg_inbound.prepare(spec, self.awg, self.runtime)
rendered = build_inbounds(spec, "vpn.example.com")
inbound = next(ib for ib in rendered["inbounds"] if ib["tag"] == "awg-in")
self.assertEqual(inbound["protocol"], "tunnel")
self.assertEqual((inbound["listen"], inbound["port"]), ("127.0.0.1", 18700))
self.assertEqual(inbound["streamSettings"]["sockopt"]["tproxy"], "tproxy")
self.assertTrue(inbound["settings"]["followRedirect"])
awg_links = [link for link in rendered["links"] if link["tag"] == "awg-in"]
self.assertEqual([link["user"] for link in awg_links], ["alice", "bob"])
for link in awg_links:
self.assertEqual(link["port"], 443)
self.assertTrue(link["link"].startswith("vpn://"))
self.assertIn("Endpoint = vpn.example.com:443", link["config"])
# Subscriptions carry only what v2ray-style clients read.
for subscription in rendered["subscriptions"]:
body = base64.b64decode(subscription["body"]).decode()
self.assertNotIn("vpn://", body)
class PeerCounterTests(Fixture):
def test_counters_are_matched_to_users(self):
listener = self.listener()
spec = self.spec(listener, self.listener(tag="down", subnet="10.67.0.0/24"))
awg_inbound.prepare(spec, self.awg, self.runtime)
state = self.state(listener)
alice = state["users"]["alice"]["publicKey"]
bob = state["users"]["bob"]["publicKey"]
dump = (
"private\tpublic\t51820\toff\n"
f"{alice}\tpsk\t203.0.113.5:40000\t10.66.0.2/32\t1790000000\t1000\t2000\t25\n"
f"{bob}\tpsk\t(none)\t10.66.0.3/32\t0\t0\t0\t25\n"
"stranger\t(none)\t(none)\t10.66.0.9/32\t0\t5\t5\toff\n"
)
os.environ["AWG_DUMP_awgi_awg_in"] = dump
try:
peers = awg_inbound.peer_counters(spec, self.awg)
finally:
del os.environ["AWG_DUMP_awgi_awg_in"]
self.assertEqual(
peers,
[
{"key": alice, "endpoint": "203.0.113.5:40000", "handshake": 1790000000, "rx": 1000, "tx": 2000, "interface": "awgi-awg-in", "tag": "awg-in", "user": "alice"},
{"key": bob, "endpoint": None, "handshake": 0, "rx": 0, "tx": 0, "interface": "awgi-awg-in", "tag": "awg-in", "user": "bob"},
],
)
if __name__ == "__main__":
unittest.main()