fix: various fixes

This commit is contained in:
fufsob committed 2026-09-15 17:52:49 +00:00
1 parent 303821f43a
commit 2ce8da3f43
18 files changed
+471 -88

No files matched your search

+46 -4
View File
@@ -22,6 +22,8 @@ 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)
- [serverPassword](#services-proxy-suite-inbounds-listeners-name-serverpassword)
- [serverPasswordFile](#services-proxy-suite-inbounds-listeners-name-serverpasswordfile)
- [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)
@@ -178,7 +180,7 @@ null
<a id="services-proxy-suite-inbounds-listeners-name-jsonfile"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.jsonFile
Runtime path to a raw XRay inbound (no share link); tag is overridden\.
Runtime path to a raw XRay inbound (no share link); tag is overridden and port, if left out, filled in\.
*Type:*
null or string
@@ -198,7 +200,7 @@ null
<a id="services-proxy-suite-inbounds-listeners-name-method"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.method
Shadowsocks cipher\. 2022 ciphers take a base64 key of matching length as password\.
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\.
*Type:*
string
@@ -218,7 +220,7 @@ string
<a id="services-proxy-suite-inbounds-listeners-name-port"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.port
Bound port\.
Bound port\. A raw-JSON listener’s port must match it: the firewall and the port checks go by this one\.
*Type:*
16 bit unsigned integer; between 0 and 65535 (both inclusive)
@@ -377,6 +379,46 @@ list of string
]
```
<a id="services-proxy-suite-inbounds-listeners-name-serverpassword"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.serverPassword
Server key of a multi-user shadowsocks 2022 listener, shared by its users\. Ends up in the Nix store; prefer serverPasswordFile\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"c2VydmVyLWtleS0xNmJ5dGU="
```
<a id="services-proxy-suite-inbounds-listeners-name-serverpasswordfile"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.serverPasswordFile
Runtime path to the server key\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/run/secrets/proxy-inbound-ss-server-key"
```
<a id="services-proxy-suite-inbounds-listeners-name-shareport"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.sharePort
@@ -789,7 +831,7 @@ null
<a id="services-proxy-suite-inbounds-listeners-name-xrayjson"></a>
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.xrayJson
Raw XRay inbound, built into the store; tag is overridden\.
Raw XRay inbound, built into the store; tag is overridden and port, if left out, filled in\.
*Type:*
null or (attribute set)
@@ -76,7 +76,20 @@ in
{
protocol = "freedom";
tag = "direct";
settings = { };
# Checked on the address actually dialed, so a name resolving private is caught too
# (routing's geoip:private sees only literal IPs under AsIs). Explicit either way:
# XRay's own default blocks private for vless/vmess/trojan/shadowsocks only, which
# left socks/http open and ignored blockPrivate = false.
settings.finalRules =
if derived.proxyInboundsCfg.routing.blockPrivate then
[
{
action = "block";
ip = [ "geoip:private" ];
}
]
else
[ { action = "allow"; } ];
}
{
protocol = "blackhole";
+2
View File
@@ -49,6 +49,8 @@ let
users
flow
method
serverPassword
serverPasswordFile
transport
tls
reality
+13 -5
View File
@@ -94,11 +94,13 @@ let
# Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay).
proxyInboundsResolveInSingBox = !pureXrayEnabled && !lib.any (ib: ib.via == "direct") proxyInbounds;
# Even when XRay resolves (a direct listener), it hands sing-box the name, which sing-box
# looks up again: guard there too.
proxyInboundsGuardPrivate =
proxyInboundsEnabled
&& proxyInboundsCfg.routing.blockPrivate
&& proxyInboundsNeedLocalProxy
&& proxyInboundsResolveInSingBox;
&& !pureXrayEnabled;
# Other vias name static outbounds, rendered into the inbound service's own config.
proxyInboundViaTags = lib.unique (
@@ -129,10 +131,13 @@ let
# Loopback listeners are fronted locally; their ports stay closed.
proxyInboundsPublic = builtins.filter (
ib:
!builtins.elem ib.listener.address [
"127.0.0.1"
"::1"
]
!(
lib.hasPrefix "127." ib.listener.address
|| builtins.elem ib.listener.address [
"::1"
"localhost"
]
)
) proxyInbounds;
# h3-only xhttp listeners are UDP-only, leaving the TCP port to a web server.
proxyInboundIsH3Only =
@@ -266,6 +271,9 @@ let
tunAutoRouteTableIndex = 2022;
tunAutoRouteRulePriority = 9000;
# Keeps proxy-suite's own daemons (the inbound XRay, replies to its clients included)
# out of the pure-XRay global TUN.
xrayTunServiceUserRulePriority = 8995;
xrayTunPerAppTproxyRulePriority = 8996;
xrayTunPerAppTunRulePriority = 8997;
+8
View File
@@ -6,6 +6,7 @@
}:
let
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser;
proxyCfg = cfg.proxy;
globalTproxy = proxyCfg.tproxy;
perAppTun = cfg.perAppRouting.tun;
@@ -48,6 +49,9 @@ let
chain prerouting {
type filter hook prerouting priority mangle; policy accept;
ip daddr $RESERVED_IP return
# Connections to this host itself (inbounds, sshd on a public address)
# are served here, not taken by the tproxy socket.
fib daddr type local return
# Packets re-entering via loopback after output marking should not
# be skipped just because the host has an RFC1918 source address.
iifname != "lo" ip saddr $RESERVED_IP return
@@ -60,6 +64,10 @@ let
ip daddr $RESERVED_IP return
${tproxyLocalSubnetLines}
meta mark ${toString globalTproxy.proxyMark} return
# Replies to connections from outside, and proxy-suite's own daemons (the
# inbound XRay dials unmarked, lacking CAP_NET_ADMIN), leave as they are.
ct direction reply return
meta skuid "${serviceUser}" return
${tgWsProxyBypassMarkLine}${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ip protocol tcp meta mark set ${toString globalTproxy.fwmark}
ip protocol udp meta mark set ${toString globalTproxy.fwmark}
}
@@ -158,7 +158,7 @@ let
port = mkOption {
type = types.port;
default = 443;
description = "Bound port.";
description = "Bound port. A raw-JSON listener's port must match it: the firewall and the port checks go by this one.";
};
sharePort = mkOption {
@@ -194,10 +194,13 @@ let
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.";
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";
transport = mkOption {
type = transportType;
default = { };
@@ -219,14 +222,14 @@ let
xrayJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = "Raw XRay inbound, built into the store; tag is overridden.";
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." "/run/secrets/proxy-inbound-vless.json";
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
+53 -28
View File
@@ -14,6 +14,9 @@ let
overrideInbounds = builtins.filter (ib: ib.via != defaultVia) proxyInbounds;
defaultInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via == defaultVia) proxyInbounds);
# A blocked listener stays blocked: neither serverAddress nor the proxy exceptions open it.
exceptionInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via != "block") proxyInbounds);
blockPrivateRule = lib.optional proxyInboundsCfg.routing.blockPrivate {
type = "field";
ruleTag = "inbound-block-private";
@@ -30,20 +33,36 @@ let
addr != null
&& (lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null);
serverAddressRule = lib.optional (proxyInboundsCfg.serverAddress != null) (
{
type = "field";
ruleTag = "inbound-server-address-direct";
outboundTag = "direct";
}
// (
if serverAddressIsIp then
{ ip = [ proxyInboundsCfg.serverAddress ]; }
else
{ domain = [ "full:${proxyInboundsCfg.serverAddress}" ]; }
)
# 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
++ lib.optionals proxyInboundsCfg.subscriptions.enable [
80
443
]
);
serverAddressRule =
lib.optional (proxyInboundsCfg.serverAddress != null && exceptionInboundTags != [ ])
(
{
type = "field";
ruleTag = "inbound-server-address-direct";
inboundTag = exceptionInboundTags;
port = lib.concatMapStringsSep "," toString serverAddressPorts;
outboundTag = "direct";
}
// (
if serverAddressIsIp then
{ ip = [ proxyInboundsCfg.serverAddress ]; }
else
{ domain = [ "full:${proxyInboundsCfg.serverAddress}" ]; }
)
);
blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [
{
type = "field";
@@ -61,23 +80,29 @@ let
inboundProxy = proxyInboundsCfg.routing.proxy;
proxyDomainRule = lib.optional (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ]) {
type = "field";
ruleTag = "inbound-proxy-domain";
domain =
map (domain: "domain:${domain}") inboundProxy.domains
++ map (name: "geosite:${name}") inboundProxy.geosites;
inboundTag = map (ib: ib.tag) proxyInbounds;
outboundTag = "proxy";
};
proxyDomainRule =
lib.optional
(exceptionInboundTags != [ ] && (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ]))
{
type = "field";
ruleTag = "inbound-proxy-domain";
domain =
map (domain: "domain:${domain}") inboundProxy.domains
++ map (name: "geosite:${name}") inboundProxy.geosites;
inboundTag = exceptionInboundTags;
outboundTag = "proxy";
};
proxyIpRule = lib.optional (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ]) {
type = "field";
ruleTag = "inbound-proxy-ip";
ip = inboundProxy.ips ++ map (name: "geoip:${name}") inboundProxy.geoips;
inboundTag = map (ib: ib.tag) proxyInbounds;
outboundTag = "proxy";
};
proxyIpRule =
lib.optional
(exceptionInboundTags != [ ] && (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ]))
{
type = "field";
ruleTag = "inbound-proxy-ip";
ip = inboundProxy.ips ++ map (name: "geoip:${name}") inboundProxy.geoips;
inboundTag = exceptionInboundTags;
outboundTag = "proxy";
};
# Only when the default egress is a proxy, and only for its listeners.
zapretDirectEnabled =
+69 -9
View File
@@ -309,13 +309,22 @@ let
)
"proxy-suite: a proxyInbounds listener port collides with proxy.tproxy.port (${toString globalTproxy.port})"
)
(mkAssertion
(
!proxyInboundsEnabled
|| !lib.any (port: builtins.elem port derived.proxyInboundPorts) (
[ derived.constants.inboundStatsApiPort ]
++ 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)"
)
]
++ lib.concatMap (
ib:
let
l = ib.listener;
prefix = "proxy-suite: inbounds listener '${ib.tag}'";
firstUser = if l.users == [ ] then null else builtins.head l.users;
needsUuid = builtins.elem l.type [
"vless"
"vmess"
@@ -327,6 +336,13 @@ let
"http"
];
tlsTerminated = l.tls.enable || l.type == "trojan";
multiUserShadowsocks = l.type == "shadowsocks" && builtins.length l.users > 1;
eachUser =
condition: fields: message:
mkAssertion (
!condition
|| lib.all (user: builtins.length (builtins.filter (f: user.${f} != null) fields) == 1) l.users
) message;
in
[
(exactlyOneOf proxyInboundsEnabled [
@@ -340,14 +356,58 @@ let
(mkAssertion (
!proxyInboundsEnabled || l.type == null || l.users != [ ]
) "${prefix}: at least one entry in users is required")
(exactlyOneOf (proxyInboundsEnabled && needsUuid && firstUser != null) [
firstUser.uuid
firstUser.uuidFile
] "${prefix}: ${toString l.type} users need exactly one of uuid or uuidFile")
(exactlyOneOf (proxyInboundsEnabled && needsPassword && firstUser != null) [
firstUser.password
firstUser.passwordFile
] "${prefix}: ${toString l.type} users need exactly one of password or passwordFile")
# XRay refuses to start on a repeated email, which is the user's name.
(uniqueValues (proxyInboundsEnabled && l.type != null) (builtins.filter (n: n != "") (
map (user: user.name) l.users
)) "${prefix}: users must each have a distinct name")
(eachUser (proxyInboundsEnabled && needsUuid) [
"uuid"
"uuidFile"
] "${prefix}: ${toString l.type} users each need exactly one of uuid or uuidFile")
(eachUser (proxyInboundsEnabled && needsPassword) [
"password"
"passwordFile"
] "${prefix}: ${toString l.type} users each need exactly one of password or passwordFile")
(mkAssertion (
!proxyInboundsEnabled || !multiUserShadowsocks || lib.hasPrefix "2022-blake3-aes-" l.method
) "${prefix}: shadowsocks with more than one user needs a 2022-blake3-aes-* method")
(exactlyOneOf (proxyInboundsEnabled && multiUserShadowsocks)
[
l.serverPassword
l.serverPasswordFile
]
"${prefix}: shadowsocks with more than one user needs exactly one of serverPassword or serverPasswordFile"
)
(mkAssertion (
!proxyInboundsEnabled
|| !l.reality.enable
|| builtins.elem l.transport.type [
"raw"
"xhttp"
"grpc"
]
) "${prefix}: reality only runs over the raw, xhttp and grpc transports")
(mkAssertion (
!proxyInboundsEnabled || l.xrayJson == null || (l.xrayJson.port or l.port) == l.port
) "${prefix}: xrayJson.port and port differ; the firewall and the port checks go by port")
(mkAssertion (
!proxyInboundsEnabled
|| !proxyInboundsCfg.shareLinks
|| !l.reality.enable
|| builtins.elem l.type [
"vless"
"trojan"
]
) "${prefix}: share links carry reality only for vless and trojan; set inbounds.shareLinks = false to serve it anyway")
(mkAssertion (
!proxyInboundsEnabled
|| !proxyInboundsCfg.shareLinks
|| !l.tls.enable
|| !builtins.elem l.type [
"shadowsocks"
"socks"
]
) "${prefix}: share links cannot carry tls for ${toString l.type}; set inbounds.shareLinks = false to serve it anyway")
(exactlyOneOf (proxyInboundsEnabled && l.reality.enable) [
l.reality.privateKey
l.reality.privateKeyFile
@@ -16,6 +16,7 @@ let
inherit (constants)
tunAutoRouteTableIndex
tunAutoRouteRulePriority
xrayTunServiceUserRulePriority
xrayTunPerAppTproxyRulePriority
xrayTunPerAppTunRulePriority
xrayGlobalTunIPv6Address
@@ -57,6 +58,8 @@ in
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunServiceUserRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString xrayTunServiceUserRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
@@ -77,6 +80,9 @@ in
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
''}
service_uid=$(${pkgs.coreutils}/bin/id -u ${constants.serviceUser})
${ip} -4 rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main
${ip} -6 rule add pref ${toString xrayTunServiceUserRulePriority} uidrange "$service_uid-$service_uid" lookup main
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
'';
@@ -136,6 +142,16 @@ in
family = "-6";
priority = xrayTunPerAppTunRulePriority;
}}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-4";
priority = xrayTunServiceUserRulePriority;
}}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-6";
priority = xrayTunServiceUserRulePriority;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }}
@@ -121,12 +121,15 @@ else
''
+ lib.optionalString proxyInboundsGuardPrivate ''
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
# Last, so only traffic falling through to a direct final is resolved. Local mixed-
# in clients lose names that resolve private.
| if (.route.final // "direct") == "direct" then
.route.rules += [
{inbound: ["mixed-in"], action: "resolve"},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}
]
# Just before the first direct rule (or last, for a direct final), so names that the
# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local
# mixed-in clients lose names that resolve private.
| [{inbound: ["mixed-in"], action: "resolve"},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard
| (.route.rules | map((.outbound? // "") == "direct") | index(true)) as $first_direct
| if $first_direct != null then
.route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:]
elif (.route.final // "direct") == "direct" then
.route.rules += $guard
else . end
''
@@ -147,6 +147,7 @@ let
enableAutoProxy ? false,
enableOutboundTest ? false,
enableZapretCutoff ? false,
excludeServiceUserFromTun ? false,
}:
pkgs.writeShellScript "proxy-suite-core" ''
set -euo pipefail
@@ -344,6 +345,14 @@ let
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
-f "$BACKEND_JQ_FILTER" \
"${configFile}" > "$RUNTIME_DIR/config.json"
${lib.optionalString excludeServiceUserFromTun ''
# proxy-suite's own daemons (the inbound XRay, replies to its clients included)
# stay out of the TUN; the uid is only known on this host.
SERVICE_UID=$(${pkgs.coreutils}/bin/id -u ${constants.serviceUser})
${jq} --argjson uid "$SERVICE_UID" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = [$uid]' \
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next"
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
''}
# The backend runs as ${constants.serviceUser}: its configs are group-readable.
for backend_config in "$RUNTIME_DIR/config.json" "$RUNTIME_DIR/xray-sidecar.json"; do
[ -e "$backend_config" ] || continue
@@ -416,6 +425,8 @@ let
xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = xraySidecarBasePorts.tun;
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
# Pure XRay's TUN routes by ip rules instead: see xrayTunUpScript.
excludeServiceUserFromTun = !pureXrayEnabled;
};
startPerAppTun = mkStartScript {
+11 -1
View File
@@ -8,7 +8,17 @@
}:
let
pkgs = import nixpkgs { inherit system; };
nixpkgsPkgs = import nixpkgs { inherit system; };
# lib.hasInfix matches ".*infix.*", which std::regex backtracks through recursively: on
# the ~100 KB proxy-ctl script that overflows the evaluator's stack. Splitting on the
# bare infix walks the text flat. Only the checks' own pkgs; the modules keep lib as is.
pkgs = nixpkgsPkgs // {
lib = nixpkgsPkgs.lib.extend (
_: super: {
hasInfix = infix: content: builtins.length (builtins.split (super.escapeRegex infix) content) > 1;
}
);
};
parserChecks = import ./checks/parsers.nix { inherit pkgs; };
checkLib = import ./checks/lib.nix {
inherit
+4 -3
View File
@@ -8,7 +8,8 @@ let
# deployments keep these in a secret manager.
uuid = "b831381d-6324-4d53-ad4f-8cda48b30811";
ssPassword = "dGhpcy1pcy1hLTE2Ynl0ZS1rZXk=";
serverAddress = "192.168.0.1";
# Public addresses: blockPrivate would refuse the origin on a private one.
serverAddress = "11.0.0.1";
network = address: {
networking.useDHCP = false;
@@ -72,7 +73,7 @@ pkgs.testers.runNixOSTest {
{
imports = [
proxySuiteModule
(network "192.168.0.2")
(network "11.0.0.2")
];
services.proxy-suite = {
@@ -105,7 +106,7 @@ pkgs.testers.runNixOSTest {
server.succeed(f"jq -e '.inbounds[] | select(.tag == \"vless-in\" and .port == 8443)' {cfg}")
server.succeed(f"jq -e '.inbounds[] | select(.tag == \"ss-in\" and .port == 8388)' {cfg}")
# Credentials live only in the runtime config, never in the store.
server.succeed(f"test $(stat -c %a {cfg}) = 600")
server.succeed(f"test $(stat -c %a {cfg}) = 640")
server.fail("grep -r '${uuid}' /nix/store/*-proxy-suite-inbounds")
with subtest("safety rules are present and ordered first"):
+100 -1
View File
@@ -49,6 +49,18 @@ let
};
mixedConfig = mkInboundsConfig mixedFixture;
# A blocked listener gets neither the proxy exceptions nor serverAddress.
blockedFixture = mkInbounds {
serverAddress = "vpn.example.com";
routing.proxy.domains = [ "telegram.org" ];
listeners.open = realityListener;
listeners.shut = realityListener // {
port = 8443;
via = "block";
};
};
blockedConfig = mkInboundsConfig blockedFixture;
# Two listeners, two different servers.
pinnedFixture = evalProxySuite [
{
@@ -124,7 +136,7 @@ let
type = "vless";
port = 10002;
sharePort = 443;
address = "127.0.0.1";
address = "127.0.0.53";
users = [ { uuidFile = "/run/secrets/ws"; } ];
transport = {
type = "ws";
@@ -215,7 +227,76 @@ let
else
throw "proxy-inbounds check: expected an assertion matching '${fragment}', got: ${builtins.toJSON (map (a: a.message) failed)}";
mkRejectsListener =
listener:
mkRejects (
baseProxy
// {
inbounds = {
enable = true;
listeners.bad = listener;
};
}
);
ssUsers = [
{
name = "a";
passwordFile = "/run/secrets/a";
}
{
name = "b";
passwordFile = "/run/secrets/b";
}
];
failing = [
(mkRejectsListener (
realityListener // { port = 18536; }
) "collides with a port proxy-suite uses internally")
# Every user is checked, not only the first.
(mkRejectsListener (
realityListener // { users = realityListener.users ++ [ { name = "second"; } ]; }
) "users each need exactly one of uuid or uuidFile")
(mkRejectsListener {
type = "shadowsocks";
users = ssUsers;
} "needs exactly one of serverPassword or serverPasswordFile")
(mkRejectsListener {
type = "trojan";
users = map (u: u // { name = "same"; }) ssUsers;
tls = {
certificateFile = "/c";
keyFile = "/k";
};
} "users must each have a distinct name")
(mkRejectsListener {
type = "shadowsocks";
method = "2022-blake3-chacha20-poly1305";
serverPasswordFile = "/run/secrets/server";
users = ssUsers;
} "needs a 2022-blake3-aes-* method")
(mkRejectsListener (
realityListener
// {
flow = null;
transport.type = "ws";
}
) "reality only runs over the raw, xhttp and grpc transports")
(mkRejectsListener {
xrayJson = {
protocol = "dokodemo-door";
port = 8080;
};
} "xrayJson.port and port differ")
(mkRejectsListener (
realityListener
// {
type = "vmess";
flow = null;
}
) "share links carry reality only for vless and trojan")
(mkRejects (
baseProxy
// {
@@ -392,6 +473,24 @@ let
(ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ];
true
)
# Names that resolve private are refused where XRay dials them itself.
(
assert
(lib.findFirst (ob: ob.tag == "direct") null relayConfig.outbounds).settings.finalRules == [
{
action = "block";
ip = [ "geoip:private" ];
}
];
true
)
# Only the listener ports, not every service on this host.
(
assert (ruleByTag namedConfig "inbound-server-address-direct").port == "443";
true
)
(assert (ruleByTag blockedConfig "inbound-proxy-domain").inboundTag == [ "open" ]; true)
(assert (ruleByTag blockedConfig "inbound-server-address-direct").inboundTag == [ "open" ]; true)
# No address to exempt when it is detected at runtime instead.
(assert !builtins.elem "inbound-server-address-direct" (ruleTags relayConfig); true)
(
+6 -1
View File
@@ -2144,7 +2144,12 @@ def _where_inbounds(config, domain, geosite_dir):
and _where_rule_set_match({"path": os.path.join(geosite_dir, f"geosite-{value}.srs"), "format": "binary"}, domain))
)
if matched:
return _s(rule.get("outboundTag")), f"{_s(rule.get('ruleTag'))} ({entry})"
# A rule held to some listeners or ports says so: the rest go on down the list.
scope = "".join(
[f", listeners {','.join(map(_s, rule['inboundTag']))}" if rule.get("inboundTag") else ""]
+ [f", ports {_s(rule['port'])}" if rule.get("port") else ""]
)
return _s(rule.get("outboundTag")), f"{_s(rule.get('ruleTag'))} ({entry}{scope})"
return "", ""
+5
View File
@@ -690,6 +690,11 @@ class WhereTest(EnvTest):
self.assertEqual(ctl._where_inbounds(config, "rr1.googlevideo.com", "")[0], "proxy")
self.assertEqual(ctl._where_inbounds(config, "youtube.com", ""), ("direct", "inbound-zapret-direct-domain (full:youtube.com)"))
self.assertEqual(ctl._where_inbounds(config, "example.org", "")[0], "proxy")
config["routing"]["rules"][2] |= {"inboundTag": ["relay"], "port": "443"}
self.assertEqual(
ctl._where_inbounds(config, "youtube.com", "")[1],
"inbound-zapret-direct-domain (full:youtube.com, listeners relay, ports 443)",
)
class StatusSnapshotTest(EnvTest):
+32 -10
View File
@@ -50,6 +50,13 @@ def _user_secret(user: dict, listener_type: str, tag: str) -> str:
return _resolve(user.get("password"), user.get("passwordFile"), "password", tag)
def _server_secret(listener: dict, tag: str) -> str:
"""Server key of a multi-user shadowsocks 2022 listener."""
return _resolve(
listener.get("serverPassword"), listener.get("serverPasswordFile"), "server password", tag
)
def _b64(value: str) -> str:
"""base64 without padding, as share links carry it."""
return base64.urlsafe_b64encode(value.encode("utf-8")).decode("ascii").rstrip("=")
@@ -150,8 +157,10 @@ def render_xray_inbound(listener: dict) -> dict:
users = listener["users"]
if len(users) == 1:
settings["password"] = _user_secret(users[0], listener_type, tag)
settings["email"] = users[0].get("name") or f"{tag}-0"
else:
# Multi-user shadowsocks needs the 2022 ciphers.
# Multi-user is 2022-blake3-aes only: the server key, then one key per user.
settings["password"] = _server_secret(listener, tag)
settings["clients"] = _clients(listener, tag)
elif listener_type in ("socks", "http"):
settings = {"auth": "password", "accounts": _accounts(listener, tag)}
@@ -240,10 +249,11 @@ def _vmess_link(listener: dict, secret: str, server_address: str, label: str) ->
"id": secret,
"aid": "0",
"scy": "auto",
"net": transport["type"],
# Clients know plain TCP as "tcp", and take gRPC's service name from path.
"net": "tcp" if transport["type"] == "raw" else transport["type"],
"type": "none",
"host": transport.get("host") or "",
"path": transport["path"],
"path": transport["serviceName"] if transport["type"] == "grpc" else transport["path"],
"tls": "tls" if (tls["enable"] or reality["enable"]) else "",
"sni": tls.get("serverName") or server_address,
}
@@ -272,7 +282,15 @@ def build_share_link(listener: dict, server_address: str, user_index: int = 0) -
return _vmess_link(listener, secret, server_address, label)
if listener_type == "shadowsocks":
userinfo = _b64(f"{listener['method']}:{secret}")
if len(users) > 1:
# SIP022 multi-user: the client presents the server key and its own.
secret = f"{_server_secret(listener, tag)}:{secret}"
method = listener["method"]
# SIP002: 2022 ciphers take the userinfo percent-encoded, the older ones base64.
if method.startswith("2022-"):
userinfo = f"{method}:{urllib.parse.quote(secret, safe='')}"
else:
userinfo = _b64(f"{method}:{secret}")
return f"ss://{userinfo}@{endpoint}#{fragment}"
if listener_type in ("socks", "http"):
@@ -280,7 +298,8 @@ def build_share_link(listener: dict, server_address: str, user_index: int = 0) -
userinfo = _b64(f"{user_name}:{secret}")
return f"socks://{userinfo}@{endpoint}#{fragment}"
credentials = urllib.parse.quote(user_name, safe="") + ":" + urllib.parse.quote(secret, safe="")
return f"http://{credentials}@{endpoint}#{fragment}"
scheme = "https" if listener["tls"]["enable"] else "http"
return f"{scheme}://{credentials}@{endpoint}#{fragment}"
params = _link_transport_params(listener)
params.update(_link_security_params(listener, server_address))
@@ -298,13 +317,16 @@ def build_listener(listener: dict, server_address: str, share_links: bool) -> di
"""
tag = listener["tag"]
raw = listener.get("xrayJson")
if listener.get("jsonFile") is not None:
with open(listener["jsonFile"], encoding="utf-8") as handle:
inbound = json.load(handle)
return {"tag": tag, "inbound": {**inbound, "tag": tag}, "links": []}
if listener.get("xrayJson") is not None:
return {"tag": tag, "inbound": {**listener["xrayJson"], "tag": tag}, "links": []}
raw = json.load(handle)
if raw is not None:
# The firewall and the port checks go by the listener's port, so the JSON must agree.
port = raw.get("port", listener["port"])
if port != listener["port"]:
raise ValueError(f"listener '{tag}': its JSON listens on port {port}, but port is {listener['port']}")
return {"tag": tag, "inbound": {**raw, "tag": tag, "port": port}, "links": []}
inbound = render_xray_inbound(listener)
links = (
+64 -14
View File
@@ -55,6 +55,20 @@ def reality(**overrides):
return settings
def multi_user_shadowsocks(**overrides):
spec = {
"type": "shadowsocks",
"serverPassword": "server-psk",
"serverPasswordFile": None,
"users": [
{"name": "a", "password": "psk-a", "passwordFile": None},
{"name": "b", "password": "psk-b", "passwordFile": None},
],
}
spec.update(overrides)
return listener(**spec)
def link_params(link: str) -> dict:
query = urllib.parse.urlsplit(link).query
return dict(urllib.parse.parse_qsl(query))
@@ -162,18 +176,17 @@ class RenderInboundTests(unittest.TestCase):
self.assertEqual(ib["settings"]["method"], "2022-blake3-aes-128-gcm")
self.assertEqual(ib["settings"]["network"], "tcp,udp")
def test_shadowsocks_multi_user_uses_clients(self):
ib = render_xray_inbound(
listener(
type="shadowsocks",
users=[
{"name": "a", "password": "psk-a", "passwordFile": None},
{"name": "b", "password": "psk-b", "passwordFile": None},
],
)
def test_shadowsocks_multi_user_has_server_key_and_clients(self):
ib = render_xray_inbound(multi_user_shadowsocks())
self.assertEqual(ib["settings"]["password"], "server-psk")
self.assertEqual(
ib["settings"]["clients"],
[{"password": "psk-a", "email": "a"}, {"password": "psk-b", "email": "b"}],
)
self.assertNotIn("password", ib["settings"])
self.assertEqual(len(ib["settings"]["clients"]), 2)
def test_shadowsocks_multi_user_needs_server_key(self):
with self.assertRaisesRegex(ValueError, "no server password"):
render_xray_inbound(multi_user_shadowsocks(serverPassword=None))
def test_socks_accounts_and_udp(self):
ib = render_xray_inbound(
@@ -262,13 +275,44 @@ class ShareLinkTests(unittest.TestCase):
self.assertEqual(blob["net"], "ws")
self.assertEqual(blob["tls"], "tls")
def test_vmess_link_names_raw_tcp_and_grpc_service(self):
def blob(transport):
payload = build_share_link(listener(type="vmess", transport=transport), "vpn.example.com")[len("vmess://") :]
return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
self.assertEqual(blob({"type": "raw", "path": "/", "host": None, "serviceName": ""})["net"], "tcp")
self.assertEqual(blob({"type": "grpc", "path": "/", "host": None, "serviceName": "Gun"})["path"], "Gun")
def test_shadowsocks_link_is_sip002(self):
spec = listener(type="shadowsocks", users=[{"name": "", "password": "psk", "passwordFile": None}])
spec = listener(
type="shadowsocks", method="aes-128-gcm", users=[{"name": "", "password": "psk", "passwordFile": None}]
)
link = build_share_link(spec, "vpn.example.com")
userinfo = link[len("ss://") :].split("@", 1)[0]
userinfo += "=" * (-len(userinfo) % 4)
decoded = base64.urlsafe_b64decode(userinfo).decode()
self.assertEqual(decoded, "2022-blake3-aes-128-gcm:psk")
self.assertEqual(decoded, "aes-128-gcm:psk")
def test_shadowsocks_2022_link_is_percent_encoded(self):
link = build_share_link(multi_user_shadowsocks(serverPassword="a+b/c="), "vpn.example.com")
self.assertTrue(link.startswith("ss://2022-blake3-aes-128-gcm:a%2Bb%2Fc%3D%3Apsk-a@"), link)
def test_http_link_over_tls_is_https(self):
spec = listener(
type="http",
users=[{"name": "me", "password": "pw", "passwordFile": None}],
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None},
)
self.assertTrue(build_share_link(spec, "vpn.example.com").startswith("https://me:pw@"))
def test_raw_json_port_must_match_the_listener(self):
from proxy_inbound import build_listener
raw = listener(type=None, xrayJson={"protocol": "dokodemo-door"})
self.assertEqual(build_listener(raw, "", False)["inbound"]["port"], 443)
with self.assertRaisesRegex(ValueError, "port 8080, but port is 443"):
build_listener(listener(type=None, xrayJson={"protocol": "dokodemo-door", "port": 8080}), "", False)
class RoundTripTests(unittest.TestCase):
@@ -336,6 +380,11 @@ class RoundTripTests(unittest.TestCase):
self.assertEqual(ob["method"], "2022-blake3-aes-128-gcm")
self.assertEqual(ob["password"], "psk")
def test_shadowsocks_multi_user_round_trip(self):
link = build_share_link(multi_user_shadowsocks(), "vpn.example.com", 1)
ob = build_outbound(link, "round-trip", backend="sing-box")
self.assertEqual(ob["password"], "server-psk:psk-b")
def test_vmess_round_trip(self):
link = build_share_link(listener(type="vmess"), "vpn.example.com")
ob = build_outbound(link, "round-trip", backend="sing-box")
@@ -485,6 +534,7 @@ class BuildInboundsTests(unittest.TestCase):
listener(
tag="raw",
type=None,
port=8080,
xrayJson={"protocol": "dokodemo-door", "tag": "ignored", "port": 8080},
)
],
@@ -502,7 +552,7 @@ class BuildInboundsTests(unittest.TestCase):
spec = {
"serverAddress": "vpn.example.com",
"shareLinks": True,
"listeners": [listener(tag="secret-in", type=None, jsonFile=path)],
"listeners": [listener(tag="secret-in", type=None, port=2053, jsonFile=path)],
}
result = build_inbounds(spec, "vpn.example.com")
self.assertEqual(result["inbounds"][0]["tag"], "secret-in")