fix: various fixes
This commit is contained in:
18 files changed
+446
-63
No files matched your search
@@ -22,6 +22,8 @@ Part of the [proxy-suite options reference](./index.md).
|
|||||||
- [publicKey](#services-proxy-suite-inbounds-listeners-name-reality-publickey)
|
- [publicKey](#services-proxy-suite-inbounds-listeners-name-reality-publickey)
|
||||||
- [serverNames](#services-proxy-suite-inbounds-listeners-name-reality-servernames)
|
- [serverNames](#services-proxy-suite-inbounds-listeners-name-reality-servernames)
|
||||||
- [shortIds](#services-proxy-suite-inbounds-listeners-name-reality-shortids)
|
- [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)
|
- [sharePort](#services-proxy-suite-inbounds-listeners-name-shareport)
|
||||||
- [tls](#services-proxy-suite-inbounds-listeners-name-tls)
|
- [tls](#services-proxy-suite-inbounds-listeners-name-tls)
|
||||||
- [enable](#services-proxy-suite-inbounds-listeners-name-tls-enable)
|
- [enable](#services-proxy-suite-inbounds-listeners-name-tls-enable)
|
||||||
@@ -178,7 +180,7 @@ null
|
|||||||
<a id="services-proxy-suite-inbounds-listeners-name-jsonfile"></a>
|
<a id="services-proxy-suite-inbounds-listeners-name-jsonfile"></a>
|
||||||
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.jsonFile
|
## 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:*
|
*Type:*
|
||||||
null or string
|
null or string
|
||||||
@@ -198,7 +200,7 @@ null
|
|||||||
<a id="services-proxy-suite-inbounds-listeners-name-method"></a>
|
<a id="services-proxy-suite-inbounds-listeners-name-method"></a>
|
||||||
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.method
|
## 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:*
|
*Type:*
|
||||||
string
|
string
|
||||||
@@ -218,7 +220,7 @@ string
|
|||||||
<a id="services-proxy-suite-inbounds-listeners-name-port"></a>
|
<a id="services-proxy-suite-inbounds-listeners-name-port"></a>
|
||||||
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.port
|
## 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:*
|
*Type:*
|
||||||
16 bit unsigned integer; between 0 and 65535 (both inclusive)
|
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>
|
<a id="services-proxy-suite-inbounds-listeners-name-shareport"></a>
|
||||||
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.sharePort
|
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.sharePort
|
||||||
|
|
||||||
@@ -789,7 +831,7 @@ null
|
|||||||
<a id="services-proxy-suite-inbounds-listeners-name-xrayjson"></a>
|
<a id="services-proxy-suite-inbounds-listeners-name-xrayjson"></a>
|
||||||
## services\.proxy-suite\.inbounds\.listeners\.\<name>\.xrayJson
|
## 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:*
|
*Type:*
|
||||||
null or (attribute set)
|
null or (attribute set)
|
||||||
|
|||||||
@@ -76,7 +76,20 @@ in
|
|||||||
{
|
{
|
||||||
protocol = "freedom";
|
protocol = "freedom";
|
||||||
tag = "direct";
|
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";
|
protocol = "blackhole";
|
||||||
|
|||||||
@@ -49,6 +49,8 @@ let
|
|||||||
users
|
users
|
||||||
flow
|
flow
|
||||||
method
|
method
|
||||||
|
serverPassword
|
||||||
|
serverPasswordFile
|
||||||
transport
|
transport
|
||||||
tls
|
tls
|
||||||
reality
|
reality
|
||||||
|
|||||||
@@ -94,11 +94,13 @@ let
|
|||||||
# Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay).
|
# Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay).
|
||||||
proxyInboundsResolveInSingBox = !pureXrayEnabled && !lib.any (ib: ib.via == "direct") proxyInbounds;
|
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 =
|
proxyInboundsGuardPrivate =
|
||||||
proxyInboundsEnabled
|
proxyInboundsEnabled
|
||||||
&& proxyInboundsCfg.routing.blockPrivate
|
&& proxyInboundsCfg.routing.blockPrivate
|
||||||
&& proxyInboundsNeedLocalProxy
|
&& proxyInboundsNeedLocalProxy
|
||||||
&& proxyInboundsResolveInSingBox;
|
&& !pureXrayEnabled;
|
||||||
|
|
||||||
# Other vias name static outbounds, rendered into the inbound service's own config.
|
# Other vias name static outbounds, rendered into the inbound service's own config.
|
||||||
proxyInboundViaTags = lib.unique (
|
proxyInboundViaTags = lib.unique (
|
||||||
@@ -129,10 +131,13 @@ let
|
|||||||
# Loopback listeners are fronted locally; their ports stay closed.
|
# Loopback listeners are fronted locally; their ports stay closed.
|
||||||
proxyInboundsPublic = builtins.filter (
|
proxyInboundsPublic = builtins.filter (
|
||||||
ib:
|
ib:
|
||||||
!builtins.elem ib.listener.address [
|
!(
|
||||||
"127.0.0.1"
|
lib.hasPrefix "127." ib.listener.address
|
||||||
|
|| builtins.elem ib.listener.address [
|
||||||
"::1"
|
"::1"
|
||||||
|
"localhost"
|
||||||
]
|
]
|
||||||
|
)
|
||||||
) proxyInbounds;
|
) proxyInbounds;
|
||||||
# h3-only xhttp listeners are UDP-only, leaving the TCP port to a web server.
|
# h3-only xhttp listeners are UDP-only, leaving the TCP port to a web server.
|
||||||
proxyInboundIsH3Only =
|
proxyInboundIsH3Only =
|
||||||
@@ -266,6 +271,9 @@ let
|
|||||||
|
|
||||||
tunAutoRouteTableIndex = 2022;
|
tunAutoRouteTableIndex = 2022;
|
||||||
tunAutoRouteRulePriority = 9000;
|
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;
|
xrayTunPerAppTproxyRulePriority = 8996;
|
||||||
xrayTunPerAppTunRulePriority = 8997;
|
xrayTunPerAppTunRulePriority = 8997;
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
|
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser;
|
||||||
proxyCfg = cfg.proxy;
|
proxyCfg = cfg.proxy;
|
||||||
globalTproxy = proxyCfg.tproxy;
|
globalTproxy = proxyCfg.tproxy;
|
||||||
perAppTun = cfg.perAppRouting.tun;
|
perAppTun = cfg.perAppRouting.tun;
|
||||||
@@ -48,6 +49,9 @@ let
|
|||||||
chain prerouting {
|
chain prerouting {
|
||||||
type filter hook prerouting priority mangle; policy accept;
|
type filter hook prerouting priority mangle; policy accept;
|
||||||
ip daddr $RESERVED_IP return
|
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
|
# Packets re-entering via loopback after output marking should not
|
||||||
# be skipped just because the host has an RFC1918 source address.
|
# be skipped just because the host has an RFC1918 source address.
|
||||||
iifname != "lo" ip saddr $RESERVED_IP return
|
iifname != "lo" ip saddr $RESERVED_IP return
|
||||||
@@ -60,6 +64,10 @@ let
|
|||||||
ip daddr $RESERVED_IP return
|
ip daddr $RESERVED_IP return
|
||||||
${tproxyLocalSubnetLines}
|
${tproxyLocalSubnetLines}
|
||||||
meta mark ${toString globalTproxy.proxyMark} return
|
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}
|
${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}
|
ip protocol udp meta mark set ${toString globalTproxy.fwmark}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ let
|
|||||||
port = mkOption {
|
port = mkOption {
|
||||||
type = types.port;
|
type = types.port;
|
||||||
default = 443;
|
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 {
|
sharePort = mkOption {
|
||||||
@@ -194,10 +194,13 @@ let
|
|||||||
method = mkOption {
|
method = mkOption {
|
||||||
type = types.str;
|
type = types.str;
|
||||||
default = "2022-blake3-aes-128-gcm";
|
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";
|
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 {
|
transport = mkOption {
|
||||||
type = transportType;
|
type = transportType;
|
||||||
default = { };
|
default = { };
|
||||||
@@ -219,14 +222,14 @@ let
|
|||||||
xrayJson = mkOption {
|
xrayJson = mkOption {
|
||||||
type = types.nullOr types.attrs;
|
type = types.nullOr types.attrs;
|
||||||
default = null;
|
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 = {
|
example = {
|
||||||
protocol = "dokodemo-door";
|
protocol = "dokodemo-door";
|
||||||
settings.port = 8080;
|
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
|
in
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ let
|
|||||||
overrideInbounds = builtins.filter (ib: ib.via != defaultVia) proxyInbounds;
|
overrideInbounds = builtins.filter (ib: ib.via != defaultVia) proxyInbounds;
|
||||||
defaultInboundTags = map (ib: ib.tag) (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 {
|
blockPrivateRule = lib.optional proxyInboundsCfg.routing.blockPrivate {
|
||||||
type = "field";
|
type = "field";
|
||||||
ruleTag = "inbound-block-private";
|
ruleTag = "inbound-block-private";
|
||||||
@@ -30,10 +33,26 @@ let
|
|||||||
addr != null
|
addr != null
|
||||||
&& (lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null);
|
&& (lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null);
|
||||||
|
|
||||||
serverAddressRule = lib.optional (proxyInboundsCfg.serverAddress != null) (
|
# 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";
|
type = "field";
|
||||||
ruleTag = "inbound-server-address-direct";
|
ruleTag = "inbound-server-address-direct";
|
||||||
|
inboundTag = exceptionInboundTags;
|
||||||
|
port = lib.concatMapStringsSep "," toString serverAddressPorts;
|
||||||
outboundTag = "direct";
|
outboundTag = "direct";
|
||||||
}
|
}
|
||||||
// (
|
// (
|
||||||
@@ -61,21 +80,27 @@ let
|
|||||||
|
|
||||||
inboundProxy = proxyInboundsCfg.routing.proxy;
|
inboundProxy = proxyInboundsCfg.routing.proxy;
|
||||||
|
|
||||||
proxyDomainRule = lib.optional (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ]) {
|
proxyDomainRule =
|
||||||
|
lib.optional
|
||||||
|
(exceptionInboundTags != [ ] && (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ]))
|
||||||
|
{
|
||||||
type = "field";
|
type = "field";
|
||||||
ruleTag = "inbound-proxy-domain";
|
ruleTag = "inbound-proxy-domain";
|
||||||
domain =
|
domain =
|
||||||
map (domain: "domain:${domain}") inboundProxy.domains
|
map (domain: "domain:${domain}") inboundProxy.domains
|
||||||
++ map (name: "geosite:${name}") inboundProxy.geosites;
|
++ map (name: "geosite:${name}") inboundProxy.geosites;
|
||||||
inboundTag = map (ib: ib.tag) proxyInbounds;
|
inboundTag = exceptionInboundTags;
|
||||||
outboundTag = "proxy";
|
outboundTag = "proxy";
|
||||||
};
|
};
|
||||||
|
|
||||||
proxyIpRule = lib.optional (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ]) {
|
proxyIpRule =
|
||||||
|
lib.optional
|
||||||
|
(exceptionInboundTags != [ ] && (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ]))
|
||||||
|
{
|
||||||
type = "field";
|
type = "field";
|
||||||
ruleTag = "inbound-proxy-ip";
|
ruleTag = "inbound-proxy-ip";
|
||||||
ip = inboundProxy.ips ++ map (name: "geoip:${name}") inboundProxy.geoips;
|
ip = inboundProxy.ips ++ map (name: "geoip:${name}") inboundProxy.geoips;
|
||||||
inboundTag = map (ib: ib.tag) proxyInbounds;
|
inboundTag = exceptionInboundTags;
|
||||||
outboundTag = "proxy";
|
outboundTag = "proxy";
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -309,13 +309,22 @@ let
|
|||||||
)
|
)
|
||||||
"proxy-suite: a proxyInbounds listener port collides with proxy.tproxy.port (${toString globalTproxy.port})"
|
"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 (
|
++ lib.concatMap (
|
||||||
ib:
|
ib:
|
||||||
let
|
let
|
||||||
l = ib.listener;
|
l = ib.listener;
|
||||||
prefix = "proxy-suite: inbounds listener '${ib.tag}'";
|
prefix = "proxy-suite: inbounds listener '${ib.tag}'";
|
||||||
firstUser = if l.users == [ ] then null else builtins.head l.users;
|
|
||||||
needsUuid = builtins.elem l.type [
|
needsUuid = builtins.elem l.type [
|
||||||
"vless"
|
"vless"
|
||||||
"vmess"
|
"vmess"
|
||||||
@@ -327,6 +336,13 @@ let
|
|||||||
"http"
|
"http"
|
||||||
];
|
];
|
||||||
tlsTerminated = l.tls.enable || l.type == "trojan";
|
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
|
in
|
||||||
[
|
[
|
||||||
(exactlyOneOf proxyInboundsEnabled [
|
(exactlyOneOf proxyInboundsEnabled [
|
||||||
@@ -340,14 +356,58 @@ let
|
|||||||
(mkAssertion (
|
(mkAssertion (
|
||||||
!proxyInboundsEnabled || l.type == null || l.users != [ ]
|
!proxyInboundsEnabled || l.type == null || l.users != [ ]
|
||||||
) "${prefix}: at least one entry in users is required")
|
) "${prefix}: at least one entry in users is required")
|
||||||
(exactlyOneOf (proxyInboundsEnabled && needsUuid && firstUser != null) [
|
# XRay refuses to start on a repeated email, which is the user's name.
|
||||||
firstUser.uuid
|
(uniqueValues (proxyInboundsEnabled && l.type != null) (builtins.filter (n: n != "") (
|
||||||
firstUser.uuidFile
|
map (user: user.name) l.users
|
||||||
] "${prefix}: ${toString l.type} users need exactly one of uuid or uuidFile")
|
)) "${prefix}: users must each have a distinct name")
|
||||||
(exactlyOneOf (proxyInboundsEnabled && needsPassword && firstUser != null) [
|
(eachUser (proxyInboundsEnabled && needsUuid) [
|
||||||
firstUser.password
|
"uuid"
|
||||||
firstUser.passwordFile
|
"uuidFile"
|
||||||
] "${prefix}: ${toString l.type} users need exactly one of password or passwordFile")
|
] "${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) [
|
(exactlyOneOf (proxyInboundsEnabled && l.reality.enable) [
|
||||||
l.reality.privateKey
|
l.reality.privateKey
|
||||||
l.reality.privateKeyFile
|
l.reality.privateKeyFile
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ let
|
|||||||
inherit (constants)
|
inherit (constants)
|
||||||
tunAutoRouteTableIndex
|
tunAutoRouteTableIndex
|
||||||
tunAutoRouteRulePriority
|
tunAutoRouteRulePriority
|
||||||
|
xrayTunServiceUserRulePriority
|
||||||
xrayTunPerAppTproxyRulePriority
|
xrayTunPerAppTproxyRulePriority
|
||||||
xrayTunPerAppTunRulePriority
|
xrayTunPerAppTunRulePriority
|
||||||
xrayGlobalTunIPv6Address
|
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 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 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} -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 xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
|
||||||
while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 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} -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}
|
${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} -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}
|
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
|
||||||
'';
|
'';
|
||||||
@@ -136,6 +142,16 @@ in
|
|||||||
family = "-6";
|
family = "-6";
|
||||||
priority = xrayTunPerAppTunRulePriority;
|
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 = "-4"; table = tunAutoRouteTableIndex; }}
|
||||||
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
|
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
|
||||||
${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }}
|
${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }}
|
||||||
|
|||||||
@@ -121,12 +121,15 @@ else
|
|||||||
''
|
''
|
||||||
+ lib.optionalString proxyInboundsGuardPrivate ''
|
+ lib.optionalString proxyInboundsGuardPrivate ''
|
||||||
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
|
# 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-
|
# Just before the first direct rule (or last, for a direct final), so names that the
|
||||||
# in clients lose names that resolve private.
|
# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local
|
||||||
| if (.route.final // "direct") == "direct" then
|
# mixed-in clients lose names that resolve private.
|
||||||
.route.rules += [
|
| [{inbound: ["mixed-in"], action: "resolve"},
|
||||||
{inbound: ["mixed-in"], action: "resolve"},
|
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard
|
||||||
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}
|
| (.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
|
else . end
|
||||||
''
|
''
|
||||||
@@ -147,6 +147,7 @@ let
|
|||||||
enableAutoProxy ? false,
|
enableAutoProxy ? false,
|
||||||
enableOutboundTest ? false,
|
enableOutboundTest ? false,
|
||||||
enableZapretCutoff ? false,
|
enableZapretCutoff ? false,
|
||||||
|
excludeServiceUserFromTun ? false,
|
||||||
}:
|
}:
|
||||||
pkgs.writeShellScript "proxy-suite-core" ''
|
pkgs.writeShellScript "proxy-suite-core" ''
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -344,6 +345,14 @@ let
|
|||||||
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
|
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
|
||||||
-f "$BACKEND_JQ_FILTER" \
|
-f "$BACKEND_JQ_FILTER" \
|
||||||
"${configFile}" > "$RUNTIME_DIR/config.json"
|
"${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.
|
# 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
|
for backend_config in "$RUNTIME_DIR/config.json" "$RUNTIME_DIR/xray-sidecar.json"; do
|
||||||
[ -e "$backend_config" ] || continue
|
[ -e "$backend_config" ] || continue
|
||||||
@@ -416,6 +425,8 @@ let
|
|||||||
xrayTunDnsRuntime = pureXrayEnabled;
|
xrayTunDnsRuntime = pureXrayEnabled;
|
||||||
xraySidecarBasePort = xraySidecarBasePorts.tun;
|
xraySidecarBasePort = xraySidecarBasePorts.tun;
|
||||||
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
|
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
|
||||||
|
# Pure XRay's TUN routes by ip rules instead: see xrayTunUpScript.
|
||||||
|
excludeServiceUserFromTun = !pureXrayEnabled;
|
||||||
};
|
};
|
||||||
|
|
||||||
startPerAppTun = mkStartScript {
|
startPerAppTun = mkStartScript {
|
||||||
|
|||||||
+11
-1
@@ -8,7 +8,17 @@
|
|||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
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; };
|
parserChecks = import ./checks/parsers.nix { inherit pkgs; };
|
||||||
checkLib = import ./checks/lib.nix {
|
checkLib = import ./checks/lib.nix {
|
||||||
inherit
|
inherit
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ let
|
|||||||
# deployments keep these in a secret manager.
|
# deployments keep these in a secret manager.
|
||||||
uuid = "b831381d-6324-4d53-ad4f-8cda48b30811";
|
uuid = "b831381d-6324-4d53-ad4f-8cda48b30811";
|
||||||
ssPassword = "dGhpcy1pcy1hLTE2Ynl0ZS1rZXk=";
|
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: {
|
network = address: {
|
||||||
networking.useDHCP = false;
|
networking.useDHCP = false;
|
||||||
@@ -72,7 +73,7 @@ pkgs.testers.runNixOSTest {
|
|||||||
{
|
{
|
||||||
imports = [
|
imports = [
|
||||||
proxySuiteModule
|
proxySuiteModule
|
||||||
(network "192.168.0.2")
|
(network "11.0.0.2")
|
||||||
];
|
];
|
||||||
|
|
||||||
services.proxy-suite = {
|
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 == \"vless-in\" and .port == 8443)' {cfg}")
|
||||||
server.succeed(f"jq -e '.inbounds[] | select(.tag == \"ss-in\" and .port == 8388)' {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.
|
# 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")
|
server.fail("grep -r '${uuid}' /nix/store/*-proxy-suite-inbounds")
|
||||||
|
|
||||||
with subtest("safety rules are present and ordered first"):
|
with subtest("safety rules are present and ordered first"):
|
||||||
|
|||||||
@@ -49,6 +49,18 @@ let
|
|||||||
};
|
};
|
||||||
mixedConfig = mkInboundsConfig mixedFixture;
|
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.
|
# Two listeners, two different servers.
|
||||||
pinnedFixture = evalProxySuite [
|
pinnedFixture = evalProxySuite [
|
||||||
{
|
{
|
||||||
@@ -124,7 +136,7 @@ let
|
|||||||
type = "vless";
|
type = "vless";
|
||||||
port = 10002;
|
port = 10002;
|
||||||
sharePort = 443;
|
sharePort = 443;
|
||||||
address = "127.0.0.1";
|
address = "127.0.0.53";
|
||||||
users = [ { uuidFile = "/run/secrets/ws"; } ];
|
users = [ { uuidFile = "/run/secrets/ws"; } ];
|
||||||
transport = {
|
transport = {
|
||||||
type = "ws";
|
type = "ws";
|
||||||
@@ -215,7 +227,76 @@ let
|
|||||||
else
|
else
|
||||||
throw "proxy-inbounds check: expected an assertion matching '${fragment}', got: ${builtins.toJSON (map (a: a.message) failed)}";
|
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 = [
|
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 (
|
(mkRejects (
|
||||||
baseProxy
|
baseProxy
|
||||||
// {
|
// {
|
||||||
@@ -392,6 +473,24 @@ let
|
|||||||
(ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ];
|
(ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ];
|
||||||
true
|
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.
|
# No address to exempt when it is detected at runtime instead.
|
||||||
(assert !builtins.elem "inbound-server-address-direct" (ruleTags relayConfig); true)
|
(assert !builtins.elem "inbound-server-address-direct" (ruleTags relayConfig); true)
|
||||||
(
|
(
|
||||||
|
|||||||
@@ -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))
|
and _where_rule_set_match({"path": os.path.join(geosite_dir, f"geosite-{value}.srs"), "format": "binary"}, domain))
|
||||||
)
|
)
|
||||||
if matched:
|
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 "", ""
|
return "", ""
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -690,6 +690,11 @@ class WhereTest(EnvTest):
|
|||||||
self.assertEqual(ctl._where_inbounds(config, "rr1.googlevideo.com", "")[0], "proxy")
|
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, "youtube.com", ""), ("direct", "inbound-zapret-direct-domain (full:youtube.com)"))
|
||||||
self.assertEqual(ctl._where_inbounds(config, "example.org", "")[0], "proxy")
|
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):
|
class StatusSnapshotTest(EnvTest):
|
||||||
|
|||||||
+32
-10
@@ -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)
|
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:
|
def _b64(value: str) -> str:
|
||||||
"""base64 without padding, as share links carry it."""
|
"""base64 without padding, as share links carry it."""
|
||||||
return base64.urlsafe_b64encode(value.encode("utf-8")).decode("ascii").rstrip("=")
|
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"]
|
users = listener["users"]
|
||||||
if len(users) == 1:
|
if len(users) == 1:
|
||||||
settings["password"] = _user_secret(users[0], listener_type, tag)
|
settings["password"] = _user_secret(users[0], listener_type, tag)
|
||||||
|
settings["email"] = users[0].get("name") or f"{tag}-0"
|
||||||
else:
|
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)
|
settings["clients"] = _clients(listener, tag)
|
||||||
elif listener_type in ("socks", "http"):
|
elif listener_type in ("socks", "http"):
|
||||||
settings = {"auth": "password", "accounts": _accounts(listener, tag)}
|
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,
|
"id": secret,
|
||||||
"aid": "0",
|
"aid": "0",
|
||||||
"scy": "auto",
|
"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",
|
"type": "none",
|
||||||
"host": transport.get("host") or "",
|
"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 "",
|
"tls": "tls" if (tls["enable"] or reality["enable"]) else "",
|
||||||
"sni": tls.get("serverName") or server_address,
|
"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)
|
return _vmess_link(listener, secret, server_address, label)
|
||||||
|
|
||||||
if listener_type == "shadowsocks":
|
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}"
|
return f"ss://{userinfo}@{endpoint}#{fragment}"
|
||||||
|
|
||||||
if listener_type in ("socks", "http"):
|
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}")
|
userinfo = _b64(f"{user_name}:{secret}")
|
||||||
return f"socks://{userinfo}@{endpoint}#{fragment}"
|
return f"socks://{userinfo}@{endpoint}#{fragment}"
|
||||||
credentials = urllib.parse.quote(user_name, safe="") + ":" + urllib.parse.quote(secret, safe="")
|
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 = _link_transport_params(listener)
|
||||||
params.update(_link_security_params(listener, server_address))
|
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"]
|
tag = listener["tag"]
|
||||||
|
|
||||||
|
raw = listener.get("xrayJson")
|
||||||
if listener.get("jsonFile") is not None:
|
if listener.get("jsonFile") is not None:
|
||||||
with open(listener["jsonFile"], encoding="utf-8") as handle:
|
with open(listener["jsonFile"], encoding="utf-8") as handle:
|
||||||
inbound = json.load(handle)
|
raw = json.load(handle)
|
||||||
return {"tag": tag, "inbound": {**inbound, "tag": tag}, "links": []}
|
if raw is not None:
|
||||||
|
# The firewall and the port checks go by the listener's port, so the JSON must agree.
|
||||||
if listener.get("xrayJson") is not None:
|
port = raw.get("port", listener["port"])
|
||||||
return {"tag": tag, "inbound": {**listener["xrayJson"], "tag": tag}, "links": []}
|
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)
|
inbound = render_xray_inbound(listener)
|
||||||
links = (
|
links = (
|
||||||
|
|||||||
@@ -55,6 +55,20 @@ def reality(**overrides):
|
|||||||
return settings
|
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:
|
def link_params(link: str) -> dict:
|
||||||
query = urllib.parse.urlsplit(link).query
|
query = urllib.parse.urlsplit(link).query
|
||||||
return dict(urllib.parse.parse_qsl(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"]["method"], "2022-blake3-aes-128-gcm")
|
||||||
self.assertEqual(ib["settings"]["network"], "tcp,udp")
|
self.assertEqual(ib["settings"]["network"], "tcp,udp")
|
||||||
|
|
||||||
def test_shadowsocks_multi_user_uses_clients(self):
|
def test_shadowsocks_multi_user_has_server_key_and_clients(self):
|
||||||
ib = render_xray_inbound(
|
ib = render_xray_inbound(multi_user_shadowsocks())
|
||||||
listener(
|
self.assertEqual(ib["settings"]["password"], "server-psk")
|
||||||
type="shadowsocks",
|
self.assertEqual(
|
||||||
users=[
|
ib["settings"]["clients"],
|
||||||
{"name": "a", "password": "psk-a", "passwordFile": None},
|
[{"password": "psk-a", "email": "a"}, {"password": "psk-b", "email": "b"}],
|
||||||
{"name": "b", "password": "psk-b", "passwordFile": None},
|
|
||||||
],
|
|
||||||
)
|
)
|
||||||
)
|
|
||||||
self.assertNotIn("password", ib["settings"])
|
def test_shadowsocks_multi_user_needs_server_key(self):
|
||||||
self.assertEqual(len(ib["settings"]["clients"]), 2)
|
with self.assertRaisesRegex(ValueError, "no server password"):
|
||||||
|
render_xray_inbound(multi_user_shadowsocks(serverPassword=None))
|
||||||
|
|
||||||
def test_socks_accounts_and_udp(self):
|
def test_socks_accounts_and_udp(self):
|
||||||
ib = render_xray_inbound(
|
ib = render_xray_inbound(
|
||||||
@@ -262,13 +275,44 @@ class ShareLinkTests(unittest.TestCase):
|
|||||||
self.assertEqual(blob["net"], "ws")
|
self.assertEqual(blob["net"], "ws")
|
||||||
self.assertEqual(blob["tls"], "tls")
|
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):
|
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")
|
link = build_share_link(spec, "vpn.example.com")
|
||||||
userinfo = link[len("ss://") :].split("@", 1)[0]
|
userinfo = link[len("ss://") :].split("@", 1)[0]
|
||||||
userinfo += "=" * (-len(userinfo) % 4)
|
userinfo += "=" * (-len(userinfo) % 4)
|
||||||
decoded = base64.urlsafe_b64decode(userinfo).decode()
|
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):
|
class RoundTripTests(unittest.TestCase):
|
||||||
@@ -336,6 +380,11 @@ class RoundTripTests(unittest.TestCase):
|
|||||||
self.assertEqual(ob["method"], "2022-blake3-aes-128-gcm")
|
self.assertEqual(ob["method"], "2022-blake3-aes-128-gcm")
|
||||||
self.assertEqual(ob["password"], "psk")
|
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):
|
def test_vmess_round_trip(self):
|
||||||
link = build_share_link(listener(type="vmess"), "vpn.example.com")
|
link = build_share_link(listener(type="vmess"), "vpn.example.com")
|
||||||
ob = build_outbound(link, "round-trip", backend="sing-box")
|
ob = build_outbound(link, "round-trip", backend="sing-box")
|
||||||
@@ -485,6 +534,7 @@ class BuildInboundsTests(unittest.TestCase):
|
|||||||
listener(
|
listener(
|
||||||
tag="raw",
|
tag="raw",
|
||||||
type=None,
|
type=None,
|
||||||
|
port=8080,
|
||||||
xrayJson={"protocol": "dokodemo-door", "tag": "ignored", "port": 8080},
|
xrayJson={"protocol": "dokodemo-door", "tag": "ignored", "port": 8080},
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
@@ -502,7 +552,7 @@ class BuildInboundsTests(unittest.TestCase):
|
|||||||
spec = {
|
spec = {
|
||||||
"serverAddress": "vpn.example.com",
|
"serverAddress": "vpn.example.com",
|
||||||
"shareLinks": True,
|
"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")
|
result = build_inbounds(spec, "vpn.example.com")
|
||||||
self.assertEqual(result["inbounds"][0]["tag"], "secret-in")
|
self.assertEqual(result["inbounds"][0]["tag"], "secret-in")
|
||||||
|
|||||||
Reference in new issue
Block a user