diff --git a/docs/options/inbounds.md b/docs/options/inbounds.md index 1fac4fe..9ae3aa9 100644 --- a/docs/options/inbounds.md +++ b/docs/options/inbounds.md @@ -47,6 +47,14 @@ Part of the [proxy-suite options reference](./index.md). - [privateKeyFile](#services-proxy-suite-inbounds-listeners-name-amneziawg-privatekeyfile) - [subnet](#services-proxy-suite-inbounds-listeners-name-amneziawg-subnet) - [subnet6](#services-proxy-suite-inbounds-listeners-name-amneziawg-subnet6) + - [fallbacks](#services-proxy-suite-inbounds-listeners-name-fallbacks) + - item + - [alpn](#services-proxy-suite-inbounds-listeners-name-fallbacks-alpn) + - [dest](#services-proxy-suite-inbounds-listeners-name-fallbacks-dest) + - [listener](#services-proxy-suite-inbounds-listeners-name-fallbacks-listener) + - [name](#services-proxy-suite-inbounds-listeners-name-fallbacks-name) + - [path](#services-proxy-suite-inbounds-listeners-name-fallbacks-path) + - [xver](#services-proxy-suite-inbounds-listeners-name-fallbacks-xver) - [flow](#services-proxy-suite-inbounds-listeners-name-flow) - hysteria - [masquerade](#services-proxy-suite-inbounds-listeners-name-hysteria-masquerade) @@ -752,6 +760,154 @@ null "fd66:66::/64" ``` + +## services\.proxy-suite\.inbounds\.listeners\.\\.fallbacks + +Where XRay sends connections that are not this listener’s protocol, so several share +one port (vless or trojan on the raw transport)\. Matched in order on SNI, ALPN and path; +the first entry without any is the catch-all, such as a decoy web server\. Browsers +negotiate h2 unless tls\.alpn says otherwise, so a dest that speaks only HTTP/1\.1 needs +tls\.alpn = \[ “http/1\.1” ], or an alpn = “h2” entry to one that speaks h2c\. + +*Type:* +list of (submodule) + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + { path = "/ws"; listener = "ws-in"; } # ws-in: vless, ws, address = "127.0.0.1" + { dest = 8080; } +] + +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.fallbacks\.\*\.alpn + +Negotiated ALPN to match\. Null matches any\. + +*Type:* +null or one of “h2”, “http/1\.1” + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"h2" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.fallbacks\.\*\.dest + +Where matching connections go: a port, host:port, or a unix socket path\. Exclusive with listener\. + +*Type:* +null or 16 bit unsigned integer; between 0 and 65535 (both inclusive) or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"127.0.0.1:8080" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.fallbacks\.\*\.listener + +Tag of another listener that matching connections go to, instead of dest\. It must be a +vless listener without tls or reality, on a loopback address: it gets the connection +decrypted, with the client address in PROXY protocol, and its share links advertise this +listener’s port and TLS or REALITY\. Behind REALITY it must be xhttp or grpc, the only +transports REALITY clients run besides raw\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"ws-in" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.fallbacks\.\*\.name + +SNI to match\. Null matches any\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"www.example.com" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.fallbacks\.\*\.path + +Request path to match\. Null matches any\. XRay reads it from HTTP/1\.1 only, so a ` listener ` +must be on ws or httpupgrade, with this as its transport\.path; xhttp and grpc clients speak h2 +and go by alpn = “h2” or a catch-all instead\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"/ws" +``` + + +## services\.proxy-suite\.inbounds\.listeners\.\\.fallbacks\.\*\.xver + +PROXY protocol version sent to dest; 0 sends none\. A listener always gets 2\. + +*Type:* +one of 0, 1, 2 + +*Default:* + +```nix +0 +``` + ## services\.proxy-suite\.inbounds\.listeners\.\\.flow diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 9026e50..240cfc2 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -35,6 +35,32 @@ let inherit (xrayTemplates) mkDnsServer; }; + # Fallbacks to another listener are resolved here, where every listener is known. + inboundByTag = tag: lib.findFirst (ib: ib.tag == tag) null derived.proxyInbounds; + fallbackFront = + tag: + lib.findFirst ( + ib: lib.any (fb: fb.listener == tag) ib.listener.fallbacks + ) null derived.proxyInbounds; + renderFallback = + fb: + { + inherit (fb) name alpn path; + } + // ( + if fb.listener == null then + { inherit (fb) dest xver; } + else + let + target = (inboundByTag fb.listener).listener; + host = if lib.hasInfix ":" target.address then "[${target.address}]" else target.address; + in + { + dest = "${host}:${toString target.port}"; + xver = 2; + } + ); + # Listener specification handed to build-inbound.py at service start. Secrets # appear here only as paths; the script reads them at runtime. proxyInboundsSpec = { @@ -63,6 +89,25 @@ let jsonFile ; listen = ib.listener.address; + fallbacks = map renderFallback ib.listener.fallbacks; + # The listener in front, whose port and TLS or REALITY the share links carry. + front = + let + f = fallbackFront ib.tag; + in + if f == null then + null + else + { + inherit (f) tag; + inherit (f.listener) + type + port + sharePort + tls + reality + ; + }; } # Only on AmneziaWG listeners: the defaults of the others need not type-check. // lib.optionalAttrs (ib.listener.type == "amneziawg") { diff --git a/modules/proxy-suite/options/types/inbounds.nix b/modules/proxy-suite/options/types/inbounds.nix index bd92e80..0e0508b 100644 --- a/modules/proxy-suite/options/types/inbounds.nix +++ b/modules/proxy-suite/options/types/inbounds.nix @@ -244,6 +244,55 @@ let }; }; + fallbackType = types.submodule { + options = { + name = nullStr "SNI to match. Null matches any." "www.example.com"; + + alpn = mkOption { + type = types.nullOr ( + types.enum [ + "h2" + "http/1.1" + ] + ); + default = null; + description = "Negotiated ALPN to match. Null matches any."; + example = "h2"; + }; + + path = nullStr '' + Request path to match. Null matches any. XRay reads it from HTTP/1.1 only, so a `listener` + must be on ws or httpupgrade, with this as its transport.path; xhttp and grpc clients speak h2 + and go by alpn = "h2" or a catch-all instead. + '' "/ws"; + + dest = mkOption { + type = types.nullOr (types.either types.port types.str); + default = null; + description = "Where matching connections go: a port, host:port, or a unix socket path. Exclusive with listener."; + example = "127.0.0.1:8080"; + }; + + listener = nullStr '' + Tag of another listener that matching connections go to, instead of dest. It must be a + vless listener without tls or reality, on a loopback address: it gets the connection + decrypted, with the client address in PROXY protocol, and its share links advertise this + listener's port and TLS or REALITY. Behind REALITY it must be xhttp or grpc, the only + transports REALITY clients run besides raw. + '' "ws-in"; + + xver = mkOption { + type = types.enum [ + 0 + 1 + 2 + ]; + default = 0; + description = "PROXY protocol version sent to dest; 0 sends none. A listener always gets 2."; + }; + }; + }; + inboundType = types.submodule ( { name, ... }: { @@ -335,6 +384,24 @@ let description = "REALITY."; }; + fallbacks = mkOption { + type = types.listOf fallbackType; + default = [ ]; + description = '' + Where XRay sends connections that are not this listener's protocol, so several share + one port (vless or trojan on the raw transport). Matched in order on SNI, ALPN and path; + the first entry without any is the catch-all, such as a decoy web server. Browsers + negotiate h2 unless tls.alpn says otherwise, so a dest that speaks only HTTP/1.1 needs + tls.alpn = [ "http/1.1" ], or an alpn = "h2" entry to one that speaks h2c. + ''; + example = lib.literalExpression '' + [ + { path = "/ws"; listener = "ws-in"; } # ws-in: vless, ws, address = "127.0.0.1" + { dest = 8080; } + ] + ''; + }; + xrayJson = mkOption { type = types.nullOr types.attrs; default = null; diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 4f39f3a..f90e354 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -609,8 +609,86 @@ let (mkAssertion ( !proxyInboundsEnabled || l.hysteria.masquerade == null || l.type == "hysteria2" ) "${prefix}: hysteria.masquerade is for hysteria2 listeners only") + (mkAssertion ( + !proxyInboundsEnabled + || l.fallbacks == [ ] + || ( + builtins.elem l.type [ + "vless" + "trojan" + ] + && l.transport.type == "raw" + ) + ) "${prefix}: fallbacks run only on a vless or trojan listener with transport.type = \"raw\"") ] - ) proxyInbounds; + ++ map ( + fb: + exactlyOneOf proxyInboundsEnabled [ + fb.dest + fb.listener + ] "${prefix}: fallbacks each need exactly one of dest or listener" + ) l.fallbacks + # The target gets the connection decrypted and in PROXY protocol, which only + # the front may send it, and its share links take the front's security. + ++ lib.concatMap ( + fb: + let + target = lib.findFirst (other: other.tag == fb.listener) null proxyInbounds; + t = target.listener; + in + [ + (mkAssertion + ( + !proxyInboundsEnabled + || ( + target != null + && target.tag != ib.tag + && t.type == "vless" + && !t.tls.enable + && !t.reality.enable + && (lib.hasPrefix "127." t.address || t.address == "::1") + ) + ) + "${prefix}: fallback listener '${fb.listener}' must be another vless listener, without tls or reality, on a loopback address" + ) + # XRay matches path on HTTP/1.1 only; xhttp and grpc clients speak h2 under TLS. + (mkAssertion + ( + !proxyInboundsEnabled + || fb.path == null + || target == null + || ( + builtins.elem t.transport.type [ + "ws" + "httpupgrade" + ] + && fb.path == t.transport.path + ) + ) + "${prefix}: fallback path matches only a ws or httpupgrade listener '${fb.listener}', and must be its transport.path" + ) + # REALITY clients run raw, xhttp and grpc only, and raw would be the front's own protocol. + (mkAssertion + ( + !proxyInboundsEnabled + || !l.reality.enable + || target == null + || builtins.elem t.transport.type [ + "xhttp" + "grpc" + ] + ) + "${prefix}: a REALITY listener's fallback listener '${fb.listener}' must use the xhttp or grpc transport" + ) + ] + ) (builtins.filter (fb: fb.listener != null) l.fallbacks) + ) proxyInbounds + # Its share links can carry only one front's port and security. + ++ [ + (uniqueValues proxyInboundsEnabled (lib.concatMap ( + ib: builtins.filter (tag: tag != null) (map (fb: fb.listener) ib.listener.fallbacks) + ) proxyInbounds) "proxy-suite: a listener can be the fallback listener of only one other") + ]; # AmneziaWG listeners run an interface each and give their clients addresses in a subnet. awgListeners = builtins.filter (ib: ib.listener.type == "amneziawg") proxyInbounds; diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index b3f93cb..6f6b313 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -186,6 +186,52 @@ let firewallSpec = mkInboundsSpec firewallFixture; wsListener = lib.head (builtins.filter (l: l.tag == "ws-in") firewallSpec.listeners); + # A ws listener behind a TLS front's fallback, and a decoy web server. + fallbackTarget = { + type = "vless"; + port = 10002; + address = "127.0.0.1"; + users = [ { uuidFile = "/run/secrets/ws"; } ]; + transport = { + type = "ws"; + path = "/ws"; + }; + }; + fallbackListeners = { + front-in = { + type = "vless"; + port = 443; + users = [ { uuidFile = "/run/secrets/uuid"; } ]; + tls = { + enable = true; + certificateFile = "/run/acme/fullchain.pem"; + keyFile = "/run/acme/key.pem"; + }; + fallbacks = [ + { + path = "/ws"; + listener = "ws-in"; + } + { dest = 8080; } + ]; + }; + ws-in = fallbackTarget; + }; + fallbackFixture = mkInbounds { listeners = fallbackListeners; }; + fallbackSpec = mkInboundsSpec fallbackFixture; + fallbackSpecListener = tag: lib.head (builtins.filter (l: l.tag == tag) fallbackSpec.listeners); + mkRejectsFallback = + listeners: + mkRejects ( + baseProxy + // { + inbounds = { + enable = true; + inherit listeners; + }; + } + ); + noFirewallFixture = mkInbounds { openFirewall = false; listeners.vless-in = realityListener; @@ -324,6 +370,74 @@ let ]; failing = [ + (mkRejectsListener ( + realityListener + // { + transport.type = "xhttp"; + fallbacks = [ { dest = 8080; } ]; + } + ) "fallbacks run only on a vless or trojan listener") + (mkRejectsListener ( + realityListener // { fallbacks = [ { } ]; } + ) "fallbacks each need exactly one of dest or listener") + (mkRejectsFallback ( + fallbackListeners + // { + ws-in = fallbackTarget // { + address = "::"; + }; + } + ) "fallback listener 'ws-in' must be another vless listener") + (mkRejectsFallback ( + fallbackListeners + // { + ws-in = fallbackTarget // { + tls.enable = true; + }; + } + ) "fallback listener 'ws-in' must be another vless listener") + (mkRejectsFallback ( + fallbackListeners + // { + front-in = fallbackListeners.front-in // { + fallbacks = [ { listener = "missing"; } ]; + }; + } + ) "fallback listener 'missing' must be another vless listener") + (mkRejectsFallback ( + fallbackListeners + // { + front-in = fallbackListeners.front-in // { + fallbacks = [ + { + path = "/other"; + listener = "ws-in"; + } + ]; + }; + } + ) "fallback path matches only a ws or httpupgrade listener 'ws-in'") + (mkRejectsFallback ( + fallbackListeners + // { + front-in = fallbackListeners.front-in // { + fallbacks = [ { listener = "ws-in"; } ]; + reality.enable = true; + }; + ws-in = fallbackTarget // { + transport.type = "ws"; + }; + } + ) "a REALITY listener's fallback listener 'ws-in' must use the xhttp or grpc transport") + (mkRejectsFallback ( + fallbackListeners + // { + second-in = realityListener // { + port = 8443; + fallbacks = [ { listener = "ws-in"; } ]; + }; + } + ) "can be the fallback listener of only one other") (mkRejectsListener ( realityListener // { port = 18533; } ) "collides with a port proxy-suite uses internally") @@ -697,6 +811,31 @@ let true ) (ok (wsListener.port == 10002 && wsListener.sharePort == 443)) + # A fallback to a listener is resolved to its address, in PROXY protocol; a dest is kept as is. + (ok ( + (fallbackSpecListener "front-in").fallbacks == [ + { + name = null; + alpn = null; + path = "/ws"; + dest = "127.0.0.1:10002"; + xver = 2; + } + { + name = null; + alpn = null; + path = null; + dest = 8080; + xver = 0; + } + ] + )) + (ok ((fallbackSpecListener "ws-in").front.tag == "front-in")) + (ok ((fallbackSpecListener "ws-in").front.tls.enable)) + (ok ((fallbackSpecListener "front-in").front == null)) + (ok ( + !lib.any (a: !a.assertion && lib.hasInfix "fallback" a.message) fallbackFixture.config.assertions + )) (ok ( (lib.head (builtins.filter (l: l.tag == "hy2-in") firewallSpec.listeners)).hysteria.masquerade == "https://www.example.com" diff --git a/scripts/proxy_inbound.py b/scripts/proxy_inbound.py index 0289036..2ed309b 100644 --- a/scripts/proxy_inbound.py +++ b/scripts/proxy_inbound.py @@ -125,7 +125,10 @@ def _xray_stream(listener: dict, tag: str) -> dict: # Behind a web server the socket address is loopback, which XRay will not record as # online; the forwarded address is only trusted when one of these headers is present. if transport.get("trustedXForwardedFor"): - stream["sockopt"] = {"trustedXForwardedFor": transport["trustedXForwardedFor"]} + stream.setdefault("sockopt", {})["trustedXForwardedFor"] = transport["trustedXForwardedFor"] + # Behind another listener's fallback, the client address arrives in PROXY protocol. + if listener.get("front"): + stream.setdefault("sockopt", {})["acceptProxyProtocol"] = True reality = listener["reality"] tls = listener["tls"] @@ -193,6 +196,12 @@ def render_xray_inbound(listener: dict) -> dict: else: raise ValueError(f"listener '{tag}': unsupported type '{listener_type}'") + if listener.get("fallbacks"): + settings["fallbacks"] = [ + {key: value for key, value in fallback.items() if value is not None} + for fallback in listener["fallbacks"] + ] + return { "tag": tag, "listen": listener["listen"], @@ -310,7 +319,9 @@ def build_share_link( fragment = urllib.parse.quote(label, safe="") endpoint_address = onion_address or server_address host = f"[{endpoint_address}]" if ":" in endpoint_address else endpoint_address - endpoint = f"{host}:{_share_port(listener)}" + # Behind another listener's fallback, clients dial that one, under its TLS or REALITY. + front = listener.get("front") or listener + endpoint = f"{host}:{_share_port(front)}" if listener_type == "vmess": return _vmess_link(listener, secret, server_address, label, endpoint_address) @@ -342,7 +353,7 @@ def build_share_link( return f"hysteria2://{urllib.parse.quote(secret, safe='')}@{endpoint}?{query}#{fragment}" params = _link_transport_params(listener) - params.update(_link_security_params(listener, server_address)) + params.update(_link_security_params(front, server_address)) if listener_type == "vless" and listener.get("flow"): params["flow"] = listener["flow"] query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote) @@ -419,7 +430,7 @@ def build_listener( return { "tag": tag, "type": listener["type"], - "port": _share_port(listener), + "port": _share_port(listener.get("front") or listener), "inbound": inbound, "links": links, "onionLinks": onion_links, diff --git a/scripts/test-build-inbound.py b/scripts/test-build-inbound.py index d1a3476..5b82734 100644 --- a/scripts/test-build-inbound.py +++ b/scripts/test-build-inbound.py @@ -163,6 +163,26 @@ class RenderInboundTests(unittest.TestCase): {"trustedXForwardedFor": ["X-Real-IP"]}, ) + def test_fallbacks_reach_settings_without_nulls(self): + self.assertNotIn("fallbacks", render_xray_inbound(listener())["settings"]) + fallbacks = [ + {"name": None, "alpn": None, "path": "/ws", "dest": "127.0.0.1:10002", "xver": 2}, + {"name": None, "alpn": None, "path": None, "dest": 8080, "xver": 0}, + ] + self.assertEqual( + render_xray_inbound(listener(fallbacks=fallbacks))["settings"]["fallbacks"], + [{"path": "/ws", "dest": "127.0.0.1:10002", "xver": 2}, {"dest": 8080, "xver": 0}], + ) + + def test_fallback_target_accepts_proxy_protocol(self): + """The front sends the client address in PROXY protocol; loopback alone records nobody online.""" + transport = {"type": "ws", "path": "/ws", "host": None, "serviceName": "", "trustedXForwardedFor": ["X-Real-IP"]} + front = {"tag": "front-in", "type": "vless", "port": 443, "sharePort": None} + self.assertEqual( + render_xray_inbound(listener(transport=transport, front=front))["streamSettings"]["sockopt"], + {"trustedXForwardedFor": ["X-Real-IP"], "acceptProxyProtocol": True}, + ) + def test_grpc_transport(self): ib = render_xray_inbound( listener(transport={"type": "grpc", "path": "/", "host": None, "serviceName": "GunService"}) @@ -231,6 +251,32 @@ class ShareLinkTests(unittest.TestCase): self.assertEqual(params["flow"], "xtls-rprx-vision") self.assertEqual(params["type"], "tcp") + def test_fallback_target_link_carries_the_front(self): + """Clients dial the front, under its TLS or REALITY, with the target's own transport.""" + transport = {"type": "ws", "path": "/ws", "host": "cdn.example.com", "serviceName": "", "trustedXForwardedFor": []} + target = listener(port=10002, listen="127.0.0.1", transport=transport) + tls_front = { + "tag": "front-in", + "type": "trojan", + "port": 8443, + "sharePort": 443, + "tls": {"enable": False, "certificateFile": "/c", "keyFile": "/k", "serverName": "vpn.example.com"}, + "reality": listener()["reality"], + } + link = build_share_link(dict(target, front=tls_front), "1.2.3.4") + self.assertTrue(link.startswith("vless://uuid-1@1.2.3.4:443?")) + params = link_params(link) + self.assertEqual(params["security"], "tls") + self.assertEqual(params["sni"], "vpn.example.com") + self.assertEqual((params["type"], params["path"], params["host"]), ("ws", "/ws", "cdn.example.com")) + + reality_front = dict(tls_front, type="vless", port=443, sharePort=None, reality=reality()) + params = link_params(build_share_link(dict(target, front=reality_front), "1.2.3.4")) + self.assertEqual( + (params["security"], params["pbk"], params["sni"], params["sid"]), + ("reality", "public-key", "www.microsoft.com", "0123abcd"), + ) + def test_reality_link_without_public_key_fails(self): with self.assertRaisesRegex(ValueError, "reality.publicKey is required"): build_share_link(listener(reality=reality(publicKey=None)), "vpn.example.com")