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

+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