From 2ce8da3f43db650a61fb7409c41e41573d362330 Mon Sep 17 00:00:00 2001 From: fufsob Date: Tue, 15 Sep 2026 17:40:59 +0000 Subject: [PATCH] fix: various fixes --- docs/options/inbounds.md | 50 ++++++++- .../config-templates/proxy-inbounds.nix | 15 ++- modules/proxy-suite/config.nix | 2 + modules/proxy-suite/derived.nix | 18 +++- modules/proxy-suite/nftables.nix | 8 ++ .../proxy-suite/options/types/inbounds.nix | 11 +- modules/proxy-suite/rules/proxy-inbounds.nix | 81 +++++++++----- modules/proxy-suite/service-assertions.nix | 78 ++++++++++++-- .../proxy-suite/service/routing-scripts.nix | 16 +++ .../script-blocks/backend-jq-filter.nix | 17 +-- modules/proxy-suite/service/start-scripts.nix | 11 ++ nix/checks.nix | 12 ++- nix/checks/proxy-inbounds-runtime.nix | 7 +- nix/checks/proxy-inbounds.nix | 101 +++++++++++++++++- pkgs/proxy-ctl/proxy_ctl.py | 7 +- pkgs/proxy-ctl/test_proxy_ctl.py | 5 + scripts/proxy_inbound.py | 42 ++++++-- scripts/test-build-inbound.py | 78 +++++++++++--- 18 files changed, 471 insertions(+), 88 deletions(-) diff --git a/docs/options/inbounds.md b/docs/options/inbounds.md index a451a1d..fcccad9 100644 --- a/docs/options/inbounds.md +++ b/docs/options/inbounds.md @@ -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 ## services\.proxy-suite\.inbounds\.listeners\.\\.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 ## services\.proxy-suite\.inbounds\.listeners\.\\.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 ## services\.proxy-suite\.inbounds\.listeners\.\\.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 ] ``` + +## services\.proxy-suite\.inbounds\.listeners\.\\.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=" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.serverPasswordFile + +Runtime path to the server key\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/run/secrets/proxy-inbound-ss-server-key" +``` + ## services\.proxy-suite\.inbounds\.listeners\.\\.sharePort @@ -789,7 +831,7 @@ null ## services\.proxy-suite\.inbounds\.listeners\.\\.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) diff --git a/modules/proxy-suite/config-templates/proxy-inbounds.nix b/modules/proxy-suite/config-templates/proxy-inbounds.nix index c9de485..a5e723f 100644 --- a/modules/proxy-suite/config-templates/proxy-inbounds.nix +++ b/modules/proxy-suite/config-templates/proxy-inbounds.nix @@ -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"; diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index b6da946..45dc7a5 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -49,6 +49,8 @@ let users flow method + serverPassword + serverPasswordFile transport tls reality diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index fac9b9e..85aaf7e 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -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; diff --git a/modules/proxy-suite/nftables.nix b/modules/proxy-suite/nftables.nix index 91234e1..daabd89 100644 --- a/modules/proxy-suite/nftables.nix +++ b/modules/proxy-suite/nftables.nix @@ -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} } diff --git a/modules/proxy-suite/options/types/inbounds.nix b/modules/proxy-suite/options/types/inbounds.nix index d01ae82..c4c4c6f 100644 --- a/modules/proxy-suite/options/types/inbounds.nix +++ b/modules/proxy-suite/options/types/inbounds.nix @@ -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 diff --git a/modules/proxy-suite/rules/proxy-inbounds.nix b/modules/proxy-suite/rules/proxy-inbounds.nix index a4fe849..092aeba 100644 --- a/modules/proxy-suite/rules/proxy-inbounds.nix +++ b/modules/proxy-suite/rules/proxy-inbounds.nix @@ -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 = diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 82cd8fc..abb4e9b 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -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 diff --git a/modules/proxy-suite/service/routing-scripts.nix b/modules/proxy-suite/service/routing-scripts.nix index 56a0f48..471ca7b 100644 --- a/modules/proxy-suite/service/routing-scripts.nix +++ b/modules/proxy-suite/service/routing-scripts.nix @@ -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; }} diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix index 9e41fee..90669ff 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -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 '' diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index 98e5689..e7b0261 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -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 { diff --git a/nix/checks.nix b/nix/checks.nix index e103726..d030f4e 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -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 diff --git a/nix/checks/proxy-inbounds-runtime.nix b/nix/checks/proxy-inbounds-runtime.nix index a128fc7..eecf16c 100644 --- a/nix/checks/proxy-inbounds-runtime.nix +++ b/nix/checks/proxy-inbounds-runtime.nix @@ -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"): diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index fd2934c..6e18a64 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -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) ( diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index ab7cc58..5095d20 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -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 "", "" diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index af365bd..5abf922 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -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): diff --git a/scripts/proxy_inbound.py b/scripts/proxy_inbound.py index 9f5cfa0..65f5a9c 100644 --- a/scripts/proxy_inbound.py +++ b/scripts/proxy_inbound.py @@ -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 = ( diff --git a/scripts/test-build-inbound.py b/scripts/test-build-inbound.py index 7ba8d80..2c31882 100644 --- a/scripts/test-build-inbound.py +++ b/scripts/test-build-inbound.py @@ -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")