feat: warp/awg and hysteria2 improvements

This commit is contained in:
fufsob committed 2026-09-28 15:26:52 +00:00
1 parent d25fcb5468
commit cd3aa5a53f
24 files changed
+676 -18

No files matched your search

+11
View File
@@ -15,6 +15,7 @@ Part of the [proxy-suite options reference](./index.md).
- [asOutbound](#services-proxy-suite-amneziawg-profiles-name-asoutbound)
- [autostart](#services-proxy-suite-amneziawg-profiles-name-autostart)
- [configFile](#services-proxy-suite-amneziawg-profiles-name-configfile)
- [domainStrategy](#services-proxy-suite-amneziawg-profiles-name-domainstrategy)
- [endpoint](#services-proxy-suite-amneziawg-profiles-name-endpoint)
- [interfaceName](#services-proxy-suite-amneziawg-profiles-name-interfacename)
- [settings](#services-proxy-suite-amneziawg-profiles-name-settings)
@@ -138,6 +139,16 @@ File with an AmneziaWG \.conf\.
**Type:** null or string\
**Default:** `null`
<a id="services-proxy-suite-amneziawg-profiles-name-domainstrategy"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.domainStrategy
Which address family the outbound dials a name over first\. Ignored with
` asOutbound = "userspace" `\. ` null `: the backend’s default\.
**Type:** null or one of “prefer_ipv4”, “prefer_ipv6”, “ipv4_only”, “ipv6_only”\
**Default:** `null`\
**Example:** `"prefer_ipv6"`
<a id="services-proxy-suite-amneziawg-profiles-name-endpoint"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.endpoint
+99
View File
@@ -11,6 +11,7 @@ Part of the [proxy-suite options reference](./index.md).
- [package](#services-proxy-suite-inbounds-package)
- [listeners](#services-proxy-suite-inbounds-listeners)
- `<name>`
- [acceptProxyProtocol](#services-proxy-suite-inbounds-listeners-name-acceptproxyprotocol)
- [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)
@@ -60,8 +61,14 @@ Part of the [proxy-suite options reference](./index.md).
- [flow](#services-proxy-suite-inbounds-listeners-name-flow)
- hysteria
- [masquerade](#services-proxy-suite-inbounds-listeners-name-hysteria-masquerade)
- [portHopping](#services-proxy-suite-inbounds-listeners-name-hysteria-porthopping)
- salamander
- [enable](#services-proxy-suite-inbounds-listeners-name-hysteria-salamander-enable)
- [password](#services-proxy-suite-inbounds-listeners-name-hysteria-salamander-password)
- [passwordFile](#services-proxy-suite-inbounds-listeners-name-hysteria-salamander-passwordfile)
- [jsonFile](#services-proxy-suite-inbounds-listeners-name-jsonfile)
- [method](#services-proxy-suite-inbounds-listeners-name-method)
- [order](#services-proxy-suite-inbounds-listeners-name-order)
- [port](#services-proxy-suite-inbounds-listeners-name-port)
- [reality](#services-proxy-suite-inbounds-listeners-name-reality)
- [enable](#services-proxy-suite-inbounds-listeners-name-reality-enable)
@@ -71,8 +78,10 @@ Part of the [proxy-suite options reference](./index.md).
- [publicKey](#services-proxy-suite-inbounds-listeners-name-reality-publickey)
- [serverNames](#services-proxy-suite-inbounds-listeners-name-reality-servernames)
- [shortIds](#services-proxy-suite-inbounds-listeners-name-reality-shortids)
- [xver](#services-proxy-suite-inbounds-listeners-name-reality-xver)
- [serverPassword](#services-proxy-suite-inbounds-listeners-name-serverpassword)
- [serverPasswordFile](#services-proxy-suite-inbounds-listeners-name-serverpasswordfile)
- [shareAddress](#services-proxy-suite-inbounds-listeners-name-shareaddress)
- [sharePort](#services-proxy-suite-inbounds-listeners-name-shareport)
- [tls](#services-proxy-suite-inbounds-listeners-name-tls)
- [enable](#services-proxy-suite-inbounds-listeners-name-tls-enable)
@@ -171,6 +180,20 @@ Server listeners, by tag\.
````
<a id="services-proxy-suite-inbounds-listeners-name-acceptproxyprotocol"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.acceptProxyProtocol
Read the client address from a PROXY protocol header (v1 or v2) that opens every
connection, as sent by a TCP front such as nginx’s ` stream ` with ` proxy_protocol on `\.
Without it such a listener records every client as the front’s address, which
` proxy-ctl inbounds online ` never counts\. TCP listeners only\.
Every connection must carry the header, so only set it on a listener nothing but
the front can reach, such as one on loopback\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-inbounds-listeners-name-address"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.address
@@ -581,6 +604,51 @@ Site shown to anything that is not a hysteria2 client, such as browsers and prob
**Default:** `null`\
**Example:** `"https://www.example.com"`
<a id="services-proxy-suite-inbounds-listeners-name-hysteria-porthopping"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.hysteria\.portHopping
UDP port range redirected to ` port ` (nftables, NixOS only), which clients hop across
every half a minute or so\. A single throttled or blocked flow then lasts until the
next hop instead of for the whole session\. Share links name it as ` mport `; clients
that do not know it stay on ` port `\.
Keep it clear of ports other services on this host receive on, and below the
ephemeral range (32768 and up on Linux)\.
**Type:** null or string matching the pattern \[0-9]±\[0-9]+\
**Default:** `null`\
**Example:** `"20000-30000"`
<a id="services-proxy-suite-inbounds-listeners-name-hysteria-salamander-enable"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.hysteria\.salamander\.enable
Salamander obfuscation: every packet is scrambled with a shared password, so the
traffic no longer looks like QUIC (no visible handshake or SNI) but like random
UDP\. Clients need the password, which the share links carry; those without it
cannot connect, and probes no longer reach ` masquerade `\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-inbounds-listeners-name-hysteria-salamander-password"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.hysteria\.salamander\.password
Salamander password\. Ends up in the Nix store; prefer ` passwordFile `\.
**Type:** null or string\
**Default:** `null`\
**Example:** `"hunter2"`
<a id="services-proxy-suite-inbounds-listeners-name-hysteria-salamander-passwordfile"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.hysteria\.salamander\.passwordFile
File with the Salamander password\. With neither this nor ` password `, one is
generated on first start and kept in the state directory\.
**Type:** null or string\
**Default:** `null`\
**Example:** `"/run/secrets/proxy-inbound-salamander"`
<a id="services-proxy-suite-inbounds-listeners-name-jsonfile"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.jsonFile
@@ -599,6 +667,16 @@ Shadowsocks cipher\. 2022 ciphers take a base64 key of matching length as the pa
**Default:** `"2022-blake3-aes-128-gcm"`\
**Example:** `"aes-128-gcm"`
<a id="services-proxy-suite-inbounds-listeners-name-order"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.order
Position in subscriptions and link listings, lowest first; listeners with the same
order follow their tags alphabetically\. Clients usually pick the first entry\.
**Type:** signed integer\
**Default:** `1000`\
**Example:** `0`
<a id="services-proxy-suite-inbounds-listeners-name-port"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.port
@@ -676,6 +754,16 @@ Accepted short IDs (hex)\. The first goes into share links\.
**Default:** `[ "" ]`\
**Example:** `[ "0123abcd" ]`
<a id="services-proxy-suite-inbounds-listeners-name-reality-xver"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.reality\.xver
PROXY protocol version sent to ` dest ` with each forwarded connection, or 0 for none\.
Lets a ` dest ` on this host that expects the header (nginx with ` proxy_protocol `)
see the visitor’s address instead of XRay’s\.
**Type:** one of 0, 1, 2\
**Default:** `0`
<a id="services-proxy-suite-inbounds-listeners-name-serverpassword"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.serverPassword
@@ -694,6 +782,17 @@ File with the server key\.
**Default:** `null`\
**Example:** `"/run/secrets/proxy-inbound-ss-server-key"`
<a id="services-proxy-suite-inbounds-listeners-name-shareaddress"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.shareAddress
Address in this listener’s share links (and the default SNI of their TLS), instead of
` inbounds.serverAddress `: a name of its own, so the name clients look up is the one
they then send as SNI\. Links of listeners behind its fallbacks use it too\.
**Type:** null or string\
**Default:** `null`\
**Example:** `"cdn.example.com"`
<a id="services-proxy-suite-inbounds-listeners-name-shareport"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.sharePort
+1
View File
@@ -316,6 +316,7 @@ services.proxy-suite = {
asOutbound = null;
autostart = false;
configFile = null;
domainStrategy = if config.networking.enableIPv6 then "prefer_ipv6" else "prefer_ipv4";
enable = false;
endpoint = null;
generatorUrl = null;
+12
View File
@@ -12,6 +12,7 @@ Part of the [proxy-suite options reference](./index.md).
- [asOutbound](#services-proxy-suite-warp-asoutbound)
- [autostart](#services-proxy-suite-warp-autostart)
- [configFile](#services-proxy-suite-warp-configfile)
- [domainStrategy](#services-proxy-suite-warp-domainstrategy)
- [endpoint](#services-proxy-suite-warp-endpoint)
- [generatorUrl](#services-proxy-suite-warp-generatorurl)
@@ -67,6 +68,17 @@ through the local proxy if enabled\. WARP does not work until that succeeds\.
**Default:** `null`\
**Example:** `"/run/secrets/wgcf-profile.conf"`
<a id="services-proxy-suite-warp-domainstrategy"></a>
## services\.proxy-suite\.warp\.domainStrategy
Which address family the “warp” outbound dials a name over first\. Ignored with
` asOutbound = "userspace" `\. Also applies to names resolved by the inbounds’
` routing.blockPrivate ` check, unless ` proxy.dns.strategy ` is set\.
**Type:** null or one of “prefer_ipv4”, “prefer_ipv6”, “ipv4_only”, “ipv6_only”\
**Default:** `if config.networking.enableIPv6 then "prefer_ipv6" else "prefer_ipv4"`\
**Example:** `"prefer_ipv4"`
<a id="services-proxy-suite-warp-endpoint"></a>
## services\.proxy-suite\.warp\.endpoint
+40 -1
View File
@@ -449,7 +449,12 @@ let
description = "proxy-suite AmneziaWG tunnel behind the ${ob.name} outbound";
unit = serviceName ob.name;
engine = ob.kind;
inherit (ob) tag tunnelPort directPort;
inherit (ob)
tag
tunnelPort
directPort
domainStrategy
;
profile = ''
${lib.optionalString (profile.configFile != null) ''
# It may not exist yet: WARP's appears once proxy-suite-warp has registered.
@@ -467,9 +472,14 @@ let
# WireGuard rekey every RekeyAfterTime (120 seconds by default); a handshake older than that
# on two checks in a row is a rekey that is not getting through, so the interface moves to
# a new port.
#
# An outbound interface also fetches proxy.urlTest.url over IPv4 through the tunnel, since a
# peer can keep rekeying while carrying no traffic. After three misses the peer is re-added
# for a fresh session (a new port alone keeps the old one), at most once in five minutes.
mkWatchdog =
name: profile:
let
egressProbe = profile.asOutbound == "interface";
watchdog = pkgs.writeShellScript "proxy-suite-awg" ''
set -uo pipefail
read -r _ probe rekey < <(${pkgs.python3}/bin/python3 ${configTool} \
@@ -479,6 +489,23 @@ let
exec ${pkgs.coreutils}/bin/sleep infinity
fi
${mkHandshakeHelpers profile}
${lib.optionalString egressProbe ''
new_session() {
local peers
peers=$("$awg" showconf "$interface" | ${pkgs.gawk}/bin/awk '/^\[Peer\]/ { p = 1 } p') || return
[[ -n $peers ]] || return
new_source_port
"$awg" show "$interface" peers | while read -r peer; do
"$awg" set "$interface" peer "$peer" remove || true
done
"$awg" addconf "$interface" <(printf '%s\n' "$peers") || true
}
# Only an interface with IPv4 can be judged by it.
probe_egress=0
[[ -n $(${pkgs.iproute2}/bin/ip -4 -o addr show dev "$interface") ]] && probe_egress=1
misses=0
last_session=-300
''}
stale=0
while sleep 15; do
${pingVia profile} -W 2 "$probe" >/dev/null 2>&1 || true
@@ -488,7 +515,19 @@ let
echo "proxy-suite: AmneziaWG profile '${name}' is not rekeying; moving to a new source port" >&2
new_source_port
stale=0
${lib.optionalString egressProbe "continue"}
fi
${lib.optionalString egressProbe ''
if (( !probe_egress )) || ${pkgs.curl}/bin/curl -4 -s --noproxy "*" --interface "$interface" -m 5 -o /dev/null \
${lib.escapeShellArg cfg.proxy.urlTest.url}; then
misses=0
elif (( ++misses >= 3 && SECONDS - last_session >= 300 )); then
echo "proxy-suite: AmneziaWG profile '${name}' carries no IPv4 past its peer; starting a new session" >&2
new_session
misses=0
last_session=$SECONDS
fi
''}
done
'';
in
+5
View File
@@ -76,6 +76,8 @@ let
type
port
sharePort
shareAddress
acceptProxyProtocol
users
flow
method
@@ -89,6 +91,8 @@ let
jsonFile
;
listen = ib.listener.address;
# Where a Salamander password given neither inline nor as a file is kept.
salamanderStateFile = "${cfg.host.stateDir}/inbounds/${ib.tag}/salamander-password";
fallbacks = map renderFallback ib.listener.fallbacks;
# The listener in front, whose port and TLS or REALITY the share links carry.
front =
@@ -104,6 +108,7 @@ let
type
port
sharePort
shareAddress
tls
reality
;
+16 -4
View File
@@ -148,6 +148,7 @@ let
tag = name;
kind = profile.asOutbound;
interface = profile.interfaceName;
inherit (profile) domainStrategy;
# Loopback listeners of a "singBox" or "userspace" tunnel, as warpCfg.tunnelPort/directPort
# (only sing-box listens on directPort).
tunnelPort = awgTunnelBasePort + 2 * index;
@@ -164,10 +165,13 @@ let
proxyInboundsEnabled = proxyInboundsCfg.enable;
# Listeners as a list, with `via` resolved against the default.
proxyInbounds = lib.mapAttrsToList (tag: listener: {
inherit tag listener;
via = if listener.via == null then proxyInboundsCfg.routing.via else listener.via;
}) proxyInboundsCfg.listeners;
# By order, then tag: the attrset yields tags alphabetically and the sort is stable.
proxyInbounds = builtins.sort (a: b: a.listener.order < b.listener.order) (
lib.mapAttrsToList (tag: listener: {
inherit tag listener;
via = if listener.via == null then proxyInboundsCfg.routing.via else listener.via;
}) proxyInboundsCfg.listeners
);
# .onion names from clients go to the local proxy, whose rule hands them to Tor, whatever
# the listener's via. AmneziaWG listeners never pass XRay's routing.
@@ -196,6 +200,12 @@ let
&& proxyInboundsCfg.routing.blockPrivate
&& proxyInboundsNeedLocalProxy
&& !pureXrayEnabled;
# The guard's resolved addresses are dialed in its order, so it follows WARP's preference.
proxyInboundsGuardStrategy =
if proxyCfg.dns.strategy == null && warpCfg.enable && warpCfg.asOutbound != null then
warpCfg.domainStrategy
else
null;
# Other vias name static outbounds, rendered into the inbound service's own config.
proxyInboundViaTags = lib.unique (
@@ -547,10 +557,12 @@ in
proxyInboundsEnabled
proxyInbounds
proxyInboundsAwg
proxyInboundIsUdpOnly
proxyInboundsRouteOnion
proxyInboundsNeedLocalProxy
proxyInboundsResolveInSingBox
proxyInboundsGuardPrivate
proxyInboundsGuardStrategy
proxyInboundViaTags
proxyInboundViaOutbounds
invalidInboundViaTargets
+8
View File
@@ -59,6 +59,10 @@ in
security.polkit.extraConfig = forwardWith lib.mkAfter internal.polkit.rules;
networking.nftables.enable = lib.mkIf cfg.internal.nftables (lib.mkDefault true);
networking.nftables.tables = lib.mapAttrs (_: content: {
family = "inet";
inherit content;
}) cfg.internal.nftablesTables;
networking.firewall = {
allowedTCPPorts = forward internal.firewall.allowedTCPPorts;
allowedUDPPorts = forward internal.firewall.allowedUDPPorts;
@@ -71,6 +75,10 @@ in
boot.kernel.sysctl = lib.mapAttrs (_: lib.mkDefault) cfg.internal.sysctl;
assertions = [
{
assertion = cfg.internal.nftablesTables == { } || config.networking.nftables.enable;
message = "proxy-suite: hysteria.portHopping needs nftables (networking.nftables.enable)";
}
{
assertion =
cfg.internal.firewall.extraInputRules == ""
+2
View File
@@ -66,6 +66,8 @@ in
rules = internalOption types.lines "";
};
nftables = internalOption types.bool false;
# nftables tables by name, family inet (NixOS only): NAT the firewall option cannot express.
nftablesTables = internalOption (types.attrsOf types.lines) { };
# ../helpers.nix, which the NixOS and home-manager adapters publish as
# config.lib.proxy-suite; the other hosts have no config.lib.
helpers = internalOption types.raw { };
@@ -199,6 +199,22 @@ let
'';
};
endpoint = endpoint "host:port (IPv6 in brackets) that replaces the first peer's endpoint.";
domainStrategy = mkOption {
type = types.nullOr (
types.enum [
"prefer_ipv4"
"prefer_ipv6"
"ipv4_only"
"ipv6_only"
]
);
default = null;
description = ''
Which address family the outbound dials a name over first. Ignored with
`asOutbound = "userspace"`. `null`: the backend's default.
'';
example = "prefer_ipv6";
};
allowConfigHooks = mkOption {
type = types.bool;
default = false;
@@ -238,6 +238,20 @@ let
description = "Accepted short IDs (hex). The first goes into share links.";
example = [ "0123abcd" ];
};
xver = mkOption {
type = types.enum [
0
1
2
];
default = 0;
description = ''
PROXY protocol version sent to `dest` with each forwarded connection, or 0 for none.
Lets a `dest` on this host that expects the header (nginx with `proxy_protocol`)
see the visitor's address instead of XRay's.
'';
};
};
};
@@ -328,6 +342,12 @@ let
example = 443;
};
shareAddress = nullStr ''
Address in this listener's share links (and the default SNI of their TLS), instead of
`inbounds.serverAddress`: a name of its own, so the name clients look up is the one
they then send as SNI. Links of listeners behind its fallbacks use it too.
'' "cdn.example.com";
address = mkOption {
type = types.strMatching "[^[:space:]]+";
default = "::";
@@ -335,8 +355,32 @@ let
example = "127.0.0.1";
};
acceptProxyProtocol = mkOption {
type = types.bool;
default = false;
description = ''
Read the client address from a PROXY protocol header (v1 or v2) that opens every
connection, as sent by a TCP front such as nginx's `stream` with `proxy_protocol on`.
Without it such a listener records every client as the front's address, which
`proxy-ctl inbounds online` never counts. TCP listeners only.
Every connection must carry the header, so only set it on a listener nothing but
the front can reach, such as one on loopback.
'';
};
via = nullStr "Where this listener's traffic exits, as in `inbounds.routing.via`. `null`: use that default." "nl-vps";
order = mkOption {
type = types.int;
default = 1000;
description = ''
Position in subscriptions and link listings, lowest first; listeners with the same
order follow their tags alphabetically. Clients usually pick the first entry.
'';
example = 0;
};
users = mkOption {
type = types.listOf userType;
default = [ ];
@@ -413,6 +457,39 @@ let
`null`: answer 404.
'' "https://www.example.com";
hysteria.salamander = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Salamander obfuscation: every packet is scrambled with a shared password, so the
traffic no longer looks like QUIC (no visible handshake or SNI) but like random
UDP. Clients need the password, which the share links carry; those without it
cannot connect, and probes no longer reach `masquerade`.
'';
};
password = nullStr "Salamander password. Ends up in the Nix store; prefer `passwordFile`." "hunter2";
passwordFile = nullStr ''
File with the Salamander password. With neither this nor `password`, one is
generated on first start and kept in the state directory.
'' "/run/secrets/proxy-inbound-salamander";
};
hysteria.portHopping = mkOption {
type = types.nullOr (types.strMatching "[0-9]+-[0-9]+");
default = null;
description = ''
UDP port range redirected to `port` (nftables, NixOS only), which clients hop across
every half a minute or so. A single throttled or blocked flow then lasts until the
next hop instead of for the whole session. Share links name it as `mport`; clients
that do not know it stay on `port`.
Keep it clear of ports other services on this host receive on, and below the
ephemeral range (32768 and up on Linux).
'';
example = "20000-30000";
};
amneziaWg = mkOption {
type = mkAmneziaWgType name;
default = { };
+26 -2
View File
@@ -1,7 +1,12 @@
{ lib, ... }:
{ config, lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
inherit (lib)
literalExpression
mkEnableOption
mkOption
types
;
inherit (import ./lib.nix { inherit lib; }) endpoint;
in
{
@@ -59,6 +64,25 @@ in
'';
};
domainStrategy = mkOption {
type = types.nullOr (
types.enum [
"prefer_ipv4"
"prefer_ipv6"
"ipv4_only"
"ipv6_only"
]
);
default = if config.services.proxy-suite.host.enableIPv6 then "prefer_ipv6" else "prefer_ipv4";
defaultText = literalExpression ''if config.networking.enableIPv6 then "prefer_ipv6" else "prefer_ipv4"'';
description = ''
Which address family the "warp" outbound dials a name over first. Ignored with
`asOutbound = "userspace"`. Also applies to names resolved by the inbounds'
`routing.blockPrivate` check, unless `proxy.dns.strategy` is set.
'';
example = "prefer_ipv4";
};
asAmneziaWg = mkOption {
type = types.bool;
default = false;
@@ -617,6 +617,41 @@ let
(mkAssertion (
!proxyInboundsEnabled || l.hysteria.masquerade == null || l.type == "hysteria2"
) "${prefix}: hysteria.masquerade is for hysteria2 listeners only")
(mkAssertion (
!proxyInboundsEnabled
|| (!l.hysteria.salamander.enable && l.hysteria.portHopping == null)
|| l.type == "hysteria2"
) "${prefix}: hysteria.salamander and hysteria.portHopping are for hysteria2 listeners only")
(mkAssertion (
!proxyInboundsEnabled
|| l.hysteria.salamander.password == null
|| l.hysteria.salamander.passwordFile == null
) "${prefix}: set at most one of hysteria.salamander.password and passwordFile")
(mkAssertion (
!proxyInboundsEnabled
|| l.hysteria.portHopping == null
|| (
let
bounds = map lib.toInt (lib.splitString "-" l.hysteria.portHopping);
in
builtins.elemAt bounds 0 >= 1
&& builtins.elemAt bounds 0 <= builtins.elemAt bounds 1
&& builtins.elemAt bounds 1 <= 65535
)
) "${prefix}: hysteria.portHopping must be a range \"from-to\" within 1-65535, from <= to")
# The redirect is an nftables table, which only the NixOS adapter installs.
(mkAssertion (
!proxyInboundsEnabled || l.hysteria.portHopping == null || hostKind == "nixos"
) "${prefix}: hysteria.portHopping needs a NixOS host")
# A PROXY header opens a TCP stream; raw JSON listeners set their own sockopt.
(mkAssertion
(
!proxyInboundsEnabled
|| !l.acceptProxyProtocol
|| (l.type != null && l.type != "amneziawg" && !derived.proxyInboundIsUdpOnly l)
)
"${prefix}: acceptProxyProtocol is for TCP listeners with a type (not hysteria2, amneziawg, h3-only xhttp, xrayJson or jsonFile)"
)
(mkAssertion (
!proxyInboundsEnabled
|| l.fallbacks == [ ]
+16
View File
@@ -48,6 +48,12 @@ let
builtinTags
;
constants = derived.constants;
hopRedirects = lib.concatMapStrings (
ib:
lib.optionalString (ib.listener.type == "hysteria2" && ib.listener.hysteria.portHopping != null) ''
fib daddr type local udp dport ${ib.listener.hysteria.portHopping} redirect to :${toString ib.listener.port}
''
) derived.proxyInbounds;
routingScripts = import ./routing-scripts.nix { inherit (context) ctx; };
serviceUnits = import ./units.nix {
@@ -98,6 +104,16 @@ lib.mkMerge [
|| perAppZapretEnabled
) true;
# hysteria2 port hopping: the range lands on the listener's port before the firewall
# sees it, so only that port needs opening.
nftablesTables = lib.mkIf (proxyInboundsEnabled && hopRedirects != "") {
proxy-suite-hysteria-hop = ''
chain prerouting {
type nat hook prerouting priority dstnat; policy accept;
${hopRedirects}}
'';
};
# Inbound listeners are reached from outside, so their ports have to be open.
firewall = lib.mkMerge [
(lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
@@ -3,6 +3,7 @@
pureXrayEnabled,
selectionMode,
proxyInboundsGuardPrivate,
proxyInboundsGuardStrategy ? null,
userDnsRules ? [ ],
}:
@@ -120,7 +121,11 @@ else
# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local
# mixed-in clients lose names that resolve private. Rules for other inbounds do not count:
# autoProxy's direct probe pin would put the guard first, resolving every name, .onion too.
| [{inbound: ["mixed-in"], action: "resolve"},
| [{inbound: ["mixed-in"], action: "resolve"${
lib.optionalString (
proxyInboundsGuardStrategy != null
) ", strategy: \"${proxyInboundsGuardStrategy}\""
}},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard
| (.route.rules
| map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null)
@@ -405,12 +405,29 @@ let
}
// lib.optionalAttrs (routingMark != null) { mark = routingMark; };
}
// lib.optionalAttrs (ob.domainStrategy != null) {
settings.domainStrategy =
{
prefer_ipv4 = "UseIPv4v6";
prefer_ipv6 = "UseIPv6v4";
ipv4_only = "UseIPv4";
ipv6_only = "UseIPv6";
}
.${ob.domainStrategy};
}
else
{
type = "direct";
inherit (ob) tag;
bind_interface = ob.interface;
domain_resolver = constants.awgDnsServerTag ob.tag;
domain_resolver =
if ob.domainStrategy == null then
constants.awgDnsServerTag ob.tag
else
{
server = constants.awgDnsServerTag ob.tag;
strategy = ob.domainStrategy;
};
}
// lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }
);
+2
View File
@@ -23,6 +23,7 @@ let
xray
proxyInboundsCfg
proxyInboundsGuardPrivate
proxyInboundsGuardStrategy
routeModeRulesFile
tproxyFile
tunFile
@@ -156,6 +157,7 @@ let
pureXrayEnabled
selectionMode
proxyInboundsGuardPrivate
proxyInboundsGuardStrategy
;
userDnsRules = proxyCfg.dns.singBox.rules;
};
+7 -2
View File
@@ -94,7 +94,7 @@ in
services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) {
warp = {
configFile = w.profilePath;
inherit (w) endpoint;
inherit (w) endpoint domainStrategy;
asOutbound = lib.mkIf viaAmneziaWg w.asOutbound;
autostart = lib.mkIf w.autostart true;
};
@@ -113,7 +113,12 @@ in
until [ -s "$profile" ]; do sleep 5; done
fi
'';
inherit (w) tunnelPort directPort endpoint;
inherit (w)
tunnelPort
directPort
endpoint
domainStrategy
;
};
})
+16 -2
View File
@@ -87,6 +87,7 @@ let
tunnelPort,
directPort,
endpoint,
domainStrategy,
}:
{
convert = ''
@@ -100,7 +101,17 @@ let
(${builtins.toJSON (dnsServer "remote" cfg.proxy.dns.remote)} + {detour: "${tag}", domain_resolver: "local"})
]},
route: {
default_domain_resolver: "remote",
default_domain_resolver: ${
builtins.toJSON (
if domainStrategy == null then
"remote"
else
{
server = "remote";
strategy = domainStrategy;
}
)
},
rules: [{inbound: ["direct-in"], outbound: "direct"}],
final: "${tag}"
},
@@ -134,7 +145,8 @@ let
# `profile` is a shell snippet, run as root on a privileged host, that sets $profile to
# the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort,
# and `endpoint`, a host:port in place of the profile's Endpoint.
# `endpoint`, a host:port in place of the profile's Endpoint, and `domainStrategy`, the
# address family it dials destinations over first.
mkTunnel =
{
description,
@@ -144,6 +156,7 @@ let
tunnelPort,
directPort ? null,
endpoint ? null,
domainStrategy ? null,
engine ? "singBox",
}:
let
@@ -153,6 +166,7 @@ let
tunnelPort
directPort
endpoint
domainStrategy
;
};
tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
+116
View File
@@ -184,6 +184,23 @@ let
};
};
firewallSpec = mkInboundsSpec firewallFixture;
firewallNft = firewallFixture.config.networking.nftables.tables;
hopFixture = mkInbounds {
listeners.hy2-in = {
type = "hysteria2";
port = 443;
users = [ { passwordFile = "/run/secrets/hy2"; } ];
tls = {
certificateFile = "/c";
keyFile = "/k";
};
hysteria.salamander.enable = true;
hysteria.portHopping = "20000-30000";
};
};
hopSpec = lib.head (mkInboundsSpec hopFixture).listeners;
hopTable = hopFixture.config.networking.nftables.tables.proxy-suite-hysteria-hop;
wsListener = lib.head (builtins.filter (l: l.tag == "ws-in") firewallSpec.listeners);
# A ws listener behind a TLS front's fallback, and a decoy web server.
@@ -592,6 +609,57 @@ let
}
) "needs both tls.certificateFile and tls.keyFile")
# A PROXY header opens a TCP stream; QUIC has none to open.
(mkRejects (
baseProxy
// {
inbounds = {
enable = true;
listeners.hy2-in = {
type = "hysteria2";
port = 8444;
users = [ { passwordFile = "/run/secrets/hy2"; } ];
acceptProxyProtocol = true;
tls = {
certificateFile = "/c";
keyFile = "/k";
};
};
};
}
) "acceptProxyProtocol is for TCP listeners")
(mkRejects (
baseProxy
// {
inbounds = {
enable = true;
listeners.vless-in = realityListener // {
hysteria.salamander.enable = true;
};
};
}
) "hysteria.salamander and hysteria.portHopping are for hysteria2 listeners only")
(mkRejects (
baseProxy
// {
inbounds = {
enable = true;
listeners.hy2-in = {
type = "hysteria2";
port = 443;
users = [ { passwordFile = "/run/secrets/hy2"; } ];
hysteria.portHopping = "30000-20000";
tls = {
certificateFile = "/c";
keyFile = "/k";
};
};
};
}
) "hysteria.portHopping must be a range")
(mkRejects (
baseProxy
// {
@@ -811,6 +879,54 @@ let
true
)
(ok (wsListener.port == 10002 && wsListener.sharePort == 443))
# hysteria2 port hopping: the range is redirected to the listener's port, which alone
# stays open; nothing is installed without it.
(ok (
hopTable.family == "inet"
&& lib.hasInfix "udp dport 20000-30000 redirect to :443" hopTable.content
&& lib.hasInfix "type nat hook prerouting" hopTable.content
))
(ok (!(firewallNft ? proxy-suite-hysteria-hop)))
(ok (hopSpec.hysteria.salamander.enable && hopSpec.hysteria.portHopping == "20000-30000"))
(ok (lib.hasSuffix "/inbounds/hy2-in/salamander-password" hopSpec.salamanderStateFile))
# Lowest order first, then tags alphabetically: links and subscriptions follow the spec.
(ok (
map (l: l.tag)
(mkInboundsSpec (mkInbounds {
listeners = {
a-in = realityListener // {
port = 8441;
};
b-in = realityListener // {
port = 8442;
order = 0;
};
c-in = realityListener // {
port = 8443;
};
};
})).listeners == [
"b-in"
"a-in"
"c-in"
]
))
# Off unless asked for, and handed to the script with REALITY's xver.
(ok (!wsListener.acceptProxyProtocol))
(ok (
let
spec =
lib.head
(mkInboundsSpec (mkInbounds {
listeners.vless-in = lib.recursiveUpdate realityListener {
address = "127.0.0.1";
acceptProxyProtocol = true;
reality.xver = 2;
};
})).listeners;
in
spec.acceptProxyProtocol && spec.reality.xver == 2
))
# A fallback to a listener is resolved to its address, in PROXY protocol; a dest is kept as is.
(ok (
(fallbackSpecListener "front-in").fallbacks == [
+53 -5
View File
@@ -11,6 +11,8 @@ without changing the spec or the link generator.
import base64
import hashlib
import json
import os
import secrets
import urllib.parse
from awg_inbound import client_entries
@@ -57,6 +59,34 @@ def _server_secret(listener: dict, tag: str) -> str:
)
def _salamander(listener: dict) -> str | None:
"""The Salamander password of a hysteria2 listener that obfuscates, else None.
Given inline or as a file; otherwise generated on first start and kept in the
state file, so share links stay the same across restarts.
"""
salamander = (listener.get("hysteria") or {}).get("salamander") or {}
if not salamander.get("enable"):
return None
if salamander.get("password") is not None or salamander.get("passwordFile") is not None:
return _resolve(
salamander.get("password"), salamander.get("passwordFile"), "salamander password", listener["tag"]
)
path = listener["salamanderStateFile"]
try:
stored = _read_secret(path)
except FileNotFoundError:
stored = ""
if stored:
return stored
os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
generated = secrets.token_urlsafe(24)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(generated + "\n")
return generated
def _b64(value: str) -> str:
"""base64 without padding, as share links carry it."""
return base64.urlsafe_b64encode(value.encode("utf-8")).decode("ascii").rstrip("=")
@@ -100,12 +130,16 @@ def _xray_stream(listener: dict, tag: str) -> dict:
masquerade = (listener.get("hysteria") or {}).get("masquerade")
if masquerade:
settings["masquerade"] = {"type": "proxy", "url": masquerade, "rewriteHost": True}
return {
stream = {
"network": "hysteria",
"hysteriaSettings": settings,
"security": "tls",
"tlsSettings": _tls_settings(listener["tls"], ["h3"]),
}
salamander = _salamander(listener)
if salamander is not None:
stream["finalmask"] = {"udp": [{"type": "salamander", "settings": {"password": salamander}}]}
return stream
transport = listener["transport"]
network = transport["type"]
@@ -126,8 +160,9 @@ def _xray_stream(listener: dict, tag: str) -> dict:
# online; the forwarded address is only trusted when one of these headers is present.
if transport.get("trustedXForwardedFor"):
stream.setdefault("sockopt", {})["trustedXForwardedFor"] = transport["trustedXForwardedFor"]
# Behind another listener's fallback, the client address arrives in PROXY protocol.
if listener.get("front"):
# Behind another listener's fallback or a TCP front, the client address arrives in
# PROXY protocol.
if listener.get("front") or listener.get("acceptProxyProtocol"):
stream.setdefault("sockopt", {})["acceptProxyProtocol"] = True
reality = listener["reality"]
@@ -146,6 +181,8 @@ def _xray_stream(listener: dict, tag: str) -> dict:
),
"shortIds": reality["shortIds"],
}
if reality.get("xver"):
stream["realitySettings"]["xver"] = reality["xver"]
elif tls["enable"] or listener["type"] == "trojan":
stream["security"] = "tls"
stream["tlsSettings"] = _tls_settings(tls)
@@ -312,6 +349,12 @@ def build_share_link(
if user_index < 0 or user_index >= len(users):
raise ValueError(f"listener '{tag}': user index {user_index} is out of range")
# Behind another listener's fallback, clients dial that one, under its TLS or REALITY.
front = listener.get("front") or listener
# A listener with a name of its own is dialled by it, so the name clients look up is the
# one they then send as SNI; it is also the default SNI.
server_address = front.get("shareAddress") or server_address
user = users[user_index]
secret = _user_secret(user, listener_type, tag)
user_name = user.get("name") or f"{tag}-{user_index}"
@@ -319,8 +362,6 @@ def build_share_link(
fragment = urllib.parse.quote(label, safe="")
endpoint_address = onion_address or server_address
host = f"[{endpoint_address}]" if ":" in endpoint_address else endpoint_address
# Behind another listener's fallback, clients dial that one, under its TLS or REALITY.
front = listener.get("front") or listener
endpoint = f"{host}:{_share_port(front)}"
if listener_type == "vmess":
@@ -349,6 +390,13 @@ def build_share_link(
if listener_type == "hysteria2":
tls = listener["tls"]
params = {"sni": tls.get("serverName") or server_address, "alpn": ",".join(tls.get("alpn") or ["h3"])}
salamander = _salamander(listener)
if salamander is not None:
params.update({"obfs": "salamander", "obfs-password": salamander})
# v2rayN's name for the hop range; clients that do not know it stay on the port.
hopping = (listener.get("hysteria") or {}).get("portHopping")
if hopping:
params["mport"] = hopping
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
return f"hysteria2://{urllib.parse.quote(secret, safe='')}@{endpoint}?{query}#{fragment}"
+12
View File
@@ -161,6 +161,18 @@ def render_xray_outbound(ob: dict, routing_mark: int | None = None) -> dict:
}
if ob.get("password"):
stream["hysteriaSettings"]["auth"] = ob["password"]
# XRay wants udphop outermost, ahead of any other UDP mask.
if ob.get("server_ports"):
stream.setdefault("finalmask", {}).setdefault("udp", []).append(
{
"type": "udphop",
"settings": {
"mode": "intervalRemote",
"interval": "20-40",
"remotePorts": ",".join(r.replace(":", "-") for r in ob["server_ports"]),
},
}
)
if ob.get("obfs", {}).get("type") == "salamander":
stream.setdefault("finalmask", {}).setdefault("udp", []).append(
{
+6
View File
@@ -433,6 +433,12 @@ def parse_hysteria2(url: str, tag: str) -> dict:
if params.get("obfs") == "salamander":
ob["obfs"] = {"type": "salamander", "password": params.get("obfs-password", "")}
# Port hopping, as v2rayN writes it: "20000-30000", or several joined by commas. A fixed
# interval: hop_interval_max, which would randomise it, is newer than sing-box 1.13.
if params.get("mport"):
ob["server_ports"] = [r.strip().replace("-", ":") for r in params["mport"].split(",") if r.strip()]
ob["hop_interval"] = "30s"
return ob
+76
View File
@@ -18,6 +18,7 @@ def listener(**overrides):
"type": "vless",
"port": 443,
"sharePort": None,
"acceptProxyProtocol": False,
"listen": "::",
"via": "direct",
"users": [{"name": "", "uuid": "uuid-1", "uuidFile": None, "password": None, "passwordFile": None}],
@@ -40,6 +41,7 @@ def listener(**overrides):
"privateKeyFile": None,
"publicKey": None,
"shortIds": [""],
"xver": 0,
},
"xrayJson": None,
"jsonFile": None,
@@ -57,6 +59,7 @@ def reality(**overrides):
"privateKeyFile": None,
"publicKey": "public-key",
"shortIds": ["0123abcd"],
"xver": 0,
}
settings.update(overrides)
return settings
@@ -183,6 +186,19 @@ class RenderInboundTests(unittest.TestCase):
{"trustedXForwardedFor": ["X-Real-IP"], "acceptProxyProtocol": True},
)
def test_accept_proxy_protocol_behind_a_tcp_front(self):
"""nginx's stream front sends the client address in PROXY protocol, with no fallback involved."""
ib = render_xray_inbound(listener(acceptProxyProtocol=True, reality=reality()))
self.assertEqual(ib["streamSettings"]["sockopt"], {"acceptProxyProtocol": True})
self.assertNotIn("sockopt", render_xray_inbound(listener(reality=reality()))["streamSettings"])
def test_reality_xver_only_when_set(self):
self.assertNotIn("xver", render_xray_inbound(listener(reality=reality()))["streamSettings"]["realitySettings"])
self.assertEqual(
render_xray_inbound(listener(reality=reality(xver=2)))["streamSettings"]["realitySettings"]["xver"],
2,
)
def test_grpc_transport(self):
ib = render_xray_inbound(
listener(transport={"type": "grpc", "path": "/", "host": None, "serviceName": "GunService"})
@@ -447,6 +463,66 @@ class RoundTripTests(unittest.TestCase):
# Without masquerade XRay answers non-clients with 404; nothing to render.
plain = render_xray_inbound(dict(spec, hysteria={"masquerade": None}))
self.assertEqual(plain["streamSettings"]["hysteriaSettings"], {"version": 2})
self.assertNotIn("finalmask", plain["streamSettings"])
def test_hysteria2_salamander_and_hopping_reach_links(self):
salamander = {"enable": True, "password": "m@sk", "passwordFile": None}
spec = listener(
type="hysteria2",
users=[{"name": "phone", "password": "pw", "passwordFile": None}],
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": "hy.example.com"},
hysteria={"masquerade": None, "salamander": salamander, "portHopping": "20000-30000"},
)
self.assertEqual(
render_xray_inbound(spec)["streamSettings"]["finalmask"],
{"udp": [{"type": "salamander", "settings": {"password": "m@sk"}}]},
)
link = build_share_link(spec, "vpn.example.com")
params = link_params(link)
self.assertEqual((params["obfs"], params["obfs-password"], params["mport"]), ("salamander", "m@sk", "20000-30000"))
# The link reads back with both, into either backend.
ob = build_outbound(link, "hop", backend="sing-box")
self.assertEqual(ob["obfs"], {"type": "salamander", "password": "m@sk"})
self.assertEqual(ob["server_ports"], ["20000:30000"])
self.assertEqual(ob["server_port"], 443)
masks = build_outbound(link, "hop", backend="xray")["streamSettings"]["finalmask"]["udp"]
self.assertEqual([m["type"] for m in masks], ["udphop", "salamander"])
self.assertEqual(masks[0]["settings"]["remotePorts"], "20000-30000")
def test_share_address_is_dialled_and_the_default_sni(self):
tls = {"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None}
front = listener(shareAddress="cdn.example.com", tls=tls, flow="xtls-rprx-vision")
link = build_share_link(front, "vpn.example.com")
self.assertTrue(link.startswith("vless://uuid-1@cdn.example.com:443?"), link)
self.assertEqual(link_params(link)["sni"], "cdn.example.com")
# A listener behind its fallback is dialled the same way.
behind = listener(
port=10006,
address="127.0.0.1",
transport={"type": "xhttp", "path": "/x", "host": None, "mode": None, "serviceName": "", "trustedXForwardedFor": []},
front={"tag": "front-in", "type": "vless", "port": 443, "sharePort": None, "shareAddress": "cdn.example.com", "tls": tls, "reality": reality(enable=False)},
)
self.assertTrue(build_share_link(behind, "vpn.example.com").startswith("vless://uuid-1@cdn.example.com:443?"))
self.assertTrue(build_share_link(listener(tls=tls), "vpn.example.com").startswith("vless://uuid-1@vpn.example.com:443?"))
def test_hysteria2_salamander_password_generated_once(self):
with tempfile.TemporaryDirectory() as tmp:
state = os.path.join(tmp, "inbounds", "hy2-in", "salamander-password")
spec = listener(
type="hysteria2",
users=[{"name": "phone", "password": "pw", "passwordFile": None}],
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None},
hysteria={"salamander": {"enable": True, "password": None, "passwordFile": None}},
salamanderStateFile=state,
)
first = link_params(build_share_link(spec, "vpn.example.com"))["obfs-password"]
self.assertTrue(first)
self.assertEqual(oct(os.stat(state).st_mode & 0o777), "0o600")
# Kept across restarts, so the links users hold stay valid.
self.assertEqual(link_params(build_share_link(spec, "vpn.example.com"))["obfs-password"], first)
self.assertEqual(
render_xray_inbound(spec)["streamSettings"]["finalmask"]["udp"][0]["settings"]["password"], first
)
def test_trojan_round_trip(self):
link = build_share_link(