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

+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" ''