diff --git a/README.md b/README.md index c9a5107..4bd7722 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ The goal is to replace GUI clients like v2rayN and throne – you configure your - **DPI bypass** via zapret – handles YouTube, Discord, and other sites defined by the project - **Telegram proxy** – running local MTProto WebSocket proxy using tg-ws-proxy - **SSH SOCKS5 proxy** – create a local SOCKS5 listener from an SSH connection +- **Server inbounds** – accept connections *from* outside over vless (REALITY), vmess, trojan, shadowsocks, socks, or http; relay them through your outbounds or exit directly, with share links and QR codes for clients --- @@ -92,15 +93,15 @@ services.proxy-suite = { }; }; - # Optional SSH dynamic SOCKS5 proxy. Set asOutbound = true to make the - # local SSH SOCKS listener available as an ordinary proxy outbound. + # Optional SSH tunnel. Set asOutbound = true to make it an ordinary proxy + # outbound tagged "ssh-proxy". sshProxy = { enable = true; user = "root"; host = "ssh.example.com"; asOutbound = false; identityFile = "/run/secrets/proxy-suite-ssh-key"; - knownHostsFile = "/run/secrets/proxy-suite-ssh-known-hosts"; + hostKeyFile = "/run/secrets/proxy-suite-ssh-known-hosts"; }; # Native AmneziaWG profiles are independent of the SingBox/XRay backend. @@ -168,6 +169,7 @@ Commands: proxy on|off enable/disable the proxy backend stack tproxy on|off enable/disable TProxy transparent mode tun on|off enable/disable TUN mode + ssh on|off enable/disable the SSH SOCKS5 proxy awg list|status [profile] list profiles or show AmneziaWG status awg on start an AmneziaWG profile awg off [profile] stop one or all active AmneziaWG profiles @@ -183,5 +185,8 @@ Commands: wrap -- run a command via a perAppRouting profile subscription list show subscriptions, cache age, and proxy count subscription update force-refresh all subscription caches and restart active proxy services + inbounds [list] list server inbounds and their state + inbounds link [user] print the client share link for an inbound + inbounds qr [user] print the client share link as a QR code ``` diff --git a/docs/options.md b/docs/options.md index ec5f6d2..6c87b53 100644 --- a/docs/options.md +++ b/docs/options.md @@ -181,11 +181,59 @@ Update module option docs there instead of editing this file by hand. - xray - [enable](#services-proxy-suite-proxy-xray-enable) - [package](#services-proxy-suite-proxy-xray-package) + - proxyInbounds + - [enable](#services-proxy-suite-proxyinbounds-enable) + - [package](#services-proxy-suite-proxyinbounds-package) + - [blockPrivate](#services-proxy-suite-proxyinbounds-blockprivate) + - [blockRu](#services-proxy-suite-proxyinbounds-blockru) + - [listeners](#services-proxy-suite-proxyinbounds-listeners) + - `` + - [flow](#services-proxy-suite-proxyinbounds-listeners-name-flow) + - [jsonFile](#services-proxy-suite-proxyinbounds-listeners-name-jsonfile) + - [listenAddress](#services-proxy-suite-proxyinbounds-listeners-name-listenaddress) + - [method](#services-proxy-suite-proxyinbounds-listeners-name-method) + - [port](#services-proxy-suite-proxyinbounds-listeners-name-port) + - [reality](#services-proxy-suite-proxyinbounds-listeners-name-reality) + - [enable](#services-proxy-suite-proxyinbounds-listeners-name-reality-enable) + - [dest](#services-proxy-suite-proxyinbounds-listeners-name-reality-dest) + - [privateKey](#services-proxy-suite-proxyinbounds-listeners-name-reality-privatekey) + - [privateKeyFile](#services-proxy-suite-proxyinbounds-listeners-name-reality-privatekeyfile) + - [publicKey](#services-proxy-suite-proxyinbounds-listeners-name-reality-publickey) + - [serverNames](#services-proxy-suite-proxyinbounds-listeners-name-reality-servernames) + - [shortIds](#services-proxy-suite-proxyinbounds-listeners-name-reality-shortids) + - [tls](#services-proxy-suite-proxyinbounds-listeners-name-tls) + - [enable](#services-proxy-suite-proxyinbounds-listeners-name-tls-enable) + - [certificateFile](#services-proxy-suite-proxyinbounds-listeners-name-tls-certificatefile) + - [keyFile](#services-proxy-suite-proxyinbounds-listeners-name-tls-keyfile) + - [serverName](#services-proxy-suite-proxyinbounds-listeners-name-tls-servername) + - [transport](#services-proxy-suite-proxyinbounds-listeners-name-transport) + - [host](#services-proxy-suite-proxyinbounds-listeners-name-transport-host) + - [path](#services-proxy-suite-proxyinbounds-listeners-name-transport-path) + - [serviceName](#services-proxy-suite-proxyinbounds-listeners-name-transport-servicename) + - [type](#services-proxy-suite-proxyinbounds-listeners-name-transport-type) + - [type](#services-proxy-suite-proxyinbounds-listeners-name-type) + - [users](#services-proxy-suite-proxyinbounds-listeners-name-users) + - item + - [name](#services-proxy-suite-proxyinbounds-listeners-name-users-name) + - [password](#services-proxy-suite-proxyinbounds-listeners-name-users-password) + - [passwordFile](#services-proxy-suite-proxyinbounds-listeners-name-users-passwordfile) + - [uuid](#services-proxy-suite-proxyinbounds-listeners-name-users-uuid) + - [uuidFile](#services-proxy-suite-proxyinbounds-listeners-name-users-uuidfile) + - [via](#services-proxy-suite-proxyinbounds-listeners-name-via) + - [xrayJson](#services-proxy-suite-proxyinbounds-listeners-name-xrayjson) + - [openFirewall](#services-proxy-suite-proxyinbounds-openfirewall) + - [serverAddress](#services-proxy-suite-proxyinbounds-serveraddress) + - [shareLinks](#services-proxy-suite-proxyinbounds-sharelinks) + - [via](#services-proxy-suite-proxyinbounds-via) + - [zapretDirect](#services-proxy-suite-proxyinbounds-zapretdirect) - sshProxy - [enable](#services-proxy-suite-sshproxy-enable) - [asOutbound](#services-proxy-suite-sshproxy-asoutbound) + - [domainStrategy](#services-proxy-suite-sshproxy-domainstrategy) - [extraArgs](#services-proxy-suite-sshproxy-extraargs) - [host](#services-proxy-suite-sshproxy-host) + - [hostKey](#services-proxy-suite-sshproxy-hostkey) + - [hostKeyFile](#services-proxy-suite-sshproxy-hostkeyfile) - [identityFile](#services-proxy-suite-sshproxy-identityfile) - [knownHostsFile](#services-proxy-suite-sshproxy-knownhostsfile) - [listenAddress](#services-proxy-suite-sshproxy-listenaddress) @@ -380,11 +428,26 @@ services.proxy-suite = { package = pkgs.xray; }; }; + proxyInbounds = { + blockPrivate = true; + blockRu = true; + enable = false; + listeners = { }; + openFirewall = true; + package = pkgs.xray; + serverAddress = null; + shareLinks = true; + via = "proxy"; + zapretDirect = true; + }; sshProxy = { asOutbound = false; + domainStrategy = null; enable = false; extraArgs = [ ]; host = null; + hostKey = [ ]; + hostKeyFile = null; identityFile = null; knownHostsFile = null; listenAddress = "127.0.0.1"; @@ -661,14 +724,51 @@ services.proxy-suite = { package = pkgs.xray; }; }; + proxyInbounds = { + blockPrivate = false; + blockRu = false; + enable = true; + listeners = { + _type = "literalExpression"; + text = '' + { + vless-reality = { + type = "vless"; + port = 443; + users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]; + flow = "xtls-rprx-vision"; + reality = { + enable = true; + dest = "www.microsoft.com:443"; + serverNames = [ "www.microsoft.com" ]; + privateKeyFile = "/run/secrets/proxy-inbound-reality-key"; + publicKey = "jNXH..."; + shortIds = [ "0123abcd" ]; + }; + }; + } + ''; + }; + openFirewall = false; + package = pkgs.xray; + serverAddress = "vpn.example.com"; + shareLinks = false; + via = "direct"; + zapretDirect = false; + }; sshProxy = { asOutbound = true; + domainStrategy = "prefer_ipv4"; enable = true; extraArgs = [ "-o" "ServerAliveInterval=30" ]; host = "ssh.example.com"; + hostKey = [ + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." + ]; + hostKeyFile = "/root/.ssh/known_hosts"; identityFile = "/run/secrets/proxy-suite-ssh-key"; knownHostsFile = "/run/secrets/proxy-suite-ssh-known-hosts"; listenAddress = "127.0.0.1"; @@ -5571,6 +5671,1519 @@ pkgs.xray + +## services\.proxy-suite\.proxyInbounds\.enable + + + +Whether to enable server-side proxy inbounds (accept connections from outside)\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +false +``` + + + +*Example:* + +```nix +true +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.package + + + +XRay package serving the inbounds\. + +This is independent of proxy\.xray\.package: the inbound service always +runs XRay, whichever backend the client side uses, and works with +proxy\.enable = false\. + + + +*Type:* +package + + + +*Default:* + +```nix +pkgs.xray +``` + + + +*Example:* + +```nix +pkgs.xray +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.blockPrivate + + + +Send traffic destined for private and loopback addresses to the block +outbound\. + +On by default: without it, anyone holding an inbound credential can +reach the server’s LAN, its localhost services, and the local proxy +ports of proxy-suite itself\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +true +``` + + + +*Example:* + +```nix +false +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.blockRu + + + +Send traffic destined for Russian domains and IP ranges +(“category-ru” geosite, “ru” geoip) to the block outbound\. + +On by default: a relay whose whole point is leaving the RKN-filtered +network has no reason to carry traffic back into it, and it keeps the +server out of the way of domestic services that geo-check\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +true +``` + + + +*Example:* + +```nix +false +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners + + + +Named inbound listeners\. The attribute name becomes the inbound tag +used in routing rules and in ` proxy-ctl inbounds `\. + + + +*Type:* +attribute set of (submodule) + + + +*Default:* + +```nix +{ } +``` + + + +*Example:* + +```nix +{ + vless-reality = { + type = "vless"; + port = 443; + users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]; + flow = "xtls-rprx-vision"; + reality = { + enable = true; + dest = "www.microsoft.com:443"; + serverNames = [ "www.microsoft.com" ]; + privateKeyFile = "/run/secrets/proxy-inbound-reality-key"; + publicKey = "jNXH..."; + shortIds = [ "0123abcd" ]; + }; + }; +} + +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.flow + + + +VLESS flow control\. “xtls-rprx-vision” is the usual pairing with +REALITY on the “raw” transport; it is not valid over ws, grpc, +httpupgrade, or xhttp\. + + + +*Type:* +null or value “xtls-rprx-vision” (singular enum) + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"xtls-rprx-vision" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.jsonFile + + + +Runtime path to a file containing a complete XRay inbound object as +JSON\. Read at service start time, so the whole inbound including its +credentials can be rendered by a secret manager and never lands in +the Nix store\. The tag field is overridden by the listener name\. + +No share link is generated for listeners defined this way\. + +Set exactly one of type, xrayJson, or jsonFile for each listener\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"/run/secrets/proxy-inbound-vless.json" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.listenAddress + + + +Address this listener binds\. The default accepts both IPv4 and IPv6 +connections from anywhere\. + + + +*Type:* +string matching the pattern \[^\[:space:]]+ + + + +*Default:* + +```nix +"::" +``` + + + +*Example:* + +```nix +"0.0.0.0" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.method + + + +Shadowsocks cipher\. Ignored by other protocols\. + +The 2022 ciphers require a base64 pre-shared key of the matching +length as the password, not a passphrase\. + + + +*Type:* +string + + + +*Default:* + +```nix +"2022-blake3-aes-128-gcm" +``` + + + +*Example:* + +```nix +"aes-128-gcm" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.port + + + +Port this listener binds\. Opened in the firewall automatically unless +proxyInbounds\.openFirewall is disabled\. + + + +*Type:* +16 bit unsigned integer; between 0 and 65535 (both inclusive) + + + +*Default:* + +```nix +443 +``` + + + +*Example:* + +```nix +443 +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality + + + +REALITY settings for this listener\. Mutually exclusive with tls\. + + + +*Type:* +submodule + + + +*Default:* + +```nix +{ } +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.enable + + + +Enable REALITY on this listener\. Mutually exclusive with tls\.enable\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +false +``` + + + +*Example:* + +```nix +true +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.dest + + + +Real TLS server that unauthenticated probes are proxied to\. Must be a +host:port that serves TLS 1\.3 with HTTP/2\. + + + +*Type:* +string + + + +*Default:* + +```nix +"www.microsoft.com:443" +``` + + + +*Example:* + +```nix +"www.microsoft.com:443" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.privateKey + + + +Literal REALITY x25519 private key\. + +This value is embedded in the Nix store\. Prefer privateKeyFile\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"gG1Yz..." +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.privateKeyFile + + + +Runtime path to the REALITY x25519 private key, as produced by +` xray x25519 `\. Read at service start time; never lands in the Nix +store\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"/run/secrets/proxy-inbound-reality-key" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.publicKey + + + +REALITY x25519 public key matching privateKeyFile, as printed +alongside it by ` xray x25519 `\. Not a secret: clients need it, and it +is what generated share links carry as ` pbk `\. + +Required when proxyInbounds\.shareLinks is enabled\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"jNXH..." +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.serverNames + + + +SNI values accepted by this listener\. These must be names the dest +server actually serves\. The first entry is used in share links\. + + + +*Type:* +list of string + + + +*Default:* + +```nix +[ ] +``` + + + +*Example:* + +```nix +[ + "www.microsoft.com" +] +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.reality\.shortIds + + + +Accepted REALITY short IDs (hex, up to 16 characters)\. The default +accepts the empty short ID\. The first entry is used in share links\. + + + +*Type:* +list of string + + + +*Default:* + +```nix +[ + "" +] +``` + + + +*Example:* + +```nix +[ + "0123abcd" +] +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls + + + +TLS termination settings for this listener\. Mutually exclusive with +reality\. + + + +*Type:* +submodule + + + +*Default:* + +```nix +{ } +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls\.enable + + + +Terminate TLS on this listener\. Mutually exclusive with reality\. + +Always on for trojan listeners regardless of this setting\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +false +``` + + + +*Example:* + +```nix +true +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls\.certificateFile + + + +Runtime path to the PEM certificate chain\. Compose with +security\.acme to keep it renewed\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"/var/lib/acme/example.com/fullchain.pem" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls\.keyFile + + + +Runtime path to the PEM private key matching certificateFile\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"/var/lib/acme/example.com/key.pem" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.tls\.serverName + + + +SNI advertised in generated share links\. Defaults to +proxyInbounds\.serverAddress when unset\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"example.com" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport + + + +Stream transport settings for this listener\. + + + +*Type:* +submodule + + + +*Default:* + +```nix +{ } +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport\.host + + + +Expected Host header for the “ws”, “httpupgrade”, and “xhttp” +transports\. Leave null to accept any host\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"cdn.example.com" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport\.path + + + +Request path for the “ws”, “httpupgrade”, and “xhttp” transports\. +Ignored by the other transports\. + + + +*Type:* +string + + + +*Default:* + +```nix +"/" +``` + + + +*Example:* + +```nix +"/download" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport\.serviceName + + + +gRPC service name for the “grpc” transport\. Ignored otherwise\. + + + +*Type:* +string + + + +*Default:* + +```nix +"" +``` + + + +*Example:* + +```nix +"GunService" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.transport\.type + + + +Stream transport for this listener\. “raw” is plain TCP and is what +REALITY setups normally use\. + + + +*Type:* +one of “raw”, “ws”, “grpc”, “httpupgrade”, “xhttp” + + + +*Default:* + +```nix +"raw" +``` + + + +*Example:* + +```nix +"ws" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.type + + + +Proxy protocol served by this listener\. + +Set exactly one of type, xrayJson, or jsonFile for each listener\. + + + +*Type:* +null or one of “vless”, “vmess”, “trojan”, “shadowsocks”, “socks”, “http” + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"vless" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users + + + +Accounts accepted by this listener\. vless and vmess use uuid/uuidFile; +trojan, shadowsocks, socks, and http use password/passwordFile\. + +A share link is generated for the first user of each listener\. + + + +*Type:* +list of (submodule) + + + +*Default:* + +```nix +[ ] +``` + + + +*Example:* + +```nix +[ + { + uuidFile = "/run/secrets/proxy-inbound-uuid"; + } +] +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.name + + + +Optional label for this account\. Used as the share-link fragment so +clients show a readable server name, and as the XRay user email\. + + + +*Type:* +string + + + +*Default:* + +```nix +"" +``` + + + +*Example:* + +```nix +"phone" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.password + + + +Literal password for trojan, shadowsocks, socks, and http listeners\. + +This value is embedded in the Nix store\. Prefer passwordFile for real +credentials\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"hunter2" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.passwordFile + + + +Runtime path to a file containing the account password\. +The file is read at service start time and never lands in the Nix store\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"/run/secrets/proxy-inbound-password" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.uuid + + + +Literal UUID for vless/vmess accounts\. + +This value is embedded in the Nix store\. Prefer uuidFile for real +credentials\. + +Set exactly one of uuid or uuidFile for vless and vmess listeners\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"b831381d-6324-4d53-ad4f-8cda48b30811" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.users\.\*\.uuidFile + + + +Runtime path to a file containing the account UUID\. +Intended for use with secret managers (sops-nix, agenix, etc\.)\. +The file is read at service start time and never lands in the Nix store\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"/run/secrets/proxy-inbound-uuid" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.via + + + +Egress for traffic arriving on this listener: “proxy” (out through +the local proxy stack, following its current selection), a +proxy\.outbounds tag (pinned to that specific server), “direct” (out +from this machine), or “block”\. + +Give two listeners two different tags to have them leave through two +different servers\. + +Leave null to inherit proxyInbounds\.via\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"nl-vps" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.listeners\.\\.xrayJson + + + +Raw XRay inbound configuration as a Nix attribute set, for protocols +or options the typed fields do not cover\. Embedded into the config at +build time, so avoid putting credentials here; use jsonFile instead\. +The tag field is overridden by the listener name\. + +Set exactly one of type, xrayJson, or jsonFile for each listener\. + + + +*Type:* +null or (attribute set) + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +{ + protocol = "dokodemo-door"; + settings = { + address = "127.0.0.1"; + port = 8080; + }; +} +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.openFirewall + + + +Add every listener port to networking\.firewall\. Disable to manage the +firewall yourself\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +true +``` + + + +*Example:* + +```nix +false +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.serverAddress + + + +Public hostname or address clients connect to\. Used for generated share +links only; it does not affect what the listeners bind\. + +Leave null to detect the machine’s uplink IPv4 address at service start +time\. Set it explicitly when the server is behind NAT or reached by a +domain name\. + + + +*Type:* +null or string matching the pattern \[^\[:space:]]+ + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"vpn.example.com" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.shareLinks + + + +Write client share links to /run/proxy-suite-inbounds/links\.json at +service start, for ` proxy-ctl inbounds link ` and +` proxy-ctl inbounds qr `\. + +The file is readable by root and the userControl group only, because +the links carry the listener credentials\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +true +``` + + + +*Example:* + +```nix +false +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.via + + + +Default egress for traffic arriving on the inbounds\. Individual +listeners can override it with their own via option, which is how two +listeners can leave through two different servers\. + + - “proxy”: chain out through the local proxy stack, so the machine + relays rather than exits\. Requires proxy\.enable\. The inbound service + hands traffic to the SOCKS listener on proxy\.listenAddress, so it + follows whatever the client side is currently doing: the selected + outbound, subscriptions, urltest, and ` proxy-ctl select ` all apply, + with no second copy of that machinery\. + - A proxy\.outbounds tag: pin this traffic to that specific server, + independently of what the client side has selected\. The outbound is + built into the inbound service’s own config, so it must be one XRay + can represent (a url/urlFile entry, or xrayJson)\. Subscription + proxies cannot be named here, because their tags only exist at + runtime; use “proxy” to reach those\. + - “direct”: leave from this machine, making it a plain exit node\. Needs + no client-side proxy configuration at all\. + - “block”: drop the traffic\. + + + +*Type:* +string + + + +*Default:* + +```nix +"proxy" +``` + + + +*Example:* + +```nix +"direct" +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + + +## services\.proxy-suite\.proxyInbounds\.zapretDirect + + + +Route zapret’s hostlist domains and IPs to the direct outbound instead +of through the proxy, so this host’s own zapret unblocks them for +inbound clients\. + +Has no effect unless zapret\.enable and zapret\.syncDirectRouting are on: +the rules are built from the same hostlists that already feed +routing\.direct on the client side, so they are empty when zapret is not +running here\. + +On by default because a zapret host is by definition inside the filtered +network, and paying for a proxy hop to reach something zapret already +unblocks locally is pure latency\. Only applies to listeners using the +default via; an explicit per-listener via still wins\. + + + +*Type:* +boolean + + + +*Default:* + +```nix +true +``` + + + +*Example:* + +```nix +false +``` + +*Declared by:* + - [modules/proxy-suite/options/proxy-inbounds\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/proxy-inbounds.nix) + + + ## services\.proxy-suite\.sshProxy\.enable @@ -5609,9 +7222,15 @@ true -Add the local SSH SOCKS5 listener as a proxy-suite outbound tagged -“ssh-proxy”\. Requires proxy\.enable and an active SingBox or XRay -backend\. +Add the SSH tunnel as a proxy-suite outbound tagged “ssh-proxy”\. +Requires proxy\.enable and an active SingBox or XRay backend\. + +How the tunnel is built depends on the backend\. SingBox and hybrid +backends dial SSH natively, with no systemd unit and no local SOCKS5 +listener\. XRay has no SSH outbound, so it keeps the OpenSSH ` ssh -D ` +unit and proxies through its local SOCKS5 listener\. With +asOutbound = false the OpenSSH unit is always used, since the tunnel is +then a standalone listener the backends know nothing about\. @@ -5639,6 +7258,52 @@ true + +## services\.proxy-suite\.sshProxy\.domainStrategy + + + +Resolve destination domains locally before sending them through the +SSH SOCKS5 proxy, so the remote SSH server never has to resolve them\. +Null preserves the backend’s default behavior\. + +Only applies to the XRay backend, which reaches the tunnel through the +local SOCKS5 listener and maps this onto the outbound’s +` sockopt.domainStrategy `\. SingBox and hybrid backends dial SSH natively +and resolve destinations themselves, so this option is ignored there\. + +Note that local resolution hands the remote server an address chosen by +*this* machine’s DNS\. For anycast or geo-steered CDNs that address can +be unreachable from the remote network, which surfaces as connection +timeouts rather than as a DNS error\. Prefer fixing DNS on the remote +server if you have access to it\. + + + +*Type:* +null or one of “prefer_ipv4”, “prefer_ipv6”, “ipv4_only”, “ipv6_only” + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"prefer_ipv4" +``` + +*Declared by:* + - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) + + + ## services\.proxy-suite\.sshProxy\.extraArgs @@ -5647,6 +7312,10 @@ true Additional arguments passed to OpenSSH before the destination\. This can be used for options such as jump hosts or agent forwarding\. +OpenSSH path only: ignored when a SingBox or hybrid backend dials SSH +natively\. Keepalive, connect-timeout and restart behavior are already +set by the module, so they do not need to be repeated here\. + *Type:* @@ -5709,6 +7378,99 @@ null + +## services\.proxy-suite\.sshProxy\.hostKey + + + +Accepted SSH host public keys, in ` authorized_keys ` one-line form\. +Used by the sing-box backend, which verifies host keys by value rather +than against a known-hosts file\. + +List **every** key the server offers, not just one\. The host key +algorithm is negotiated, so pinning a single key fails the handshake +outright whenever the server picks a different algorithm\. Get the full +set with ` ssh-keyscan -p PORT HOST `, or from an existing known-hosts +entry with ` ssh-keygen -F '[HOST]:PORT' `\. + +Leaving this empty accepts **any** host key, which allows a +machine-in-the-middle on the tunnel\. Set it whenever sshProxy\.asOutbound +is used with a SingBox or hybrid backend\. + +Ignored by the XRay backend and by a standalone tunnel, which use +knownHostsFile and strictHostKeyChecking instead\. + + + +*Type:* +list of string + + + +*Default:* + +```nix +[ ] +``` + + + +*Example:* + +```nix +[ + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." +] +``` + +*Declared by:* + - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) + + + + +## services\.proxy-suite\.sshProxy\.hostKeyFile + + + +Runtime path to a known-hosts file to read the accepted host keys from, +instead of listing them inline in sshProxy\.hostKey\. Every key recorded +there for ` host:sshPort ` is accepted, so a single known-hosts file stays +the one source of truth\. Hashed known-hosts files work\. + +Read when the service starts, not at evaluation time, so the file never +enters the Nix store\. Set either this or sshProxy\.hostKey; if both are +set the file wins\. + +Used by the sing-box backend\. The XRay backend and a standalone tunnel +pass knownHostsFile to OpenSSH instead\. + + + +*Type:* +null or string + + + +*Default:* + +```nix +null +``` + + + +*Example:* + +```nix +"/root/.ssh/known_hosts" +``` + +*Declared by:* + - [modules/proxy-suite/options/ssh-proxy\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/ssh-proxy.nix) + + + ## services\.proxy-suite\.sshProxy\.identityFile @@ -5750,6 +7512,9 @@ null Optional runtime path to the known-hosts file passed to OpenSSH\. +OpenSSH path only\. A SingBox or hybrid backend verifies host keys with +sshProxy\.hostKey instead\. + *Type:* @@ -5783,6 +7548,9 @@ null Local address for the SSH-created SOCKS5 listener\. +OpenSSH path only: a SingBox or hybrid backend dials SSH natively and +creates no local listener\. + *Type:* @@ -5816,6 +7584,9 @@ string matching the pattern \[^\[:space:]]+ Local port for the SSH-created SOCKS5 listener\. +OpenSSH path only: a SingBox or hybrid backend dials SSH natively and +creates no local listener\. + *Type:* @@ -5850,6 +7621,9 @@ Local port for the SSH-created SOCKS5 listener\. Unix user for the systemd SSH proxy service\. Leave unset to use systemd’s default user\. +OpenSSH path only: ignored when a SingBox or hybrid backend dials SSH +natively and no separate unit is created\. + *Type:* @@ -5917,6 +7691,9 @@ Remote SSH server port\. OpenSSH host-key verification policy\. Use “yes” with pinned knownHostsFile contents for strict verification\. +OpenSSH path only\. A SingBox or hybrid backend verifies host keys with +sshProxy\.hostKey instead\. + *Type:* @@ -7501,6 +9278,8 @@ list of string ## services\.proxy-suite\.zapret\.ipsetExclude + + IPs/CIDRs to exclude from zapret’s ipset\. Also excluded from zapret-derived proxy direct IP routing when syncDirectRoutingUserIps = true\. diff --git a/modules/proxy-suite/config-templates/proxy-inbounds.nix b/modules/proxy-suite/config-templates/proxy-inbounds.nix new file mode 100644 index 0000000..e5dc58c --- /dev/null +++ b/modules/proxy-suite/config-templates/proxy-inbounds.nix @@ -0,0 +1,71 @@ +# Build-time XRay configuration template for the server-side inbound service. +# Inbounds and proxy outbounds are both injected at service start time, so no +# credential reaches the Nix store. +{ + lib, + derived, + inboundRules, + mkDnsServer, +}: + +let + inherit (derived) proxyCfg proxyInboundsCfg proxyInboundsNeedLocalProxy; + + # Relaying goes through the client stack's SOCKS listener rather than a second + # copy of the outbound machinery, so the inbound service always follows the + # currently selected outbound. Connect over loopback when the listener is on a + # wildcard address. + localProxyAddress = + if builtins.elem proxyCfg.listenAddress [ + "0.0.0.0" + "::" + "" + ] then + "127.0.0.1" + else + proxyCfg.listenAddress; + + # Credentials, when the local proxy has them, are injected at start time. + localProxyOutbound = lib.optional proxyInboundsNeedLocalProxy { + protocol = "socks"; + tag = "proxy"; + settings = { + servers = [ + { + address = localProxyAddress; + port = proxyCfg.port; + } + ]; + }; + }; +in +{ + log.loglevel = "warning"; + + dns.servers = [ + (mkDnsServer "remote" proxyCfg.dns.remote) + (mkDnsServer "local" proxyCfg.dns.local) + ]; + + # Filled in at start time from the listener spec. + inbounds = [ ]; + + outbounds = localProxyOutbound ++ [ + { + protocol = "freedom"; + tag = "direct"; + settings = { }; + } + { + protocol = "blackhole"; + tag = "block"; + settings = { }; + } + ]; + + routing = { + domainStrategy = "IPIfNonMatch"; + domainMatcher = "hybrid"; + rules = inboundRules.xrayInboundRules; + }; +} diff --git a/modules/proxy-suite/config-templates/xray.nix b/modules/proxy-suite/config-templates/xray.nix index 600835b..00970a8 100644 --- a/modules/proxy-suite/config-templates/xray.nix +++ b/modules/proxy-suite/config-templates/xray.nix @@ -256,6 +256,10 @@ let // lib.optionalAttrs enableTunFakeDns { fakedns = fakeDnsPools; }; in { + # Reused by the server-side inbound template, which builds a different config + # shape out of the same backend primitives. + inherit mkDnsServer; + tproxy = mkConfig { enableMixed = true; enableTProxy = true; diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 095ffc8..3ee7b76 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -24,6 +24,41 @@ let ; }; + inboundRules = import ./rules/proxy-inbounds.nix { + inherit lib; + inherit (derived) proxyInboundsCfg proxyInbounds; + inherit (rules) zapretDirectRules; + }; + + proxyInboundsTemplate = import ./config-templates/proxy-inbounds.nix { + inherit lib derived inboundRules; + inherit (xrayTemplates) mkDnsServer; + }; + + # Listener specification handed to build-inbound.py at service start. Secrets + # appear here only as paths; the script reads them at runtime. + proxyInboundsSpec = { + serverAddress = derived.proxyInboundsCfg.serverAddress; + shareLinks = derived.proxyInboundsCfg.shareLinks; + listeners = map (ib: { + inherit (ib) tag; + inherit (ib.listener) + type + port + sharePort + users + flow + method + transport + tls + reality + xrayJson + jsonFile + ; + listen = ib.listener.listenAddress; + }) derived.proxyInbounds; + }; + selectedTemplates = if derived.pureXrayEnabled then xrayTemplates else singBoxTemplates; routeModeRules = if derived.pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules; @@ -40,6 +75,12 @@ let routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" ( builtins.toJSON routeModeRules ); + proxyInboundsFile = pkgs.writeText "proxy-suite-inbounds-template.json" ( + builtins.toJSON proxyInboundsTemplate + ); + proxyInboundsSpecFile = pkgs.writeText "proxy-suite-inbounds-spec.json" ( + builtins.toJSON proxyInboundsSpec + ); in { inherit @@ -47,5 +88,7 @@ in tunFile perAppTunFile routeModeRulesFile + proxyInboundsFile + proxyInboundsSpecFile ; } diff --git a/modules/proxy-suite/default.nix b/modules/proxy-suite/default.nix index d980360..a99afe0 100644 --- a/modules/proxy-suite/default.nix +++ b/modules/proxy-suite/default.nix @@ -13,6 +13,7 @@ let cfg = config.services.proxy-suite; packages = import ../../pkgs/default.nix { inherit pkgs; }; nftr = import ./nftables.nix { inherit lib pkgs cfg; }; + derived = import ./derived.nix { inherit lib cfg; }; in { imports = [ @@ -52,6 +53,8 @@ in tunFile perAppTunFile routeModeRulesFile + proxyInboundsFile + proxyInboundsSpecFile ; inherit (nftr) nftablesRulesFile @@ -86,7 +89,9 @@ in } )) - (lib.mkIf cfg.sshProxy.enable ( + # SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH + # outbound, and a standalone tunnel has no backend at all, so both keep it. + (lib.mkIf derived.sshProxyUnitEnabled ( import ./ssh-proxy.nix { inherit lib diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index a1f7693..b0db7fb 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -39,6 +39,61 @@ let sshProxyCfg = cfg.sshProxy; sshProxyOutboundTag = "ssh-proxy"; sshProxyOutboundEnabled = sshProxyCfg.enable && sshProxyCfg.asOutbound; + # Only sing-box has a native `ssh` outbound. XRay has none, so it keeps the + # OpenSSH `ssh -D` unit and its local SOCKS listener -- as does a standalone + # tunnel that is not wired in as an outbound at all. + sshProxyNativeOutbound = sshProxyOutboundEnabled && !pureXrayEnabled; + sshProxyUnitEnabled = sshProxyCfg.enable && !sshProxyNativeOutbound; + + proxyInboundsCfg = cfg.proxyInbounds; + proxyInboundsEnabled = proxyInboundsCfg.enable; + + # Listener attrset flattened to a list with `via` resolved against the + # tree-wide default. Everything downstream (rules, spec, firewall) uses this. + proxyInbounds = lib.mapAttrsToList (tag: listener: { + inherit tag listener; + via = if listener.via == null then proxyInboundsCfg.via else listener.via; + }) proxyInboundsCfg.listeners; + + # "direct" and "block" are self-contained; "proxy" chains through the client + # stack's local SOCKS listener, so it needs the client side to be running. + proxyInboundsNeedLocalProxy = lib.any (ib: ib.via == "proxy") proxyInbounds; + + # Any other via names a static outbound, which is rendered into the inbound + # service's own config so it stays pinned regardless of the client's + # selection. Only referenced outbounds are built, so an unused (or + # sing-box-only) one never has to be XRay-representable. + proxyInboundViaTags = lib.unique ( + builtins.filter (via: !builtins.elem via builtinTags) (map (ib: ib.via) proxyInbounds) + ); + proxyInboundViaOutbounds = builtins.filter ( + ob: builtins.elem ob.tag proxyInboundViaTags + ) proxyCfg.outbounds; + + proxyInboundUdpTypes = [ + "shadowsocks" + "socks" + ]; + proxyInboundPorts = lib.unique (map (ib: ib.listener.port) proxyInbounds); + # A loopback-bound listener is reached through something else on this host (an + # nginx vhost, say), so opening its port would expose the endpoint that + # arrangement exists to hide. + proxyInboundsPublic = builtins.filter ( + ib: + !builtins.elem ib.listener.listenAddress [ + "127.0.0.1" + "::1" + ] + ) proxyInbounds; + proxyInboundFirewallPorts = lib.unique (map (ib: ib.listener.port) proxyInboundsPublic); + # A raw-JSON listener could serve anything, so open both protocols for it. + proxyInboundFirewallUdpPorts = lib.unique ( + map (ib: ib.listener.port) ( + builtins.filter ( + ib: ib.listener.type == null || builtins.elem ib.listener.type proxyInboundUdpTypes + ) proxyInboundsPublic + ) + ); selectionMode = proxyCfg.selection; builtinTags = [ @@ -81,6 +136,9 @@ let }; }; + # Subscription tags are deliberately not accepted: they only exist at runtime. + invalidInboundViaTargets = builtins.filter (tag: !builtins.elem tag outboundTags) proxyInboundViaTags; + invalidRoutingTargets = lib.unique ( map (rule: rule.outbound) ( builtins.filter ( @@ -113,6 +171,18 @@ in sshProxyCfg sshProxyOutboundTag sshProxyOutboundEnabled + sshProxyNativeOutbound + sshProxyUnitEnabled + proxyInboundsCfg + proxyInboundsEnabled + proxyInbounds + proxyInboundsNeedLocalProxy + proxyInboundViaTags + proxyInboundViaOutbounds + invalidInboundViaTargets + proxyInboundPorts + proxyInboundFirewallPorts + proxyInboundFirewallUdpPorts constants selectionMode builtinTags diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index 53a21f7..a8e30b2 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -4,6 +4,7 @@ imports = [ ./other.nix ./ssh-proxy.nix + ./proxy-inbounds.nix ./amnezia-wg.nix ./legacy-sing-box.nix ./sing-box.nix diff --git a/modules/proxy-suite/options/proxy-inbounds.nix b/modules/proxy-suite/options/proxy-inbounds.nix new file mode 100644 index 0000000..c5e1fc9 --- /dev/null +++ b/modules/proxy-suite/options/proxy-inbounds.nix @@ -0,0 +1,172 @@ +# Server-side proxy inbound options. +{ lib, pkgs, ... }: + +let + inherit (lib) + literalExpression + mkEnableOption + mkOption + types + ; + inboundTypes = import ./types/proxy-inbounds.nix { inherit lib; }; +in +{ + options.services.proxy-suite.proxyInbounds = { + enable = mkEnableOption "server-side proxy inbounds (accept connections from outside)"; + + package = mkOption { + type = types.package; + default = pkgs.xray; + defaultText = literalExpression "pkgs.xray"; + example = literalExpression "pkgs.xray"; + description = '' + XRay package serving the inbounds. + + This is independent of proxy.xray.package: the inbound service always + runs XRay, whichever backend the client side uses, and works with + proxy.enable = false. + ''; + }; + + serverAddress = mkOption { + type = types.nullOr (types.strMatching "[^[:space:]]+"); + default = null; + description = '' + Public hostname or address clients connect to. Used for generated share + links only; it does not affect what the listeners bind. + + Leave null to detect the machine's uplink IPv4 address at service start + time. Set it explicitly when the server is behind NAT or reached by a + domain name. + ''; + example = "vpn.example.com"; + }; + + openFirewall = mkOption { + type = types.bool; + default = true; + description = '' + Add every listener port to networking.firewall. Disable to manage the + firewall yourself. + ''; + example = false; + }; + + shareLinks = mkOption { + type = types.bool; + default = true; + description = '' + Write client share links to /run/proxy-suite-inbounds/links.json at + service start, for `proxy-ctl inbounds link` and + `proxy-ctl inbounds qr`. + + The file is readable by root and the userControl group only, because + the links carry the listener credentials. + ''; + example = false; + }; + + via = mkOption { + type = types.str; + default = "proxy"; + description = '' + Default egress for traffic arriving on the inbounds. Individual + listeners can override it with their own via option, which is how two + listeners can leave through two different servers. + + - "proxy": chain out through the local proxy stack, so the machine + relays rather than exits. Requires proxy.enable. The inbound service + hands traffic to the SOCKS listener on proxy.listenAddress, so it + follows whatever the client side is currently doing: the selected + outbound, subscriptions, urltest, and `proxy-ctl select` all apply, + with no second copy of that machinery. + - A proxy.outbounds tag: pin this traffic to that specific server, + independently of what the client side has selected. The outbound is + built into the inbound service's own config, so it must be one XRay + can represent (a url/urlFile entry, or xrayJson). Subscription + proxies cannot be named here, because their tags only exist at + runtime; use "proxy" to reach those. + - "direct": leave from this machine, making it a plain exit node. Needs + no client-side proxy configuration at all. + - "block": drop the traffic. + ''; + example = "direct"; + }; + + zapretDirect = mkOption { + type = types.bool; + default = true; + description = '' + Route zapret's hostlist domains and IPs to the direct outbound instead + of through the proxy, so this host's own zapret unblocks them for + inbound clients. + + Has no effect unless zapret.enable and zapret.syncDirectRouting are on: + the rules are built from the same hostlists that already feed + routing.direct on the client side, so they are empty when zapret is not + running here. + + On by default because a zapret host is by definition inside the filtered + network, and paying for a proxy hop to reach something zapret already + unblocks locally is pure latency. Only applies to listeners using the + default via; an explicit per-listener via still wins. + ''; + example = false; + }; + + blockRu = mkOption { + type = types.bool; + default = true; + description = '' + Send traffic destined for Russian domains and IP ranges + ("category-ru" geosite, "ru" geoip) to the block outbound. + + On by default: a relay whose whole point is leaving the RKN-filtered + network has no reason to carry traffic back into it, and it keeps the + server out of the way of domestic services that geo-check. + ''; + example = false; + }; + + blockPrivate = mkOption { + type = types.bool; + default = true; + description = '' + Send traffic destined for private and loopback addresses to the block + outbound. + + On by default: without it, anyone holding an inbound credential can + reach the server's LAN, its localhost services, and the local proxy + ports of proxy-suite itself. + ''; + example = false; + }; + + listeners = mkOption { + type = types.attrsOf inboundTypes.inboundType; + default = { }; + description = '' + Named inbound listeners. The attribute name becomes the inbound tag + used in routing rules and in `proxy-ctl inbounds`. + ''; + example = literalExpression '' + { + vless-reality = { + type = "vless"; + port = 443; + users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]; + flow = "xtls-rprx-vision"; + reality = { + enable = true; + dest = "www.microsoft.com:443"; + serverNames = [ "www.microsoft.com" ]; + privateKeyFile = "/run/secrets/proxy-inbound-reality-key"; + publicKey = "jNXH..."; + shortIds = [ "0123abcd" ]; + }; + }; + } + ''; + }; + }; +} diff --git a/modules/proxy-suite/options/ssh-proxy.nix b/modules/proxy-suite/options/ssh-proxy.nix index 33c12a7..93e409b 100644 --- a/modules/proxy-suite/options/ssh-proxy.nix +++ b/modules/proxy-suite/options/ssh-proxy.nix @@ -23,6 +23,9 @@ in description = '' Unix user for the systemd SSH proxy service. Leave unset to use systemd's default user. + + OpenSSH path only: ignored when a SingBox or hybrid backend dials SSH + natively and no separate unit is created. ''; example = "proxy"; }; @@ -46,14 +49,24 @@ in listenAddress = mkOption { type = types.strMatching "[^[:space:]]+"; default = "127.0.0.1"; - description = "Local address for the SSH-created SOCKS5 listener."; + description = '' + Local address for the SSH-created SOCKS5 listener. + + OpenSSH path only: a SingBox or hybrid backend dials SSH natively and + creates no local listener. + ''; example = "127.0.0.1"; }; listenPort = mkOption { type = types.port; default = 1091; - description = "Local port for the SSH-created SOCKS5 listener."; + description = '' + Local port for the SSH-created SOCKS5 listener. + + OpenSSH path only: a SingBox or hybrid backend dials SSH natively and + creates no local listener. + ''; example = 1091; }; @@ -72,10 +85,85 @@ in default = null; description = '' Optional runtime path to the known-hosts file passed to OpenSSH. + + OpenSSH path only. A SingBox or hybrid backend verifies host keys with + sshProxy.hostKey instead. ''; example = "/run/secrets/proxy-suite-ssh-known-hosts"; }; + hostKey = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + Accepted SSH host public keys, in `authorized_keys` one-line form. + Used by the sing-box backend, which verifies host keys by value rather + than against a known-hosts file. + + List **every** key the server offers, not just one. The host key + algorithm is negotiated, so pinning a single key fails the handshake + outright whenever the server picks a different algorithm. Get the full + set with `ssh-keyscan -p PORT HOST`, or from an existing known-hosts + entry with `ssh-keygen -F '[HOST]:PORT'`. + + Leaving this empty accepts **any** host key, which allows a + machine-in-the-middle on the tunnel. Set it whenever sshProxy.asOutbound + is used with a SingBox or hybrid backend. + + Ignored by the XRay backend and by a standalone tunnel, which use + knownHostsFile and strictHostKeyChecking instead. + ''; + example = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." ]; + }; + + hostKeyFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to a known-hosts file to read the accepted host keys from, + instead of listing them inline in sshProxy.hostKey. Every key recorded + there for `host:sshPort` is accepted, so a single known-hosts file stays + the one source of truth. Hashed known-hosts files work. + + Read when the service starts, not at evaluation time, so the file never + enters the Nix store. Set either this or sshProxy.hostKey; if both are + set the file wins. + + Used by the sing-box backend. The XRay backend and a standalone tunnel + pass knownHostsFile to OpenSSH instead. + ''; + example = "/root/.ssh/known_hosts"; + }; + + domainStrategy = mkOption { + type = types.nullOr ( + types.enum [ + "prefer_ipv4" + "prefer_ipv6" + "ipv4_only" + "ipv6_only" + ] + ); + default = null; + description = '' + Resolve destination domains locally before sending them through the + SSH SOCKS5 proxy, so the remote SSH server never has to resolve them. + Null preserves the backend's default behavior. + + Only applies to the XRay backend, which reaches the tunnel through the + local SOCKS5 listener and maps this onto the outbound's + `sockopt.domainStrategy`. SingBox and hybrid backends dial SSH natively + and resolve destinations themselves, so this option is ignored there. + + Note that local resolution hands the remote server an address chosen by + *this* machine's DNS. For anycast or geo-steered CDNs that address can + be unreachable from the remote network, which surfaces as connection + timeouts rather than as a DNS error. Prefer fixing DNS on the remote + server if you have access to it. + ''; + example = "prefer_ipv4"; + }; + strictHostKeyChecking = mkOption { type = types.enum [ "yes" @@ -86,6 +174,9 @@ in description = '' OpenSSH host-key verification policy. Use "yes" with pinned knownHostsFile contents for strict verification. + + OpenSSH path only. A SingBox or hybrid backend verifies host keys with + sshProxy.hostKey instead. ''; example = "yes"; }; @@ -96,6 +187,10 @@ in description = '' Additional arguments passed to OpenSSH before the destination. This can be used for options such as jump hosts or agent forwarding. + + OpenSSH path only: ignored when a SingBox or hybrid backend dials SSH + natively. Keepalive, connect-timeout and restart behavior are already + set by the module, so they do not need to be repeated here. ''; example = [ "-o" @@ -107,9 +202,15 @@ in type = types.bool; default = false; description = '' - Add the local SSH SOCKS5 listener as a proxy-suite outbound tagged - "ssh-proxy". Requires proxy.enable and an active SingBox or XRay - backend. + Add the SSH tunnel as a proxy-suite outbound tagged "ssh-proxy". + Requires proxy.enable and an active SingBox or XRay backend. + + How the tunnel is built depends on the backend. SingBox and hybrid + backends dial SSH natively, with no systemd unit and no local SOCKS5 + listener. XRay has no SSH outbound, so it keeps the OpenSSH `ssh -D` + unit and proxies through its local SOCKS5 listener. With + asOutbound = false the OpenSSH unit is always used, since the tunnel is + then a standalone listener the backends know nothing about. ''; example = true; }; diff --git a/modules/proxy-suite/options/types/proxy-inbounds.nix b/modules/proxy-suite/options/types/proxy-inbounds.nix new file mode 100644 index 0000000..adcb9f5 --- /dev/null +++ b/modules/proxy-suite/options/types/proxy-inbounds.nix @@ -0,0 +1,432 @@ +# Server-side inbound listener option type definitions. +{ lib }: + +let + inherit (lib) mkOption types; + + userType = types.submodule { + options = { + name = mkOption { + type = types.str; + default = ""; + description = '' + Optional label for this account. Used as the share-link fragment so + clients show a readable server name, and as the XRay user email. + ''; + example = "phone"; + }; + + uuid = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Literal UUID for vless/vmess accounts. + + This value is embedded in the Nix store. Prefer uuidFile for real + credentials. + + Set exactly one of uuid or uuidFile for vless and vmess listeners. + ''; + example = "b831381d-6324-4d53-ad4f-8cda48b30811"; + }; + + uuidFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to a file containing the account UUID. + Intended for use with secret managers (sops-nix, agenix, etc.). + The file is read at service start time and never lands in the Nix store. + ''; + example = "/run/secrets/proxy-inbound-uuid"; + }; + + password = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Literal password for trojan, shadowsocks, socks, and http listeners. + + This value is embedded in the Nix store. Prefer passwordFile for real + credentials. + ''; + example = "hunter2"; + }; + + passwordFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to a file containing the account password. + The file is read at service start time and never lands in the Nix store. + ''; + example = "/run/secrets/proxy-inbound-password"; + }; + }; + }; + + transportType = types.submodule { + options = { + type = mkOption { + type = types.enum [ + "raw" + "ws" + "grpc" + "httpupgrade" + "xhttp" + ]; + default = "raw"; + description = '' + Stream transport for this listener. "raw" is plain TCP and is what + REALITY setups normally use. + ''; + example = "ws"; + }; + + path = mkOption { + type = types.str; + default = "/"; + description = '' + Request path for the "ws", "httpupgrade", and "xhttp" transports. + Ignored by the other transports. + ''; + example = "/download"; + }; + + host = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Expected Host header for the "ws", "httpupgrade", and "xhttp" + transports. Leave null to accept any host. + ''; + example = "cdn.example.com"; + }; + + mode = mkOption { + type = types.nullOr ( + types.enum [ + "auto" + "packet-up" + "stream-up" + "stream-one" + ] + ); + default = null; + description = '' + Transfer mode for the "xhttp" transport. Ignored by the others. + + Leave null for XRay's own default, which lets the client choose. + Behind an HTTP/1.1 reverse proxy, "packet-up" is the mode that works: + "stream-one" needs a full-duplex HTTP/2 path from the client all the + way to the listener, which a proxy speaking HTTP/1.1 upstream cannot + provide. + ''; + example = "packet-up"; + }; + + serviceName = mkOption { + type = types.str; + default = ""; + description = '' + gRPC service name for the "grpc" transport. Ignored otherwise. + ''; + example = "GunService"; + }; + }; + }; + + tlsType = types.submodule { + options = { + enable = mkOption { + type = types.bool; + default = false; + description = '' + Terminate TLS on this listener. Mutually exclusive with reality. + + Always on for trojan listeners regardless of this setting. + ''; + example = true; + }; + + certificateFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to the PEM certificate chain. Compose with + security.acme to keep it renewed. + ''; + example = "/var/lib/acme/example.com/fullchain.pem"; + }; + + keyFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to the PEM private key matching certificateFile. + ''; + example = "/var/lib/acme/example.com/key.pem"; + }; + + serverName = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + SNI advertised in generated share links. Defaults to + proxyInbounds.serverAddress when unset. + ''; + example = "example.com"; + }; + }; + }; + + realityType = types.submodule { + options = { + enable = mkOption { + type = types.bool; + default = false; + description = '' + Enable REALITY on this listener. Mutually exclusive with tls.enable. + ''; + example = true; + }; + + dest = mkOption { + type = types.str; + default = "www.microsoft.com:443"; + description = '' + Real TLS server that unauthenticated probes are proxied to. Must be a + host:port that serves TLS 1.3 with HTTP/2. + ''; + example = "www.microsoft.com:443"; + }; + + serverNames = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + SNI values accepted by this listener. These must be names the dest + server actually serves. The first entry is used in share links. + ''; + example = [ "www.microsoft.com" ]; + }; + + privateKeyFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to the REALITY x25519 private key, as produced by + `xray x25519`. Read at service start time; never lands in the Nix + store. + ''; + example = "/run/secrets/proxy-inbound-reality-key"; + }; + + privateKey = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Literal REALITY x25519 private key. + + This value is embedded in the Nix store. Prefer privateKeyFile. + ''; + example = "gG1Yz..."; + }; + + publicKey = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + REALITY x25519 public key matching privateKeyFile, as printed + alongside it by `xray x25519`. Not a secret: clients need it, and it + is what generated share links carry as `pbk`. + + Required when proxyInbounds.shareLinks is enabled. + ''; + example = "jNXH..."; + }; + + shortIds = mkOption { + type = types.listOf types.str; + default = [ "" ]; + description = '' + Accepted REALITY short IDs (hex, up to 16 characters). The default + accepts the empty short ID. The first entry is used in share links. + ''; + example = [ "0123abcd" ]; + }; + }; + }; + + inboundType = types.submodule { + options = { + type = mkOption { + type = types.nullOr (types.enum [ + "vless" + "vmess" + "trojan" + "shadowsocks" + "socks" + "http" + ]); + default = null; + description = '' + Proxy protocol served by this listener. + + Set exactly one of type, xrayJson, or jsonFile for each listener. + ''; + example = "vless"; + }; + + port = mkOption { + type = types.port; + default = 443; + description = '' + Port this listener binds. Opened in the firewall automatically unless + proxyInbounds.openFirewall is disabled. + ''; + example = 443; + }; + + sharePort = mkOption { + type = types.nullOr types.port; + default = null; + description = '' + Port generated share links advertise, for when clients do not reach + this listener on the port it binds. Set it when something in front of + it owns the public port: an nginx vhost proxying to a loopback bind, + a container port mapping, a DNAT rule. + + Leave null to advertise port. + ''; + example = 443; + }; + + listenAddress = mkOption { + type = types.strMatching "[^[:space:]]+"; + default = "::"; + description = '' + Address this listener binds. The default accepts both IPv4 and IPv6 + connections from anywhere. + ''; + example = "0.0.0.0"; + }; + + via = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Egress for traffic arriving on this listener: "proxy" (out through + the local proxy stack, following its current selection), a + proxy.outbounds tag (pinned to that specific server), "direct" (out + from this machine), or "block". + + Give two listeners two different tags to have them leave through two + different servers. + + Leave null to inherit proxyInbounds.via. + ''; + example = "nl-vps"; + }; + + users = mkOption { + type = types.listOf userType; + default = [ ]; + description = '' + Accounts accepted by this listener. vless and vmess use uuid/uuidFile; + trojan, shadowsocks, socks, and http use password/passwordFile. + + A share link is generated for the first user of each listener. + ''; + example = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]; + }; + + flow = mkOption { + type = types.nullOr (types.enum [ "xtls-rprx-vision" ]); + default = null; + description = '' + VLESS flow control. "xtls-rprx-vision" is the usual pairing with + REALITY on the "raw" transport; it is not valid over ws, grpc, + httpupgrade, or xhttp. + ''; + example = "xtls-rprx-vision"; + }; + + method = mkOption { + type = types.str; + default = "2022-blake3-aes-128-gcm"; + description = '' + Shadowsocks cipher. Ignored by other protocols. + + The 2022 ciphers require a base64 pre-shared key of the matching + length as the password, not a passphrase. + ''; + example = "aes-128-gcm"; + }; + + transport = mkOption { + type = transportType; + default = { }; + description = '' + Stream transport settings for this listener. + ''; + }; + + tls = mkOption { + type = tlsType; + default = { }; + description = '' + TLS termination settings for this listener. Mutually exclusive with + reality. + ''; + }; + + reality = mkOption { + type = realityType; + default = { }; + description = '' + REALITY settings for this listener. Mutually exclusive with tls. + ''; + }; + + xrayJson = mkOption { + type = types.nullOr types.attrs; + default = null; + description = '' + Raw XRay inbound configuration as a Nix attribute set, for protocols + or options the typed fields do not cover. Embedded into the config at + build time, so avoid putting credentials here; use jsonFile instead. + The tag field is overridden by the listener name. + + Set exactly one of type, xrayJson, or jsonFile for each listener. + ''; + example = { + protocol = "dokodemo-door"; + settings = { + address = "127.0.0.1"; + port = 8080; + }; + }; + }; + + jsonFile = mkOption { + type = types.nullOr types.str; + default = null; + description = '' + Runtime path to a file containing a complete XRay inbound object as + JSON. Read at service start time, so the whole inbound including its + credentials can be rendered by a secret manager and never lands in + the Nix store. The tag field is overridden by the listener name. + + No share link is generated for listeners defined this way. + + Set exactly one of type, xrayJson, or jsonFile for each listener. + ''; + example = "/run/secrets/proxy-inbound-vless.json"; + }; + }; + }; +in +{ + inherit inboundType; +} diff --git a/modules/proxy-suite/rules-zapret-direct.nix b/modules/proxy-suite/rules-zapret-direct.nix index 86b26f8..4d71008 100644 --- a/modules/proxy-suite/rules-zapret-direct.nix +++ b/modules/proxy-suite/rules-zapret-direct.nix @@ -103,6 +103,14 @@ let [ ]; in { + # The zapret-derived portion on its own. proxyInbounds routes these to the + # direct outbound so the host's own zapret handles the DPI bypass for inbound + # clients, instead of paying for a proxy hop it does not need. + zapretDirect = { + domains = zapretDirectDomains; + ips = zapretDirectIps; + }; + direct = { domains = lib.unique (r.direct.domains ++ zapretDirectDomains); ips = lib.unique (r.direct.ips ++ zapretDirectIps); diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index f8c0a64..5fd5573 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -19,6 +19,7 @@ let ; }; inherit (zapretDirect) direct; + zapretDirectRules = zapretDirect.zapretDirect; customRuleCategory = outbound: @@ -105,6 +106,7 @@ in { inherit direct + zapretDirectRules geositeRuleSets geoIPRuleSets singBoxRoutingRules diff --git a/modules/proxy-suite/rules/proxy-inbounds.nix b/modules/proxy-suite/rules/proxy-inbounds.nix new file mode 100644 index 0000000..b4f9229 --- /dev/null +++ b/modules/proxy-suite/rules/proxy-inbounds.nix @@ -0,0 +1,124 @@ +# XRay routing rules for the server-side inbound service. +# +# Deliberately separate from the client ruleset: inbound traffic belongs to +# somebody else's session, so it is not subject to routing.rules, route-mode +# overrides, or the DNS-hijack machinery the client config needs. +# +# The "proxy" outbound here is the local client stack's SOCKS listener, so +# anything the client decides (selected outbound, urltest, route-mode) applies +# to relayed traffic without being reimplemented. +{ + lib, + proxyInboundsCfg, + proxyInbounds, + zapretDirectRules, +}: + +let + defaultVia = proxyInboundsCfg.via; + + # Listeners that follow the tree-wide default need no rule of their own; the + # final rule already sends them there. + overrideInbounds = builtins.filter (ib: ib.via != defaultVia) proxyInbounds; + defaultInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via == defaultVia) proxyInbounds); + + blockPrivateRule = lib.optional proxyInboundsCfg.blockPrivate { + type = "field"; + ruleTag = "inbound-block-private"; + ip = [ "geoip:private" ]; + outboundTag = "block"; + }; + + # A relay must not blackhole the address clients dial to reach it. Without + # this, a server on a .ru domain (or a .ru IP) blocks itself under blockRu: + # anyone connected through the host cannot open the very site the listeners + # are hidden behind, and a blackholed connection reads as a refusal rather + # than as a rule. Placed after blockPrivate so a NATed serverAddress cannot + # be used to reach the LAN. + # + # It may be given in either form, and geoip:ru catches a literal IP just as + # geosite catches the name. An IPv6 literal is the only form carrying a colon; + # a bare name cannot. + serverAddressIsIp = + let + addr = proxyInboundsCfg.serverAddress; + in + 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}" ]; } + ) + ); + + blockRuRules = lib.optionals proxyInboundsCfg.blockRu [ + { + type = "field"; + ruleTag = "inbound-block-ru-domain"; + domain = [ "geosite:category-ru" ]; + outboundTag = "block"; + } + { + type = "field"; + ruleTag = "inbound-block-ru-ip"; + ip = [ "geoip:ru" ]; + outboundTag = "block"; + } + ]; + + # Only meaningful when the default egress leaves through a proxy: zapret works + # on traffic this host emits itself, so destinations it can already unblock + # are better left direct than sent through a proxy hop. Scoped to the + # listeners on the default egress, so an explicit per-listener `via` wins. + zapretDirectEnabled = + proxyInboundsCfg.zapretDirect + && defaultInboundTags != [ ] + && !builtins.elem defaultVia [ + "direct" + "block" + ]; + + mkZapretRule = + ruleTag: field: items: + lib.optional (zapretDirectEnabled && items != [ ]) { + type = "field"; + inherit ruleTag; + ${field} = items; + inboundTag = defaultInboundTags; + outboundTag = "direct"; + }; + + zapretRules = + mkZapretRule "inbound-zapret-direct-domain" "domain" ( + map (domain: "domain:${domain}") zapretDirectRules.domains + ) + ++ mkZapretRule "inbound-zapret-direct-ip" "ip" zapretDirectRules.ips; + + overrideRules = map (ib: { + type = "field"; + ruleTag = "inbound-via-${ib.tag}"; + inboundTag = [ ib.tag ]; + outboundTag = ib.via; + }) overrideInbounds; + + finalRule = { + type = "field"; + ruleTag = "inbound-final"; + network = "tcp,udp"; + outboundTag = defaultVia; + }; + + xrayInboundRules = blockPrivateRule ++ serverAddressRule ++ blockRuRules ++ zapretRules ++ overrideRules ++ [ finalRule ]; +in +{ + inherit xrayInboundRules; +} diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index c534c0b..a015023 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -82,6 +82,12 @@ let (mkAssertion ( !cfg.sshProxy.enable || (cfg.sshProxy.user != null && cfg.sshProxy.host != null) ) "proxy-suite: sshProxy.user and sshProxy.host are required when sshProxy.enable = true") + # SingBox dials SSH itself and verifies host keys by value, with no + # knownHostsFile and no trust-on-first-use fallback. An empty list accepts + # any host key, so refuse rather than silently downgrade the tunnel. + (mkAssertion ( + !derived.sshProxyNativeOutbound || cfg.sshProxy.hostKey != [ ] || cfg.sshProxy.hostKeyFile != null + ) "proxy-suite: sshProxy.hostKey or sshProxy.hostKeyFile is required when sshProxy.asOutbound = true with a SingBox or hybrid backend, because SingBox verifies host keys by value and an empty list accepts any key. Point hostKeyFile at a known-hosts file, or list every key from `ssh-keyscan -p ` in hostKey -- the host key algorithm is negotiated, so a single pinned key fails the handshake when the server picks another algorithm.") (mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ]) "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}" ) @@ -208,6 +214,128 @@ let ) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true") ]) proxyCfg.outbounds; + proxyInboundsCfg = derived.proxyInboundsCfg; + proxyInboundsEnabled = derived.proxyInboundsEnabled; + proxyInbounds = derived.proxyInbounds; + proxyInboundsNeedLocalProxy = proxyInboundsEnabled && derived.proxyInboundsNeedLocalProxy; + + # A pinned outbound is rendered by the XRay renderer inside the inbound + # service, so a sing-box-only definition cannot serve as one. + singBoxOnlyPinnedTags = map (ob: ob.tag) ( + builtins.filter ( + ob: ob.singBoxJson != null || ob.json != null + ) derived.proxyInboundViaOutbounds + ); + + proxyInboundAssertions = + [ + (mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ]) + "proxy-suite: proxyInbounds via targets are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies cannot be named here because their tags only exist at runtime; use via = \"proxy\" to reach those." + ) + (mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ]) + "proxy-suite: proxyInbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson." + ) + (requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled + "proxy-suite: proxyInbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true" + ) + (requireEnabled proxyInboundsEnabled (proxyInbounds != [ ]) + "proxy-suite: proxyInbounds.enable requires at least one entry in proxyInbounds.listeners" + ) + (requireEnabled proxyInboundsNeedLocalProxy proxyEnabled + "proxy-suite: proxyInbounds.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node." + ) + (requireEnabled proxyInboundsNeedLocalProxy derived.hasAvailableOutbounds + "proxy-suite: proxyInbounds.via = \"proxy\" relays through the local proxy stack, so at least one proxy.outbounds or proxy.subscriptions entry is required" + ) + (uniqueValues proxyInboundsEnabled (map (ib: ib.listener.port) proxyInbounds) + "proxy-suite: proxyInbounds.listeners must each use a distinct port" + ) + (mkAssertion + ( + !proxyInboundsEnabled + || !proxyEnabled + || !builtins.elem proxyCfg.port derived.proxyInboundPorts + ) + "proxy-suite: a proxyInbounds listener port collides with proxy.port (${toString proxyCfg.port})" + ) + (mkAssertion + ( + !proxyInboundsEnabled + || !globalTproxy.enable + || !builtins.elem globalTproxy.port derived.proxyInboundPorts + ) + "proxy-suite: a proxyInbounds listener port collides with proxy.tproxy.port (${toString globalTproxy.port})" + ) + ] + ++ lib.concatMap ( + ib: + let + l = ib.listener; + prefix = "proxy-suite: proxyInbounds listener '${ib.tag}'"; + firstUser = if l.users == [ ] then null else builtins.head l.users; + needsUuid = builtins.elem l.type [ + "vless" + "vmess" + ]; + needsPassword = builtins.elem l.type [ + "trojan" + "shadowsocks" + "socks" + "http" + ]; + tlsTerminated = l.tls.enable || l.type == "trojan"; + in + [ + (exactlyOneOf proxyInboundsEnabled [ + l.type + l.xrayJson + l.jsonFile + ] "${prefix}: set exactly one of type, xrayJson, or jsonFile") + (mkAssertion ( + !proxyInboundsEnabled || !(l.tls.enable && l.reality.enable) + ) "${prefix}: tls.enable and reality.enable are mutually exclusive") + (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") + (exactlyOneOf (proxyInboundsEnabled && l.reality.enable) [ + l.reality.privateKey + l.reality.privateKeyFile + ] "${prefix}: reality needs exactly one of privateKey or privateKeyFile") + (mkAssertion ( + !proxyInboundsEnabled || !l.reality.enable || l.reality.serverNames != [ ] + ) "${prefix}: reality.serverNames must not be empty") + (requireAvailable (proxyInboundsEnabled && l.reality.enable && proxyInboundsCfg.shareLinks) + (l.reality.publicKey != null) + "${prefix}: reality.publicKey is required to generate share links. Run `xray x25519` to print it alongside the private key, or set proxyInbounds.shareLinks = false." + ) + (mkAssertion + ( + !proxyInboundsEnabled + || !tlsTerminated + || l.reality.enable + || (l.tls.certificateFile != null && l.tls.keyFile != null) + ) + "${prefix}: TLS termination needs both tls.certificateFile and tls.keyFile" + ) + (mkAssertion + ( + !proxyInboundsEnabled + || l.flow == null + || (l.type == "vless" && l.transport.type == "raw") + ) + "${prefix}: flow is only valid on a vless listener with transport.type = \"raw\"" + ) + ] + ) proxyInbounds; + subscriptionAssertions = lib.concatMap (sub: [ (exactlyOneOf proxyEnabled [ sub.urlFile @@ -464,6 +592,7 @@ featureAssertions ++ localProxyAuthAssertions ++ secretAssertions ++ outboundAssertions +++ proxyInboundAssertions ++ subscriptionAssertions ++ collisionAssertions ++ positiveNumberAssertions diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index a8f7c19..1ccc0d8 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -8,6 +8,8 @@ tunFile, perAppTunFile, routeModeRulesFile, + proxyInboundsFile, + proxyInboundsSpecFile, perAppTunChainFile, perAppTproxyRulesFile, perAppZapretRulesFile, @@ -44,6 +46,12 @@ let hasSubscriptions sshProxyCfg sshProxyOutboundEnabled + sshProxyUnitEnabled + proxyInboundsCfg + proxyInboundsEnabled + proxyInboundsNeedLocalProxy + proxyInboundViaOutbounds + userControlEnabled ; # Tool paths – defined once here and passed into sub-modules as needed. @@ -64,8 +72,11 @@ let proxySuiteScriptsDir = ../../../scripts; parserScriptsPythonPath = proxySuiteScriptsDir; buildOutboundPy = "${proxySuiteScriptsDir}/build-outbound.py"; + buildInboundPy = "${proxySuiteScriptsDir}/build-inbound.py"; fetchSubscriptionPy = "${proxySuiteScriptsDir}/fetch-subscription.py"; + builders = import ./builders.nix { inherit lib pkgs; }; + polkit = import ./polkit.nix { inherit lib cfg userControlCfg; }; @@ -95,6 +106,7 @@ let xray parserScriptsPythonPath buildOutboundPy + buildInboundPy fetchSubscriptionPy ; inherit @@ -102,6 +114,15 @@ let tunFile perAppTunFile routeModeRulesFile + proxyInboundsFile + proxyInboundsSpecFile + ; + inherit + proxyInboundsCfg + proxyInboundsNeedLocalProxy + proxyInboundViaOutbounds + userControlEnabled + builders ; }; @@ -144,6 +165,8 @@ let ; inherit (scripts) subscriptionTagsFile subscriptionCacheDir; inherit (scripts) routeModeStateFile; + inherit proxyInboundsEnabled; + inherit (scripts) proxyInboundsLinksFile; inherit amneziaWgProfileNamesFile; inherit (perAppRouting) perAppRoutingProfilesFile diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 059352c..ad88402 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -15,6 +15,8 @@ proxychainsQuietArg, routeModeStateFile, amneziaWgProfileNamesFile, + proxyInboundsEnabled, + proxyInboundsLinksFile, }: { proxyCtl = packages.mkProxyCtl { @@ -35,5 +37,7 @@ perAppRoutingTunEnabled = if perAppRoutingTun.enable then "1" else "0"; perAppRoutingTproxyEnabled = if perAppRoutingTproxy.enable then "1" else "0"; perAppRoutingZapretEnabled = if perAppZapretCfg.enable then "1" else "0"; + inboundsEnabled = if proxyInboundsEnabled then "1" else "0"; + inboundsLinksFile = proxyInboundsLinksFile; }; } diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 87282f4..8a3ebe3 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -9,6 +9,8 @@ tunFile, perAppTunFile, routeModeRulesFile, + proxyInboundsFile, + proxyInboundsSpecFile, nftablesRulesFile, perAppTproxyRulesFile, perAppZapretRulesFile, @@ -28,6 +30,8 @@ let tunFile perAppTunFile routeModeRulesFile + proxyInboundsFile + proxyInboundsSpecFile perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile @@ -61,6 +65,11 @@ let perAppZapretEnabled hasSubscriptions sshProxyOutboundEnabled + sshProxyUnitEnabled + proxyInboundsEnabled + proxyInboundsNeedLocalProxy + proxyInboundFirewallPorts + proxyInboundFirewallUdpPorts outboundTags effectiveOutboundTags subscriptionTags @@ -99,6 +108,9 @@ let perAppZapretEnabled hasSubscriptions sshProxyOutboundEnabled + sshProxyUnitEnabled + proxyInboundsEnabled + proxyInboundsNeedLocalProxy scripts perAppRouting routingScripts @@ -124,6 +136,12 @@ in || perAppZapretEnabled ) (lib.mkDefault true); + # Inbound listeners are reached from outside, so their ports have to be open. + networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.proxyInbounds.openFirewall) { + allowedTCPPorts = proxyInboundFirewallPorts; + allowedUDPPorts = proxyInboundFirewallUdpPorts; + }; + users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) { "${userControlCfg.group}" = { }; }; diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix new file mode 100644 index 0000000..7bca1a4 --- /dev/null +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -0,0 +1,142 @@ +# Startup script for the server-side inbound service. +# +# Much smaller than the client start script: no route-mode, no TUN/TProxy, no +# hybrid sidecar. It renders the listeners (reading their secrets), merges them +# into the build-time template, and hands the result to XRay. +{ + lib, + pkgs, + proxyCfg, + proxyInboundsCfg, + proxyInboundsNeedLocalProxy, + proxyInboundViaOutbounds, + userControlCfg, + userControlEnabled, + localProxyAuth, + localProxyAuthEnabled, + localProxyAuthPasswordSource, + jq, + python3, + parserScriptsPythonPath, + buildInboundPy, + buildOutboundPy, + proxyInboundsFile, + proxyInboundsSpecFile, + builders, +}: + +let + runtimeDir = "/run/proxy-suite-inbounds"; + linksFile = "${runtimeDir}/links.json"; + # This service's own package, not the client backend's. + xray = "${proxyInboundsCfg.package}/bin/xray"; + + # Only the local proxy needs credentials injected; the listeners' own secrets + # are resolved by build-inbound.py. + needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled; + + serverAddressBlock = + if proxyInboundsCfg.serverAddress != null then + ''SERVER_ADDRESS=${lib.escapeShellArg proxyInboundsCfg.serverAddress}'' + else if proxyInboundsCfg.shareLinks then + '' + ${builders.mkDefaultUplinkIPv4Source { + ip = "${pkgs.iproute2}/bin/ip"; + awk = "${pkgs.gawk}/bin/awk"; + errorMessage = "proxy-suite: could not determine this host's uplink address for inbound share links; set proxyInbounds.serverAddress"; + }} + SERVER_ADDRESS="$uplink_addr" + '' + else + ''SERVER_ADDRESS=""''; + + # Outbounds a listener pins itself to with `via = ""`. Rendered here, at + # start time, so a urlFile's contents stay out of the Nix store. Subscriptions + # are deliberately not duplicated into this service: their cache is refreshed + # for the client backend only, and `via = "proxy"` already reaches them. + mkViaOutboundBlock = + ob: + let + urlSource = + if ob.urlFile != null then + ob.urlFile + else if ob.url != null then + pkgs.writeText "proxy-suite-inbound-via-url-${ob.tag}" ob.url + else + null; + in + if urlSource == null then + '' + # via outbound: ${ob.tag} (static xray json) + OB_JSON=$(cat ${ + pkgs.writeText "proxy-suite-inbound-via-${ob.tag}.json" ( + builtins.toJSON (ob.xrayJson // { inherit (ob) tag; }) + ) + }) + OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") + '' + else + '' + # via outbound: ${ob.tag} + URL=$(cat ${lib.escapeShellArg urlSource}) + OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \ + --backend xray --tag ${lib.escapeShellArg ob.tag}) + OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") + ''; + + viaOutboundsBlock = lib.concatMapStrings mkViaOutboundBlock proxyInboundViaOutbounds; + + # Share links carry the listener credentials, so they are no more public than + # the config itself. + writeLinksBlock = lib.optionalString proxyInboundsCfg.shareLinks '' + ${jq} -c '.links' <<< "$RENDERED" > "${linksFile}" + ${lib.optionalString userControlEnabled '' + ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${linksFile}" + ''} + chmod ${if userControlEnabled then "640" else "600"} "${linksFile}" + ''; + + startInbounds = pkgs.writeShellScript "proxy-suite-start-inbounds" '' + set -euo pipefail + umask 077 + RUNTIME_DIR="${runtimeDir}" + mkdir -p "$RUNTIME_DIR" + + ${serverAddressBlock} + + RENDERED=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildInboundPy} \ + --spec ${proxyInboundsSpecFile} \ + --server-address "$SERVER_ADDRESS") + + INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED") + + OUTBOUNDS_JSON='[]' + ${viaOutboundsBlock} + + ${lib.optionalString needsLocalProxyAuth '' + LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" + ''} + + ${jq} \ + --argjson ibs "$INBOUNDS_JSON" \ + --argjson obs "$OUTBOUNDS_JSON" \ + --argjson auth_enabled ${if needsLocalProxyAuth then "true" else "false"} \ + --arg user ${if needsLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \ + --arg password ${if needsLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \ + '.inbounds = $ibs + | .outbounds = $obs + .outbounds + | if $auth_enabled then + (.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users) + = [{user:$user,pass:$password}] + else . end' \ + ${proxyInboundsFile} > "$RUNTIME_DIR/config.json" + chmod 600 "$RUNTIME_DIR/config.json" + + ${writeLinksBlock} + + exec ${xray} run -c "$RUNTIME_DIR/config.json" + ''; +in +{ + inherit startInbounds linksFile; +} diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index e039697..4972911 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -22,6 +22,15 @@ let sshProxyTag = "ssh-proxy"; + # sing-box domain-strategy names mapped onto XRay's sockopt.domainStrategy. + # XRay's "UseIPv4v6" means "IPv4 first, fall back to IPv6", i.e. prefer_ipv4. + xrayDomainStrategies = { + prefer_ipv4 = "UseIPv4v6"; + prefer_ipv6 = "UseIPv6v4"; + ipv4_only = "UseIPv4"; + ipv6_only = "UseIPv6"; + }; + rawOutboundJson = ob: tag: routingMark: let @@ -169,16 +178,33 @@ let mkSshProxyOutboundBlock = routingMark: let + # sing-box dials SSH itself, so there is no OpenSSH unit and no local + # SOCKS5 hop. It resolves destinations natively, which is why this shape + # takes no domainStrategy. singBoxOutbound = { - type = "socks"; + type = "ssh"; tag = sshProxyTag; - server = sshProxyCfg.listenAddress; - server_port = sshProxyCfg.listenPort; - version = "5"; + server = sshProxyCfg.host; + server_port = sshProxyCfg.sshPort; + user = sshProxyCfg.user; + } + // lib.optionalAttrs (sshProxyCfg.identityFile != null) { + private_key_path = sshProxyCfg.identityFile; + } + // lib.optionalAttrs (sshProxyCfg.hostKey != [ ]) { + host_key = sshProxyCfg.hostKey; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }; + # XRay has no SSH outbound, so it proxies through the listener the + # OpenSSH unit creates. sockopt.domainStrategy is what makes XRay resolve + # destinations here instead of handing the domain to the remote sshd. + xraySockopt = + lib.optionalAttrs (routingMark != null) { mark = routingMark; } + // lib.optionalAttrs (sshProxyCfg.domainStrategy != null) { + domainStrategy = xrayDomainStrategies.${sshProxyCfg.domainStrategy}; + }; xrayOutbound = { protocol = "socks"; tag = sshProxyTag; @@ -187,23 +213,45 @@ let port = sshProxyCfg.listenPort; }; } - // lib.optionalAttrs (routingMark != null) { - streamSettings.sockopt.mark = routingMark; + // lib.optionalAttrs (xraySockopt != { }) { + streamSettings.sockopt = xraySockopt; }; outbound = if pureXrayEnabled then xrayOutbound else singBoxOutbound; outboundJson = builtins.toJSON outbound; jsonFile = pkgs.writeText "proxy-suite-ob-ssh-proxy-${backend}.json" outboundJson; + + # Host keys come from a known-hosts file at start time so the file stays + # out of the Nix store. ssh-keygen -F also resolves hashed entries. + knownHostsTarget = + if sshProxyCfg.sshPort == 22 then + sshProxyCfg.host + else + "[${sshProxyCfg.host}]:${toString sshProxyCfg.sshPort}"; + hostKeyFileBlock = + lib.optionalString (!pureXrayEnabled && sshProxyCfg.hostKeyFile != null) + '' + SSH_HOST_KEYS=$(${pkgs.openssh}/bin/ssh-keygen -F ${lib.escapeShellArg knownHostsTarget} \ + -f ${lib.escapeShellArg sshProxyCfg.hostKeyFile} \ + | ${jq} -R -s '[splits("\n")] | map(select(length > 0 and (startswith("#") | not))) | map(sub("^\\S+\\s+"; ""))') + if [ "$(${jq} 'length' <<< "$SSH_HOST_KEYS")" -eq 0 ]; then + echo "proxy-suite: no host keys for ${knownHostsTarget} in ${sshProxyCfg.hostKeyFile}" >&2 + exit 1 + fi + OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON") + ''; in if hybridEnabled then '' - # outbound: ${sshProxyTag} (SSH SOCKS5) + # outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"}) OB_JSON=$(cat "${jsonFile}") + ${hostKeyFileBlock} _proxy_suite_add_sing_box_ob "$OB_JSON" '' else '' - # outbound: ${sshProxyTag} (SSH SOCKS5) + # outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"}) OB_JSON=$(cat "${jsonFile}") + ${hostKeyFileBlock} OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") ''; diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index fa2305c..b2b4d0d 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -26,6 +26,14 @@ tunFile, perAppTunFile, routeModeRulesFile, + proxyInboundsCfg, + proxyInboundsNeedLocalProxy, + proxyInboundViaOutbounds, + userControlEnabled, + buildInboundPy, + proxyInboundsFile, + proxyInboundsSpecFile, + builders, }: let @@ -157,6 +165,32 @@ let }; inherit (startScripts) startSocks startTun startPerAppTun; + proxyInboundsScripts = import ./proxy-inbounds-scripts.nix { + inherit + lib + pkgs + proxyCfg + proxyInboundsCfg + proxyInboundsNeedLocalProxy + proxyInboundViaOutbounds + userControlCfg + userControlEnabled + localProxyAuth + localProxyAuthEnabled + localProxyAuthPasswordSource + jq + python3 + parserScriptsPythonPath + buildInboundPy + buildOutboundPy + proxyInboundsFile + proxyInboundsSpecFile + builders + ; + }; + inherit (proxyInboundsScripts) startInbounds; + proxyInboundsLinksFile = proxyInboundsScripts.linksFile; + controlScripts = import ./control-scripts.nix { inherit lib @@ -175,8 +209,9 @@ let in { - inherit startSocks startTun startPerAppTun; + inherit startSocks startTun startPerAppTun startInbounds; inherit + proxyInboundsLinksFile routeModeStateFile setRouteModeScript subscriptionUpdateScript diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index ff59b6c..2691c77 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -13,6 +13,9 @@ perAppZapretEnabled, hasSubscriptions, sshProxyOutboundEnabled, + sshProxyUnitEnabled, + proxyInboundsEnabled, + proxyInboundsNeedLocalProxy, scripts, perAppRouting, routingScripts, @@ -41,6 +44,7 @@ let perAppTproxy = "proxy-suite-per-app-tproxy"; perAppZapret = "proxy-suite-per-app-zapret"; subscriptionUpdate = "proxy-suite-subscription-update"; + inbounds = "proxy-suite-inbounds"; }; backendDescription = @@ -61,17 +65,43 @@ let name = serviceNames.socks; value = mkRestartingService { description = "${backendDescription} proxy client (SOCKS + TProxy-ready)"; + # Only the XRay backend proxies through the OpenSSH unit's listener; + # SingBox dials SSH inside its own process and needs no ordering. after = [ "network-online.target" ] - ++ lib.optional sshProxyOutboundEnabled "proxy-suite-ssh-proxy.service"; - wants = [ "network-online.target" ]; + ++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service"; + wants = [ + "network-online.target" + ] + ++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service"; wantedBy = [ "multi-user.target" ]; execStart = scripts.startSocks; runtimeDirectory = serviceNames.socks; stateDirectory = "proxy-suite"; }; } + { + enable = proxyInboundsEnabled; + name = serviceNames.inbounds; + value = mkRestartingService { + description = "XRay server inbounds (accept connections from outside)"; + after = [ + "network-online.target" + ] + # Relayed traffic leaves through the client stack's SOCKS listener, so + # start after it. Not `requires`: the listeners should keep serving + # direct-routed traffic even if the client stack is down. + ++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service"; + wants = [ + "network-online.target" + ] + ++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service"; + wantedBy = [ "multi-user.target" ]; + execStart = scripts.startInbounds; + runtimeDirectory = serviceNames.inbounds; + }; + } { enable = proxyEnabled && globalTproxy.enable; name = serviceNames.tproxy; diff --git a/modules/proxy-suite/ssh-proxy.nix b/modules/proxy-suite/ssh-proxy.nix index 3ff489b..eb3fc4b 100644 --- a/modules/proxy-suite/ssh-proxy.nix +++ b/modules/proxy-suite/ssh-proxy.nix @@ -16,6 +16,9 @@ let -N -o BatchMode=yes -o ExitOnForwardFailure=yes + -o ServerAliveInterval=15 + -o ServerAliveCountMax=3 + -o ConnectTimeout=10 -o StrictHostKeyChecking=${lib.escapeShellArg s.strictHostKeyChecking} -D ${lib.escapeShellArg "${s.listenAddress}:${toString s.listenPort}"} ) @@ -34,10 +37,17 @@ in after = [ "network-online.target" ]; wants = [ "network-online.target" ]; wantedBy = [ "multi-user.target" ]; + # Restart=always plus a server that refuses connections would otherwise hit + # the default 5-starts-in-10s limit and stay failed. + startLimitIntervalSec = 0; serviceConfig = { ExecStart = startScript; - Restart = "on-failure"; + # `ssh -N` exits 0 when the server closes the connection cleanly, which + # under on-failure left the tunnel down for good. + Restart = "always"; RestartSec = 5; + # One fd per forwarded channel; the 1024 default is low for a relay. + LimitNOFILE = 65536; } // lib.optionalAttrs (s.serviceUser != null) { User = s.serviceUser; diff --git a/nix/checks.nix b/nix/checks.nix index 3752ebe..2b84f22 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -36,6 +36,9 @@ let amneziaWgRuntime = import ./checks/amnezia-wg-runtime.nix { inherit pkgs nixpkgs proxySuiteModule; }; + proxyInboundsRuntime = import ./checks/proxy-inbounds-runtime.nix { + inherit pkgs proxySuiteModule; + }; in moduleSuiteChecks // { @@ -43,6 +46,7 @@ moduleSuiteChecks } // pkgs.lib.optionalAttrs (system == "x86_64-linux") { amneziawg-runtime = amneziaWgRuntime; + proxy-inbounds-runtime = proxyInboundsRuntime; } // parserChecks // repoChecks diff --git a/nix/checks/lib.nix b/nix/checks/lib.nix index 05d60ac..772a892 100644 --- a/nix/checks/lib.nix +++ b/nix/checks/lib.nix @@ -44,6 +44,8 @@ let mkTProxyConfig = fixture: mkProxyConfig fixture "tproxyFile"; mkTunConfig = fixture: mkProxyConfig fixture "tunFile"; mkPerAppTunConfig = fixture: mkProxyConfig fixture "perAppTunFile"; + mkInboundsConfig = fixture: mkProxyConfig fixture "proxyInboundsFile"; + mkInboundsSpec = fixture: mkProxyConfig fixture "proxyInboundsSpecFile"; mkTProxyNftRules = fixture: let @@ -227,6 +229,8 @@ in mkTProxyConfig mkTunConfig mkPerAppTunConfig + mkInboundsConfig + mkInboundsSpec mkTProxyNftRules mkPerAppZapretNftRules mkPerAppUserRules diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index db94a6e..a33b7e2 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -11,6 +11,8 @@ let mkTProxyConfig mkTunConfig mkPerAppTunConfig + mkInboundsConfig + mkInboundsSpec mkTProxyNftRules mkPerAppZapretNftRules mkPerAppUserRules @@ -115,6 +117,16 @@ let ; }; + proxyInboundsChecks = import ./proxy-inbounds.nix { + inherit + pkgs + evalProxySuite + baseModule + mkInboundsConfig + mkInboundsSpec + ; + }; + perAppRoutingChecks = import ./per-app-routing.nix { inherit pkgs @@ -215,6 +227,7 @@ let ++ coreProxyChecks.assertions ++ localProxyAuthChecks.assertions ++ sshProxyChecks.assertions + ++ proxyInboundsChecks.assertions ++ tgWsProxyChecks.assertions ++ xrayBackendChecks.assertions ++ outboundValidationChecks.assertions diff --git a/nix/checks/parsers.nix b/nix/checks/parsers.nix index 171b0c8..82047a4 100644 --- a/nix/checks/parsers.nix +++ b/nix/checks/parsers.nix @@ -10,6 +10,15 @@ touch "$out" ''; + build-inbound-renderer = + pkgs.runCommand "build-inbound-renderer-check" { nativeBuildInputs = [ pkgs.python3 ]; } + '' + export PYTHONDONTWRITEBYTECODE=1 + export PYTHONPATH=${../../scripts}:$PYTHONPATH + python ${../../scripts/test-build-inbound.py} + touch "$out" + ''; + fetch-subscription-parser = pkgs.runCommand "fetch-subscription-parser-check" { nativeBuildInputs = [ pkgs.python3 ]; } '' diff --git a/nix/checks/proxy-inbounds-runtime.nix b/nix/checks/proxy-inbounds-runtime.nix new file mode 100644 index 0000000..420ab8d --- /dev/null +++ b/nix/checks/proxy-inbounds-runtime.nix @@ -0,0 +1,148 @@ +{ + pkgs, + proxySuiteModule, +}: + +let + # Fixed so the client can be configured against it at build time. Real + # deployments keep these in a secret manager. + uuid = "b831381d-6324-4d53-ad4f-8cda48b30811"; + ssPassword = "dGhpcy1pcy1hLTE2Ynl0ZS1rZXk="; + serverAddress = "192.168.0.1"; + + network = address: { + networking.useDHCP = false; + networking.interfaces.eth1.ipv4.addresses = [ + { + inherit address; + prefixLength = 24; + } + ]; + }; +in +pkgs.testers.runNixOSTest { + name = "proxy-suite-inbounds-runtime"; + + nodes = { + # A pure server: no client proxy stack at all. + server = + { ... }: + { + imports = [ + proxySuiteModule + (network serverAddress) + ]; + + services.proxy-suite = { + enable = true; + proxy.enable = false; + proxyInbounds = { + enable = true; + inherit serverAddress; + via = "direct"; + openFirewall = true; + listeners.vless-in = { + type = "vless"; + port = 8443; + users = [ + { + name = "tester"; + inherit uuid; + } + ]; + }; + listeners.ss-in = { + type = "shadowsocks"; + port = 8388; + method = "2022-blake3-aes-128-gcm"; + users = [ { password = ssPassword; } ]; + }; + }; + }; + + services.nginx = { + enable = true; + virtualHosts."origin".locations."/".return = "200 'served-from-origin'"; + }; + networking.firewall.allowedTCPPorts = [ 80 ]; + }; + + client = + { ... }: + { + imports = [ + proxySuiteModule + (network "192.168.0.2") + ]; + + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + xray.enable = true; + port = 1080; + outbounds = [ + { + tag = "server"; + url = "vless://${uuid}@${serverAddress}:8443?type=tcp&security=none"; + } + ]; + }; + }; + }; + }; + + testScript = '' + start_all() + server.wait_for_unit("proxy-suite-inbounds.service") + server.wait_for_unit("nginx.service") + server.wait_for_open_port(8443) + server.wait_for_open_port(8388) + + with subtest("the rendered config carries both listeners"): + cfg = "/run/proxy-suite-inbounds/config.json" + server.succeed(f"test $(jq -r '.inbounds | length' {cfg}) = 2") + 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.fail(f"grep -r '${uuid}' /nix/store/*proxy-suite-inbounds-*.json") + + with subtest("safety rules are present and ordered first"): + cfg = "/run/proxy-suite-inbounds/config.json" + server.succeed(f"test $(jq -r '.routing.rules[0].ruleTag' {cfg}) = inbound-block-private") + server.succeed(f"jq -e '.routing.rules[] | select(.ruleTag == \"inbound-block-ru-domain\")' {cfg}") + server.succeed(f"test $(jq -r '.routing.rules[-1].outboundTag' {cfg}) = direct") + + with subtest("a client reaches the origin through the inbound"): + client.wait_for_unit("proxy-suite-socks.service") + client.wait_for_open_port(1080) + client.succeed( + "curl -sS --fail --max-time 20 --proxy socks5h://127.0.0.1:1080" + f" http://{'${serverAddress}'}/ | grep -q served-from-origin" + ) + + with subtest("blocked destinations are refused"): + # The inbound must not become a way into the server's own loopback. + server.succeed("jq -e '.routing.rules[] | select(.ruleTag == \"inbound-block-private\") | select(.outboundTag == \"block\")' /run/proxy-suite-inbounds/config.json") + client.fail( + "curl -sS --fail --max-time 15 --proxy socks5h://127.0.0.1:1080" + " http://127.0.0.1/ 2>&1" + ) + + with subtest("share links are generated and readable by proxy-ctl"): + links = "/run/proxy-suite-inbounds/links.json" + server.succeed(f"test $(stat -c %a {links}) = 600") + server.succeed(f"test $(jq -r 'length' {links}) = 2") + link = server.succeed("proxy-ctl inbounds link vless-in").strip() + assert link.startswith("vless://${uuid}@${serverAddress}:8443"), link + assert "#tester" in link, link + server.succeed("proxy-ctl inbounds | grep -q vless-in") + server.succeed("proxy-ctl inbounds qr vless-in | head -c 1") + server.succeed("proxy-ctl status | grep -q proxy-suite-inbounds") + + with subtest("a listener keeps serving after a restart"): + server.succeed("systemctl restart proxy-suite-inbounds.service") + server.wait_for_open_port(8443) + ''; +} diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix new file mode 100644 index 0000000..6c070b6 --- /dev/null +++ b/nix/checks/proxy-inbounds.nix @@ -0,0 +1,448 @@ +{ + pkgs, + evalProxySuite, + baseModule, + mkInboundsConfig, + mkInboundsSpec, +}: + +let + inherit (pkgs) lib; + + realityListener = { + type = "vless"; + port = 443; + users = [ { uuidFile = "/run/secrets/uuid"; } ]; + flow = "xtls-rprx-vision"; + reality = { + enable = true; + serverNames = [ "www.microsoft.com" ]; + privateKeyFile = "/run/secrets/reality-key"; + publicKey = "public-key"; + shortIds = [ "0123abcd" ]; + }; + }; + + mkInbounds = + proxyInbounds: + evalProxySuite [ + baseModule + { services.proxy-suite.proxyInbounds = { enable = true; } // proxyInbounds; } + ]; + + relayFixture = mkInbounds { listeners.vless-in = realityListener; }; + relayConfig = mkInboundsConfig relayFixture; + relaySpec = mkInboundsSpec relayFixture; + + exitFixture = mkInbounds { + via = "direct"; + listeners.vless-in = realityListener; + }; + exitConfig = mkInboundsConfig exitFixture; + + mixedFixture = mkInbounds { + listeners.relayed = realityListener; + listeners.local-exit = realityListener // { + port = 8443; + via = "direct"; + }; + }; + mixedConfig = mkInboundsConfig mixedFixture; + + # Two listeners, two different servers. + pinnedFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "nl-vps"; + url = "http://nl.example.com:8080"; + } + { + tag = "de-vps"; + url = "http://de.example.com:8080"; + } + { + tag = "unused"; + singBoxJson = { + type = "tuic"; + }; + } + ]; + }; + proxyInbounds = { + enable = true; + via = "nl-vps"; + listeners.through-nl = realityListener; + listeners.through-de = realityListener // { + port = 8443; + via = "de-vps"; + }; + }; + }; + } + ]; + pinnedConfig = mkInboundsConfig pinnedFixture; + + # A .ru serverAddress is exactly what blockRu would otherwise blackhole. + namedFixture = mkInbounds { + serverAddress = "vpn.example.ru"; + listeners.vless-in = realityListener; + }; + namedConfig = mkInboundsConfig namedFixture; + + # The same trap in its literal-IP form. + ipNamedFixture = mkInbounds { + serverAddress = "82.146.44.102"; + listeners.vless-in = realityListener; + }; + ipNamedConfig = mkInboundsConfig ipNamedFixture; + + unguardedFixture = mkInbounds { + + + blockRu = false; + blockPrivate = false; + listeners.vless-in = realityListener; + }; + unguardedConfig = mkInboundsConfig unguardedFixture; + + firewallFixture = mkInbounds { + listeners.vless-in = realityListener; + listeners.ss-in = { + type = "shadowsocks"; + port = 8388; + users = [ { passwordFile = "/run/secrets/ss"; } ]; + }; + # Fronted by something else on this host, so its port stays closed even + # though the share link advertises the public one. + listeners.ws-in = { + type = "vless"; + port = 10002; + sharePort = 443; + listenAddress = "127.0.0.1"; + users = [ { uuidFile = "/run/secrets/ws"; } ]; + transport = { + type = "ws"; + path = "/vpnjantit"; + }; + tls = { + enable = true; + certificateFile = "/run/acme/fullchain.pem"; + keyFile = "/run/acme/key.pem"; + }; + }; + }; + firewallSpec = mkInboundsSpec firewallFixture; + wsListener = lib.head (builtins.filter (l: l.tag == "ws-in") firewallSpec.listeners); + + noFirewallFixture = mkInbounds { + openFirewall = false; + listeners.vless-in = realityListener; + }; + + ruleTags = config: map (rule: rule.ruleTag) config.routing.rules; + ruleByTag = + config: tag: builtins.head (builtins.filter (rule: rule.ruleTag == tag) config.routing.rules); + outboundTags = config: map (ob: ob.tag) config.outbounds; + hasOutbound = config: tag: builtins.elem tag (outboundTags config); + + service = fixture: fixture.config.systemd.services."proxy-suite-inbounds"; + + # Bad configurations are checked by looking at config.assertions directly + # rather than by forcing system.build.toplevel: it is far cheaper, and it + # pins which assertion fired instead of just "something failed". + baseProxy = { + enable = true; + proxy.enable = true; + proxy.singBox.enable = true; + proxy.outbounds = [ + { + tag = "primary"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + + mkRejects = + proxySuiteConfig: fragment: + let + fixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = proxySuiteConfig; + } + ]; + failed = builtins.filter (a: !a.assertion) fixture.config.assertions; + in + if lib.any (a: lib.hasInfix fragment a.message) failed then + true + else + # Name what was expected and what actually failed, so a regression here + # points at the assertion instead of just "something evaluated wrong". + throw "proxy-inbounds check: expected an assertion matching '${fragment}', got: ${builtins.toJSON (map (a: a.message) failed)}"; + + failing = [ + (mkRejects ( + baseProxy + // { + proxyInbounds = { + enable = true; + listeners.bad = { + type = "vless"; + xrayJson.protocol = "vless"; + }; + }; + } + ) "set exactly one of type, xrayJson, or jsonFile") + + (mkRejects ( + baseProxy + // { + proxyInbounds = { + enable = true; + listeners.a = realityListener; + listeners.b = realityListener; + }; + } + ) "must each use a distinct port") + + (mkRejects { + enable = true; + proxy.enable = false; + proxyInbounds = { + enable = true; + via = "proxy"; + listeners.vless-in = realityListener; + }; + } "requires proxy.enable = true") + + (mkRejects ( + baseProxy + // { + proxyInbounds = { + enable = true; + listeners.vless-in = realityListener // { + reality = realityListener.reality // { + publicKey = null; + }; + }; + }; + } + ) "reality.publicKey is required") + + (mkRejects ( + baseProxy + // { + proxyInbounds = { + enable = true; + listeners.tls-in = { + type = "vless"; + port = 8443; + users = [ { uuidFile = "/run/secrets/uuid"; } ]; + tls.enable = true; + }; + }; + } + ) "needs both tls.certificateFile and tls.keyFile") + + (mkRejects ( + baseProxy + // { + proxyInbounds = { + enable = true; + listeners.ws-in = realityListener // { + transport.type = "ws"; + }; + }; + } + ) "flow is only valid on a vless listener") + + (mkRejects ( + baseProxy + // { + proxyInbounds = { + enable = true; + via = "no-such-outbound"; + listeners.vless-in = realityListener; + }; + } + ) "are not defined in proxy.outbounds") + + (mkRejects { + enable = true; + proxy.enable = true; + proxy.singBox.enable = true; + proxy.outbounds = [ + { + tag = "sb-only"; + singBoxJson.type = "tuic"; + } + ]; + proxyInbounds = { + enable = true; + via = "sb-only"; + listeners.vless-in = realityListener; + }; + } "targets a sing-box-only outbound") + + (mkRejects (baseProxy // { proxyInbounds.enable = true; }) + "requires at least one entry in proxyInbounds.listeners" + ) + + # recursiveUpdate, not //: this one nests into proxy, which baseProxy sets. + (mkRejects + (lib.recursiveUpdate baseProxy { + proxy.port = 1080; + proxyInbounds = { + enable = true; + listeners.clash = realityListener // { + port = 1080; + }; + }; + }) + "collides with proxy.port" + ) + ]; + + assertions = [ + # The template carries no listeners; they are rendered at start time so no + # credential reaches the Nix store. + (assert relayConfig.inbounds == [ ]; true) + + # Relaying goes through the client stack's local SOCKS listener rather than + # a second copy of the outbound machinery. + (assert hasOutbound relayConfig "proxy"; true) + (assert (ruleByTag relayConfig "inbound-final").outboundTag == "proxy"; true) + ( + assert + (builtins.head (builtins.filter (ob: ob.tag == "proxy") relayConfig.outbounds)).protocol + == "socks"; + true + ) + ( + assert + (builtins.head (builtins.filter (ob: ob.tag == "proxy") relayConfig.outbounds)) + .settings.servers + == [ + { + address = "127.0.0.1"; + port = 1080; + } + ]; + true + ) + + # A pure exit node needs no proxy outbound at all. + (assert !hasOutbound exitConfig "proxy"; true) + (assert (ruleByTag exitConfig "inbound-final").outboundTag == "direct"; true) + + # Safety rules are on by default and come before anything else, so an + # inbound credential cannot reach the LAN or loopback. + (assert builtins.head (ruleTags relayConfig) == "inbound-block-private"; true) + (assert (ruleByTag relayConfig "inbound-block-private").outboundTag == "block"; true) + (assert (ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ]; true) + (assert (ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ]; true) + (assert !builtins.elem "inbound-block-private" (ruleTags unguardedConfig); true) + # The relay must not blackhole the address clients dial to reach it, and the + # exemption has to sit after blockPrivate but ahead of the country blocks. + ( + assert + lib.take 3 (ruleTags namedConfig) == [ + "inbound-block-private" + "inbound-server-address-direct" + "inbound-block-ru-domain" + ]; + true + ) + ( + assert + (ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ]; + true + ) + # No address to exempt when it is detected at runtime instead. + (assert !builtins.elem "inbound-server-address-direct" (ruleTags relayConfig); true) + ( + assert + (ruleByTag ipNamedConfig "inbound-server-address-direct").ip == [ "82.146.44.102" ]; + true + ) + (assert !builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig); true) + + # A per-listener via becomes its own rule; listeners on the default do not. + (assert builtins.elem "inbound-via-local-exit" (ruleTags mixedConfig); true) + (assert !builtins.elem "inbound-via-relayed" (ruleTags mixedConfig); true) + (assert (ruleByTag mixedConfig "inbound-via-local-exit").inboundTag == [ "local-exit" ]; true) + (assert (ruleByTag mixedConfig "inbound-via-local-exit").outboundTag == "direct"; true) + + # Two listeners can leave through two different servers: the pinned one + # gets its own rule, the default one rides the final rule. + (assert (ruleByTag pinnedConfig "inbound-via-through-de").outboundTag == "de-vps"; true) + (assert (ruleByTag pinnedConfig "inbound-final").outboundTag == "nl-vps"; true) + # Pinned outbounds are injected at start time, not baked into the template, + # and chaining through the local proxy is not needed for either of them. + (assert !hasOutbound pinnedConfig "proxy"; true) + (assert outboundTags pinnedConfig == [ "direct" "block" ]; true) + # Only referenced outbounds are rendered, so the sing-box-only one is fine. + ( + assert + map (ob: ob.tag) pinnedFixture.config.services.proxy-suite.proxy.outbounds == [ + "nl-vps" + "de-vps" + "unused" + ]; + true + ) + + # The final rule always comes last. + (assert lib.last (ruleTags relayConfig) == "inbound-final"; true) + (assert lib.last (ruleTags mixedConfig) == "inbound-final"; true) + + # Without zapret running there is nothing to route around it. + (assert !builtins.elem "inbound-zapret-direct-domain" (ruleTags relayConfig); true) + + # The spec carries secret paths, never their contents. + (assert builtins.length relaySpec.listeners == 1; true) + (assert (builtins.head relaySpec.listeners).tag == "vless-in"; true) + (assert (builtins.head relaySpec.listeners).listen == "::"; true) + ( + assert + (builtins.head (builtins.head relaySpec.listeners).users).uuidFile == "/run/secrets/uuid"; + true + ) + (assert (builtins.head relaySpec.listeners).reality.privateKeyFile == "/run/secrets/reality-key"; true) + (assert relaySpec.shareLinks; true) + + # Firewall: TCP for every listener, UDP only where the protocol uses it. + ( + assert + lib.sort lib.lessThan firewallFixture.config.networking.firewall.allowedTCPPorts == [ + 443 + 8388 + ]; + true + ) + (assert firewallFixture.config.networking.firewall.allowedUDPPorts == [ 8388 ]; true) + # A loopback-bound listener is fronted on this host; opening its port would + # expose what the arrangement hides. + (assert wsListener.port == 10002 && wsListener.sharePort == 443; true) + (assert noFirewallFixture.config.networking.firewall.allowedTCPPorts == [ ]; true) + + # The unit exists, and only waits on the client stack when it relays. + (assert (service relayFixture).wantedBy == [ "multi-user.target" ]; true) + (assert builtins.elem "proxy-suite-socks.service" (service relayFixture).after; true) + (assert !builtins.elem "proxy-suite-socks.service" (service exitFixture).after; true) + # Not `requires`: direct-routed listeners keep serving if the client is down. + (assert (service relayFixture).requires == [ ]; true) + + ] + ++ failing; +in +{ + inherit assertions; +} diff --git a/nix/checks/ssh-proxy.nix b/nix/checks/ssh-proxy.nix index a08787c..5d59eeb 100644 --- a/nix/checks/ssh-proxy.nix +++ b/nix/checks/ssh-proxy.nix @@ -10,7 +10,23 @@ let generated = import ./read-generated.nix; - sshOnlySingBox = evalProxySuite [ + testHostKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + + # The socks start script always passes proxy.tproxy.proxyMark as the routing + # mark, so an expected outbound has to carry it to match byte for byte. + markOf = fixture: fixture.config.services.proxy-suite.proxy.tproxy.proxyMark; + + # writeText paths are content-addressed, so asserting the store path appears + # in the start script pins the exact generated JSON without reading it back. + # The context has to go, or the check derivation refuses to mention the path. + expectedOutboundFile = + backend: value: + builtins.unsafeDiscardStringContext "${ + pkgs.writeText "proxy-suite-ob-ssh-proxy-${backend}.json" (builtins.toJSON value) + }"; + + # SingBox dials SSH natively: no unit, no local SOCKS listener. + sshNativeSingBox = evalProxySuite [ { system.stateVersion = "26.05"; services.proxy-suite = { @@ -20,13 +36,8 @@ let user = "root"; host = "ssh.example.com"; asOutbound = true; - serviceUser = "proxy"; identityFile = "/run/secrets/ssh-key"; - knownHostsFile = "/run/secrets/ssh-known-hosts"; - extraArgs = [ - "-o" - "ServerAliveInterval=30" - ]; + hostKey = [ testHostKey ]; }; proxy = { enable = true; @@ -35,17 +46,92 @@ let }; } ]; - sshOnlySingBoxStart = generated.readDerivation ( - sshOnlySingBox.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + sshNativeSingBoxStart = generated.readDerivation ( + sshNativeSingBox.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + expectedNativeSingBoxOutbound = expectedOutboundFile "sing-box" { + type = "ssh"; + tag = "ssh-proxy"; + server = "ssh.example.com"; + server_port = 22; + user = "root"; + private_key_path = "/run/secrets/ssh-key"; + host_key = [ testHostKey ]; + routing_mark = markOf sshNativeSingBox; + }; + + # hostKeyFile is read at start time, so the keys must be injected by the + # start script rather than baked into the outbound JSON. + sshHostKeyFile = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + sshProxy = { + enable = true; + user = "root"; + host = "ssh.example.com"; + sshPort = 2222; + asOutbound = true; + hostKeyFile = "/run/secrets/ssh-known-hosts"; + }; + proxy = { + enable = true; + singBox.enable = true; + }; + }; + } + ]; + sshHostKeyFileStart = generated.readDerivation ( + sshHostKeyFile.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + + # asOutbound = false is a standalone tunnel no backend knows about, so the + # OpenSSH unit is still created even on SingBox. + sshStandalone = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + sshProxy = { + enable = true; + user = "root"; + host = "ssh.example.com"; + asOutbound = false; + serviceUser = "proxy"; + identityFile = "/run/secrets/ssh-key"; + knownHostsFile = "/run/secrets/ssh-known-hosts"; + extraArgs = [ + "-o" + "IPQoS=throughput" + ]; + }; + proxy = { + enable = true; + singBox.enable = true; + outbounds = [ + { + tag = "static"; + url = "http://proxy.example.com:8080"; + } + ]; + }; + }; + } + ]; + standaloneService = sshStandalone.config.systemd.services."proxy-suite-ssh-proxy"; + standaloneStartScript = generated.readDerivation standaloneService.serviceConfig.ExecStart; + sshStandaloneStart = generated.readDerivation ( + sshStandalone.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart ); - sshService = sshOnlySingBox.config.systemd.services."proxy-suite-ssh-proxy"; - sshStartScript = generated.readDerivation sshService.serviceConfig.ExecStart; unchanged = evalProxySuite [ baseModule ]; unchangedStart = generated.readDerivation ( unchanged.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart ); + # XRay has no SSH outbound, so it keeps the unit and proxies through its + # local SOCKS5 listener, with domainStrategy mapped onto sockopt. sshXray = evalProxySuite [ { system.stateVersion = "26.05"; @@ -56,6 +142,7 @@ let user = "proxy"; host = "ssh.example.com"; asOutbound = true; + domainStrategy = "prefer_ipv4"; }; proxy = { enable = true; @@ -67,6 +154,20 @@ let sshXrayStart = generated.readDerivation ( sshXray.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart ); + xrayService = sshXray.config.systemd.services."proxy-suite-ssh-proxy"; + xrayStartScript = generated.readDerivation xrayService.serviceConfig.ExecStart; + expectedXrayOutbound = expectedOutboundFile "xray" { + protocol = "socks"; + tag = "ssh-proxy"; + settings = { + address = "127.0.0.1"; + port = 1091; + }; + streamSettings.sockopt = { + mark = markOf sshXray; + domainStrategy = "UseIPv4v6"; + }; + }; sshHybrid = evalProxySuite [ { @@ -78,6 +179,7 @@ let user = "proxy"; host = "ssh.example.com"; asOutbound = true; + hostKey = [ testHostKey ]; }; proxy = { enable = true; @@ -90,6 +192,15 @@ let sshHybridStart = generated.readDerivation ( sshHybrid.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart ); + expectedHybridOutbound = expectedOutboundFile "hybrid" { + type = "ssh"; + tag = "ssh-proxy"; + server = "ssh.example.com"; + server_port = 22; + user = "proxy"; + host_key = [ testHostKey ]; + routing_mark = markOf sshHybrid; + }; sshSelector = evalProxySuite [ { @@ -101,6 +212,7 @@ let user = "proxy"; host = "ssh.example.com"; asOutbound = true; + hostKey = [ testHostKey ]; }; proxy = { enable = true; @@ -159,6 +271,7 @@ let user = "proxy"; host = "ssh.example.com"; asOutbound = true; + hostKey = [ testHostKey ]; }; proxy = { enable = true; @@ -183,6 +296,7 @@ let user = "proxy"; host = "ssh.example.com"; asOutbound = true; + hostKey = [ testHostKey ]; }; } { @@ -190,6 +304,7 @@ let sshProxy = { enable = true; asOutbound = true; + hostKey = [ testHostKey ]; }; proxy = { enable = true; @@ -203,6 +318,7 @@ let user = "proxy"; host = "ssh.example.com"; asOutbound = true; + hostKey = [ testHostKey ]; }; proxy = { enable = true; @@ -215,45 +331,127 @@ let ]; }; } + # SingBox verifies host keys by value, so an empty hostKey would silently + # accept any key. + { + enable = true; + sshProxy = { + enable = true; + user = "proxy"; + host = "ssh.example.com"; + asOutbound = true; + }; + proxy = { + enable = true; + singBox.enable = true; + }; + } ]; assertions = [ ( - assert sshOnlySingBox.config.services.proxy-suite.proxy.outbounds == [ ]; + assert sshNativeSingBox.config.services.proxy-suite.proxy.outbounds == [ ]; true ) + # No OpenSSH unit and no ordering against one: sing-box dials SSH in-process. ( - assert sshOnlySingBox.config.systemd.services ? "proxy-suite-ssh-proxy"; + assert !(sshNativeSingBox.config.systemd.services ? "proxy-suite-ssh-proxy"); true ) ( assert - sshOnlySingBox.config.systemd.services."proxy-suite-socks".after == [ + sshNativeSingBox.config.systemd.services."proxy-suite-socks".after == [ "network-online.target" - "proxy-suite-ssh-proxy.service" ]; true ) ( - assert pkgs.lib.hasInfix "ssh-proxy" sshOnlySingBoxStart; + assert + sshNativeSingBox.config.systemd.services."proxy-suite-socks".wants == [ + "network-online.target" + ]; true ) ( - assert pkgs.lib.hasInfix "proxy-suite-ob-ssh-proxy-sing-box.json" sshOnlySingBoxStart; + assert pkgs.lib.hasInfix expectedNativeSingBoxOutbound sshNativeSingBoxStart; + true + ) + # The global local-resolve route rule is gone; the native outbound resolves. + ( + assert !(pkgs.lib.hasInfix "\"resolve\"" sshNativeSingBoxStart); + true + ) + + # Non-default port has to be looked up as "[host]:port" in known_hosts. + ( + assert pkgs.lib.hasInfix "ssh-keygen -F '[ssh.example.com]:2222'" sshHostKeyFileStart; true ) ( - assert pkgs.lib.hasInfix "ServerAliveInterval=30" sshStartScript; + assert pkgs.lib.hasInfix "'.host_key = \$hk'" sshHostKeyFileStart; true ) ( - assert sshService.serviceConfig.User == "proxy"; + assert pkgs.lib.hasInfix "/run/secrets/ssh-known-hosts" sshHostKeyFileStart; + true + ) + # The keys must not be baked into the store-resident outbound JSON. + ( + assert !(pkgs.lib.hasInfix "host_key" (builtins.toJSON sshHostKeyFile.config.services.proxy-suite.sshProxy.hostKey)); + true + ) + + # Standalone tunnel: unit is created, but nothing is wired as an outbound. + ( + assert sshStandalone.config.systemd.services ? "proxy-suite-ssh-proxy"; true ) ( - assert !(sshService.serviceConfig ? SocketMark); + assert !(pkgs.lib.hasInfix "ssh-proxy" sshStandaloneStart); true ) + ( + assert standaloneService.serviceConfig.User == "proxy"; + true + ) + ( + assert !(standaloneService.serviceConfig ? SocketMark); + true + ) + # Hardening: a half-open tunnel must be detected and always restarted. + ( + assert standaloneService.serviceConfig.Restart == "always"; + true + ) + ( + assert standaloneService.serviceConfig.LimitNOFILE == 65536; + true + ) + ( + assert standaloneService.startLimitIntervalSec == 0; + true + ) + ( + assert pkgs.lib.hasInfix "ServerAliveInterval=15" standaloneStartScript; + true + ) + ( + assert pkgs.lib.hasInfix "ServerAliveCountMax=3" standaloneStartScript; + true + ) + ( + assert pkgs.lib.hasInfix "ConnectTimeout=10" standaloneStartScript; + true + ) + ( + assert pkgs.lib.hasInfix "IPQoS=throughput" standaloneStartScript; + true + ) + ( + assert pkgs.lib.hasInfix "UserKnownHostsFile=/run/secrets/ssh-known-hosts" standaloneStartScript; + true + ) + ( assert !(unchanged.config.systemd.services ? "proxy-suite-ssh-proxy"); true @@ -262,18 +460,56 @@ let assert !(pkgs.lib.hasInfix "ssh-proxy" unchangedStart); true ) + + # XRay keeps the unit and orders the backend behind it. ( - assert sshXray.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart != null; + assert sshXray.config.systemd.services ? "proxy-suite-ssh-proxy"; true ) ( - assert pkgs.lib.hasInfix "proxy-suite-ob-ssh-proxy-xray.json" sshXrayStart; + assert + sshXray.config.systemd.services."proxy-suite-socks".after == [ + "network-online.target" + "proxy-suite-ssh-proxy.service" + ]; + true + ) + ( + assert + sshXray.config.systemd.services."proxy-suite-socks".wants == [ + "network-online.target" + "proxy-suite-ssh-proxy.service" + ]; + true + ) + ( + assert xrayService.serviceConfig.Restart == "always"; + true + ) + ( + assert pkgs.lib.hasInfix "ServerAliveInterval=15" xrayStartScript; + true + ) + # prefer_ipv4 maps onto XRay's "IPv4 first, fall back to IPv6". + ( + assert pkgs.lib.hasInfix expectedXrayOutbound sshXrayStart; + true + ) + + # Hybrid routes the tunnel through sing-box, so it gets the native shape. + ( + assert !(sshHybrid.config.systemd.services ? "proxy-suite-ssh-proxy"); true ) ( assert pkgs.lib.hasInfix "_proxy_suite_add_sing_box_ob" sshHybridStart; true ) + ( + assert pkgs.lib.hasInfix expectedHybridOutbound sshHybridStart; + true + ) + ( assert pkgs.lib.hasInfix "selector" sshSelectorStart; true diff --git a/nix/checks/xray-backend-features/fixtures.nix b/nix/checks/xray-backend-features/fixtures.nix index b937f41..d48120f 100644 --- a/nix/checks/xray-backend-features/fixtures.nix +++ b/nix/checks/xray-backend-features/fixtures.nix @@ -15,6 +15,7 @@ let pureXrayEnabled = true; singBoxCfg = null; proxyCfg = null; + sshProxyCfg = null; hybridEnabled = null; collapseNamedOutbounds = null; selectionMode = null; diff --git a/nix/options-doc.nix b/nix/options-doc.nix index 7700ed8..0da6eef 100644 --- a/nix/options-doc.nix +++ b/nix/options-doc.nix @@ -24,6 +24,11 @@ let sanitizeConfigForDocs = config: builtins.removeAttrs config [ "singBox" ] + // lib.optionalAttrs ((config.proxyInbounds or { }) ? package) { + proxyInbounds = config.proxyInbounds // { + package = xrayPackagePlaceholder; + }; + } // { proxy = (config.proxy or { }) // { singBox = diff --git a/nix/readme-doc.nix b/nix/readme-doc.nix index 5d1afb1..8556896 100644 --- a/nix/readme-doc.nix +++ b/nix/readme-doc.nix @@ -38,7 +38,14 @@ let packages cfg ; - inherit (configs) tproxyFile tunFile perAppTunFile routeModeRulesFile; + inherit (configs) + tproxyFile + tunFile + perAppTunFile + routeModeRulesFile + proxyInboundsFile + proxyInboundsSpecFile + ; inherit (nftr) perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile ip nft; }; in diff --git a/pkgs/proxy-ctl-lib.sh b/pkgs/proxy-ctl-lib.sh index 71c0bbe..6153c14 100644 --- a/pkgs/proxy-ctl-lib.sh +++ b/pkgs/proxy-ctl-lib.sh @@ -2,6 +2,8 @@ ALL_SERVICES=( proxy-suite-socks proxy-suite-tproxy proxy-suite-tun + proxy-suite-inbounds + proxy-suite-ssh-proxy proxy-suite-tg-ws-proxy proxy-suite-zapret-vm-exempt zapret-discord-youtube @@ -49,6 +51,7 @@ _usage() { echo " proxy on|off enable/disable the proxy backend stack" echo " tproxy on|off enable/disable TProxy transparent mode" echo " tun on|off enable/disable TUN mode" + echo " ssh on|off enable/disable the SSH SOCKS5 proxy" echo " awg list|status [profile] list profiles or show AmneziaWG status" echo " awg on start an AmneziaWG profile" echo " awg off [profile] stop one or all active AmneziaWG profiles" @@ -64,6 +67,9 @@ _usage() { echo " wrap -- run a command via a perAppRouting profile" echo " subscription list show subscriptions, cache age, and proxy count" echo " subscription update force-refresh all subscription caches and restart active proxy services" + echo " inbounds [list] list server inbounds and their state" + echo " inbounds link [user] print the client share link for an inbound" + echo " inbounds qr [user] print the client share link as a QR code" exit "$status" } @@ -363,6 +369,8 @@ cmd_route_mode() { RESTART_SERVICES=( proxy-suite-tproxy proxy-suite-tun + proxy-suite-inbounds + proxy-suite-ssh-proxy proxy-suite-tg-ws-proxy zapret-discord-youtube ) @@ -601,3 +609,73 @@ cmd_subscription() { ;; esac } + +_ensure_inbounds() { + if [ "${INBOUNDS_ENABLED:-0}" != "1" ]; then + echo "proxyInbounds is not enabled in services.proxy-suite.proxyInbounds." + exit 1 + fi +} + +# Links carry listener credentials, so the file is root/group-only. Say so +# rather than leaking a bare permission error. +_inbound_links() { + if [ ! -f "$INBOUNDS_LINKS_FILE" ]; then + echo "No share links available. Is proxy-suite-inbounds running, and is proxyInbounds.shareLinks enabled?" >&2 + exit 1 + fi + if [ ! -r "$INBOUNDS_LINKS_FILE" ]; then + echo "Share links are not readable by this user. Enable userControl, or run as root." >&2 + exit 1 + fi + cat "$INBOUNDS_LINKS_FILE" +} + +_inbound_link_for() { + local tag="$1" user="${2:-}" matches count + matches="$(_inbound_links | jq -c --arg tag "$tag" --arg user "$user" '[.[] | select(.tag == $tag) | select($user == "" or .user == $user)]')" + count="$(jq 'length' <<< "$matches")" + if [ "$count" -eq 0 ]; then + echo "Unknown inbound, or no share link for it: $tag" >&2 + exit 1 + fi + if [ "$count" -ne 1 ]; then + echo "Multiple users match '$tag'; specify one of:" >&2 + jq -r '.[].user' <<< "$matches" | sed 's/^/ /' >&2 + exit 1 + fi + jq -r '.[0].link' <<< "$matches" +} + +cmd_inbounds() { + _ensure_inbounds + case "${1:-list}" in + list) + echo "proxy-suite inbounds:" + printf " %-24s %-16s %-14s %-8s %s\n" TAG USER TYPE PORT STATE + local state + state="$(systemctl is-active proxy-suite-inbounds 2>/dev/null || true)" + _inbound_links \ + | jq -r --arg state "$state" '.[] | "\(.tag)\t\(.user)\t\(.type)\t\(.port)\t\($state)"' \ + | awk -F'\t' '{printf " %-24s %-16s %-14s %-8s %s\n", $1, $2, $3, $4, $5}' + ;; + link) + if [ -z "${2:-}" ]; then + echo "Usage: proxy-ctl inbounds link [user]" >&2 + exit 1 + fi + _inbound_link_for "$2" "${3:-}" + ;; + qr) + if [ -z "${2:-}" ]; then + echo "Usage: proxy-ctl inbounds qr [user]" >&2 + exit 1 + fi + _inbound_link_for "$2" "${3:-}" | qrencode -t ANSIUTF8 + ;; + *) + echo "Usage: proxy-ctl inbounds [list|link [user]|qr [user]]" >&2 + exit 1 + ;; + esac +} diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 9facef5..ffe7c76 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -19,6 +19,8 @@ routeModeStateFile, defaultRouteMode, amneziaWgProfileNamesFile, + inboundsEnabled, + inboundsLinksFile, }: let @@ -41,6 +43,8 @@ let ROUTE_MODE_STATE_FILE = routeModeStateFile; DEFAULT_ROUTE_MODE = defaultRouteMode; AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile; + INBOUNDS_ENABLED = inboundsEnabled; + INBOUNDS_LINKS_FILE = inboundsLinksFile; }; in pkgs.symlinkJoin { @@ -67,6 +71,7 @@ pkgs.symlinkJoin { pkgs.gnugrep pkgs.jq pkgs.proxychains-ng + pkgs.qrencode pkgs.systemd ] }" \ @@ -84,6 +89,8 @@ pkgs.symlinkJoin { --set PROXYCHAINS_QUIET_ARG ${lib.escapeShellArg (lib.removeSuffix " " proxychainsQuietArg)} \ --set ROUTE_MODE_STATE_FILE ${lib.escapeShellArg routeModeStateFile} \ --set DEFAULT_ROUTE_MODE ${lib.escapeShellArg defaultRouteMode} \ - --set AWG_PROFILES_FILE ${lib.escapeShellArg (toString amneziaWgProfileNamesFile)} + --set AWG_PROFILES_FILE ${lib.escapeShellArg (toString amneziaWgProfileNamesFile)} \ + --set INBOUNDS_ENABLED ${lib.escapeShellArg inboundsEnabled} \ + --set INBOUNDS_LINKS_FILE ${lib.escapeShellArg inboundsLinksFile} ''; } diff --git a/pkgs/proxy-ctl.sh b/pkgs/proxy-ctl.sh index d92d627..aa4cfd7 100644 --- a/pkgs/proxy-ctl.sh +++ b/pkgs/proxy-ctl.sh @@ -39,6 +39,10 @@ case "$cmd" in cmd_mode_toggle proxy-suite-tun on "${1:-}" ;; + ssh) + cmd_mode_toggle proxy-suite-ssh-proxy on "${1:-}" ssh + ;; + awg) cmd_awg "$@" ;; @@ -77,6 +81,10 @@ case "$cmd" in cmd_wrap "$@" ;; + inbounds) + cmd_inbounds "$@" + ;; + subscription) cmd_subscription "$@" ;; diff --git a/scripts/build-inbound.py b/scripts/build-inbound.py new file mode 100644 index 0000000..d953a1b --- /dev/null +++ b/scripts/build-inbound.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Read an inbound spec file and emit XRay inbounds plus client share links.""" + +import argparse +import json +import sys + +from proxy_inbound import build_inbounds + + +def main() -> None: + ap = argparse.ArgumentParser( + description="Render services.proxy-suite.proxyInbounds into XRay inbounds." + ) + ap.add_argument("--spec", required=True, help="path to the generated inbound spec JSON") + ap.add_argument( + "--server-address", + default="", + dest="server_address", + help="public address used in generated share links", + ) + args = ap.parse_args() + + with open(args.spec, encoding="utf-8") as handle: + spec = json.load(handle) + + server_address = args.server_address or spec.get("serverAddress") or "" + if spec.get("shareLinks", True) and not server_address: + print("error: no server address available for share links", file=sys.stderr) + sys.exit(1) + + try: + result = build_inbounds(spec, server_address) + except (ValueError, OSError) as exc: + print(f"error: {exc}", file=sys.stderr) + sys.exit(1) + + print(json.dumps(result)) + + +if __name__ == "__main__": + main() diff --git a/scripts/proxy_inbound.py b/scripts/proxy_inbound.py new file mode 100644 index 0000000..beeb0b8 --- /dev/null +++ b/scripts/proxy_inbound.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python3 +"""Render server-side proxy inbounds and their client share links. + +The input spec is backend-neutral: it mirrors the +services.proxy-suite.proxyInbounds option tree, with secrets given as file +paths that are read here rather than at Nix evaluation time. Only XRay is +rendered today; a render_sing_box_inbound would sit beside render_xray_inbound +without changing the spec or the link generator. +""" + +import base64 +import json +import urllib.parse + +UUID_TYPES = ("vless", "vmess") +PASSWORD_TYPES = ("trojan", "shadowsocks", "socks", "http") +UDP_TYPES = ("shadowsocks", "socks") + +TRANSPORT_SETTINGS_KEY = { + "ws": "wsSettings", + "grpc": "grpcSettings", + "httpupgrade": "httpupgradeSettings", + "xhttp": "xhttpSettings", +} + + +def _read_secret(path: str) -> str: + with open(path, encoding="utf-8") as handle: + return handle.read().strip() + + +def _resolve(literal: str | None, path: str | None, what: str, tag: str) -> str: + """Take the inline value, or the contents of the file holding it.""" + if literal is not None: + return literal + if path is not None: + value = _read_secret(path) + if not value: + raise ValueError(f"listener '{tag}': {what} file '{path}' is empty") + return value + raise ValueError(f"listener '{tag}': no {what} configured") + + +def _user_secret(user: dict, listener_type: str, tag: str) -> str: + if listener_type in UUID_TYPES: + return _resolve(user.get("uuid"), user.get("uuidFile"), "uuid", tag) + return _resolve(user.get("password"), user.get("passwordFile"), "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("=") + + +def _share_port(listener: dict) -> int: + """Port clients dial, which differs from the bound port when something in + front of the listener (an nginx vhost, a port mapping) owns the public one.""" + return listener.get("sharePort") or listener["port"] + + +def _clients(listener: dict, tag: str) -> list[dict]: + clients = [] + for index, user in enumerate(listener["users"]): + secret = _user_secret(user, listener["type"], tag) + email = user.get("name") or f"{tag}-{index}" + if listener["type"] in UUID_TYPES: + client = {"id": secret, "email": email} + if listener["type"] == "vless" and listener.get("flow"): + client["flow"] = listener["flow"] + else: + client = {"password": secret, "email": email} + clients.append(client) + return clients + + +def _accounts(listener: dict, tag: str) -> list[dict]: + accounts = [] + for index, user in enumerate(listener["users"]): + secret = _user_secret(user, listener["type"], tag) + accounts.append({"user": user.get("name") or f"{tag}-{index}", "pass": secret}) + return accounts + + +def _xray_stream(listener: dict, tag: str) -> dict: + transport = listener["transport"] + network = transport["type"] + stream: dict = {"network": network} + + settings_key = TRANSPORT_SETTINGS_KEY.get(network) + if settings_key == "grpcSettings": + stream[settings_key] = {"serviceName": transport["serviceName"]} + elif settings_key is not None: + settings = {"path": transport["path"]} + if transport.get("host"): + settings["host"] = transport["host"] + if network == "xhttp" and transport.get("mode"): + settings["mode"] = transport["mode"] + stream[settings_key] = settings + + reality = listener["reality"] + tls = listener["tls"] + if reality["enable"]: + stream["security"] = "reality" + stream["realitySettings"] = { + "show": False, + "dest": reality["dest"], + "serverNames": reality["serverNames"], + "privateKey": _resolve( + reality.get("privateKey"), + reality.get("privateKeyFile"), + "reality private key", + tag, + ), + "shortIds": reality["shortIds"], + } + elif tls["enable"] or listener["type"] == "trojan": + stream["security"] = "tls" + certificate = { + "certificateFile": tls["certificateFile"], + "keyFile": tls["keyFile"], + } + stream["tlsSettings"] = {"certificates": [certificate]} + if tls.get("serverName"): + stream["tlsSettings"]["serverName"] = tls["serverName"] + else: + stream["security"] = "none" + + return stream + + +def render_xray_inbound(listener: dict) -> dict: + """Build one XRay inbound object from a typed listener spec.""" + tag = listener["tag"] + listener_type = listener["type"] + + if listener_type in UUID_TYPES: + settings: dict = {"clients": _clients(listener, tag)} + if listener_type == "vless": + settings["decryption"] = "none" + elif listener_type == "trojan": + settings = {"clients": _clients(listener, tag)} + elif listener_type == "shadowsocks": + settings = {"method": listener["method"], "network": "tcp,udp"} + users = listener["users"] + if len(users) == 1: + settings["password"] = _user_secret(users[0], listener_type, tag) + else: + # Multi-user shadowsocks needs the 2022 ciphers. + settings["clients"] = _clients(listener, tag) + elif listener_type in ("socks", "http"): + settings = {"auth": "password", "accounts": _accounts(listener, tag)} + if listener_type == "socks": + settings["udp"] = True + else: + raise ValueError(f"listener '{tag}': unsupported type '{listener_type}'") + + return { + "tag": tag, + "listen": listener["listen"], + "port": listener["port"], + "protocol": listener_type, + "settings": settings, + "streamSettings": _xray_stream(listener, tag), + # routeOnly keeps the sniffed domain for routing decisions without + # rewriting the destination the client actually asked for. + "sniffing": { + "enabled": True, + "destOverride": ["http", "tls", "quic"], + "routeOnly": True, + }, + } + + +def _link_transport_params(listener: dict) -> dict: + transport = listener["transport"] + network = transport["type"] + # "raw" is XRay's current name for plain TCP; share links still say "tcp", + # which is what every client (and our own outbound parser) understands. + params: dict = {"type": "tcp" if network == "raw" else network} + if network == "grpc": + params["serviceName"] = transport["serviceName"] + elif network in ("ws", "httpupgrade", "xhttp"): + params["path"] = transport["path"] + if transport.get("host"): + params["host"] = transport["host"] + if network == "xhttp" and transport.get("mode"): + params["mode"] = transport["mode"] + return params + + +def _link_security_params(listener: dict, server_address: str) -> dict: + reality = listener["reality"] + tls = listener["tls"] + if reality["enable"]: + if not reality.get("publicKey"): + raise ValueError( + f"listener '{listener['tag']}': reality.publicKey is required " + "to generate a share link" + ) + server_names = reality["serverNames"] + short_ids = reality["shortIds"] + params = { + "security": "reality", + "pbk": reality["publicKey"], + "sni": server_names[0] if server_names else server_address, + "fp": "chrome", + } + if short_ids and short_ids[0]: + params["sid"] = short_ids[0] + return params + if tls["enable"] or listener["type"] == "trojan": + return { + "security": "tls", + "sni": tls.get("serverName") or server_address, + "fp": "chrome", + } + return {"security": "none"} + + +def _vmess_link(listener: dict, secret: str, server_address: str, label: str) -> str: + transport = listener["transport"] + reality = listener["reality"] + tls = listener["tls"] + blob = { + "v": "2", + "ps": label, + "add": server_address, + "port": str(_share_port(listener)), + "id": secret, + "aid": "0", + "scy": "auto", + "net": transport["type"], + "type": "none", + "host": transport.get("host") or "", + "path": transport["path"], + "tls": "tls" if (tls["enable"] or reality["enable"]) else "", + "sni": tls.get("serverName") or server_address, + } + return "vmess://" + _b64(json.dumps(blob, separators=(",", ":"))) + + +def build_share_link(listener: dict, server_address: str, user_index: int = 0) -> str: + """Build the client-facing share URL for a listener.""" + tag = listener["tag"] + listener_type = listener["type"] + users = listener["users"] + if not users: + raise ValueError(f"listener '{tag}': no users to build a share link for") + if user_index < 0 or user_index >= len(users): + raise ValueError(f"listener '{tag}': user index {user_index} is out of range") + + user = users[user_index] + secret = _user_secret(user, listener_type, tag) + user_name = user.get("name") or f"{tag}-{user_index}" + label = f"{tag} ({user_name})" + fragment = urllib.parse.quote(label, safe="") + host = f"[{server_address}]" if ":" in server_address else server_address + endpoint = f"{host}:{_share_port(listener)}" + + if listener_type == "vmess": + return _vmess_link(listener, secret, server_address, label) + + if listener_type == "shadowsocks": + userinfo = _b64(f"{listener['method']}:{secret}") + return f"ss://{userinfo}@{endpoint}#{fragment}" + + if listener_type in ("socks", "http"): + if listener_type == "socks": + 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}" + + params = _link_transport_params(listener) + params.update(_link_security_params(listener, server_address)) + if listener_type == "vless" and listener.get("flow"): + params["flow"] = listener["flow"] + query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote) + return f"{listener_type}://{secret}@{endpoint}?{query}#{fragment}" + + +def build_listener(listener: dict, server_address: str, share_links: bool) -> dict: + """Render one listener into its inbound object and, when possible, a link. + + Raw-JSON listeners are passed through untouched apart from the tag, and get + no share link: proxy-suite does not know what they serve. + """ + tag = listener["tag"] + + 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": []} + + inbound = render_xray_inbound(listener) + links = ( + [build_share_link(listener, server_address, index) for index in range(len(listener["users"]))] + if share_links + else [] + ) + return {"tag": tag, "type": listener["type"], "port": _share_port(listener), "inbound": inbound, "links": links} + + +def build_inbounds(spec: dict, server_address: str) -> dict: + """Render a whole spec into {"inbounds": [...], "links": [...]}.""" + inbounds = [] + links = [] + for listener in spec["listeners"]: + rendered = build_listener(listener, server_address, spec.get("shareLinks", True)) + inbounds.append(rendered["inbound"]) + for index, link in enumerate(rendered["links"]): + user = listener["users"][index] + links.append( + { + "tag": rendered["tag"], + "user": user.get("name") or f"{rendered['tag']}-{index}", + "type": rendered.get("type", ""), + "port": rendered.get("port", 0), + "link": link, + } + ) + return {"inbounds": inbounds, "links": links} diff --git a/scripts/test-build-inbound.py b/scripts/test-build-inbound.py new file mode 100644 index 0000000..9b9f208 --- /dev/null +++ b/scripts/test-build-inbound.py @@ -0,0 +1,454 @@ +#!/usr/bin/env python3 + +import base64 +import json +import os +import tempfile +import unittest +import urllib.parse + +from proxy_inbound import build_inbounds, build_share_link, render_xray_inbound +from proxy_parsing import build_outbound + + +def listener(**overrides): + """A listener spec with the same defaults the Nix option tree renders.""" + spec = { + "tag": "test-in", + "type": "vless", + "port": 443, + "sharePort": None, + "listen": "::", + "via": "direct", + "users": [{"name": "", "uuid": "uuid-1", "uuidFile": None, "password": None, "passwordFile": None}], + "flow": None, + "method": "2022-blake3-aes-128-gcm", + "transport": {"type": "raw", "path": "/", "host": None, "mode": None, "serviceName": ""}, + "tls": {"enable": False, "certificateFile": None, "keyFile": None, "serverName": None}, + "reality": { + "enable": False, + "dest": "www.microsoft.com:443", + "serverNames": [], + "privateKey": None, + "privateKeyFile": None, + "publicKey": None, + "shortIds": [""], + }, + "xrayJson": None, + "jsonFile": None, + } + spec.update(overrides) + return spec + + +def reality(**overrides): + settings = { + "enable": True, + "dest": "www.microsoft.com:443", + "serverNames": ["www.microsoft.com"], + "privateKey": "private-key", + "privateKeyFile": None, + "publicKey": "public-key", + "shortIds": ["0123abcd"], + } + settings.update(overrides) + return settings + + +def link_params(link: str) -> dict: + query = urllib.parse.urlsplit(link).query + return dict(urllib.parse.parse_qsl(query)) + + +class RenderInboundTests(unittest.TestCase): + def test_vless_reality_shape(self): + ib = render_xray_inbound(listener(flow="xtls-rprx-vision", reality=reality())) + self.assertEqual(ib["protocol"], "vless") + self.assertEqual(ib["port"], 443) + self.assertEqual(ib["listen"], "::") + self.assertEqual(ib["settings"]["decryption"], "none") + self.assertEqual(ib["settings"]["clients"][0]["id"], "uuid-1") + self.assertEqual(ib["settings"]["clients"][0]["flow"], "xtls-rprx-vision") + stream = ib["streamSettings"] + self.assertEqual(stream["network"], "raw") + self.assertEqual(stream["security"], "reality") + self.assertEqual(stream["realitySettings"]["privateKey"], "private-key") + self.assertEqual(stream["realitySettings"]["dest"], "www.microsoft.com:443") + self.assertEqual(stream["realitySettings"]["shortIds"], ["0123abcd"]) + # The public key is a client-side concern; it must not leak into the server config. + self.assertNotIn("publicKey", stream["realitySettings"]) + + def test_sniffing_is_route_only(self): + # Domain rules (blockRu) need sniffing, but a server must not rewrite + # the destination its clients asked for. + ib = render_xray_inbound(listener()) + self.assertTrue(ib["sniffing"]["enabled"]) + self.assertTrue(ib["sniffing"]["routeOnly"]) + + def test_secrets_are_read_from_files(self): + with tempfile.TemporaryDirectory() as tmp: + uuid_path = os.path.join(tmp, "uuid") + key_path = os.path.join(tmp, "key") + with open(uuid_path, "w", encoding="utf-8") as handle: + handle.write("file-uuid\n") + with open(key_path, "w", encoding="utf-8") as handle: + handle.write("file-key\n") + + ib = render_xray_inbound( + listener( + users=[{"name": "", "uuid": None, "uuidFile": uuid_path}], + reality=reality(privateKey=None, privateKeyFile=key_path), + ) + ) + self.assertEqual(ib["settings"]["clients"][0]["id"], "file-uuid") + self.assertEqual(ib["streamSettings"]["realitySettings"]["privateKey"], "file-key") + + def test_empty_secret_file_is_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + uuid_path = os.path.join(tmp, "uuid") + with open(uuid_path, "w", encoding="utf-8") as handle: + handle.write("\n") + with self.assertRaisesRegex(ValueError, "is empty"): + render_xray_inbound(listener(users=[{"uuid": None, "uuidFile": uuid_path}])) + + def test_ws_transport(self): + ib = render_xray_inbound( + listener( + transport={"type": "ws", "path": "/download", "host": "cdn.example.com", "serviceName": ""}, + tls={ + "enable": True, + "certificateFile": "/cert.pem", + "keyFile": "/key.pem", + "serverName": "cdn.example.com", + }, + ) + ) + stream = ib["streamSettings"] + self.assertEqual(stream["network"], "ws") + self.assertEqual(stream["wsSettings"], {"path": "/download", "host": "cdn.example.com"}) + self.assertEqual(stream["security"], "tls") + self.assertEqual( + stream["tlsSettings"]["certificates"][0], + {"certificateFile": "/cert.pem", "keyFile": "/key.pem"}, + ) + + def test_grpc_transport(self): + ib = render_xray_inbound( + listener(transport={"type": "grpc", "path": "/", "host": None, "serviceName": "GunService"}) + ) + self.assertEqual(ib["streamSettings"]["grpcSettings"], {"serviceName": "GunService"}) + + def test_trojan_forces_tls(self): + ib = render_xray_inbound( + listener( + type="trojan", + users=[{"name": "", "password": "pw", "passwordFile": None}], + tls={ + "enable": False, + "certificateFile": "/cert.pem", + "keyFile": "/key.pem", + "serverName": None, + }, + ) + ) + self.assertEqual(ib["settings"]["clients"][0]["password"], "pw") + self.assertEqual(ib["streamSettings"]["security"], "tls") + + def test_shadowsocks_single_user_uses_password(self): + ib = render_xray_inbound( + listener(type="shadowsocks", users=[{"name": "", "password": "psk", "passwordFile": None}]) + ) + self.assertEqual(ib["settings"]["password"], "psk") + 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}, + ], + ) + ) + self.assertNotIn("password", ib["settings"]) + self.assertEqual(len(ib["settings"]["clients"]), 2) + + def test_socks_accounts_and_udp(self): + ib = render_xray_inbound( + listener(type="socks", users=[{"name": "me", "password": "pw", "passwordFile": None}]) + ) + self.assertEqual(ib["settings"]["accounts"], [{"user": "me", "pass": "pw"}]) + self.assertTrue(ib["settings"]["udp"]) + + def test_unsupported_type_fails(self): + with self.assertRaisesRegex(ValueError, "unsupported type"): + render_xray_inbound(listener(type="hysteria2")) + + +class ShareLinkTests(unittest.TestCase): + def test_vless_reality_link(self): + link = build_share_link( + listener(flow="xtls-rprx-vision", reality=reality()), "vpn.example.com" + ) + self.assertTrue(link.startswith("vless://uuid-1@vpn.example.com:443?")) + params = link_params(link) + self.assertEqual(params["security"], "reality") + self.assertEqual(params["pbk"], "public-key") + self.assertEqual(params["sid"], "0123abcd") + self.assertEqual(params["sni"], "www.microsoft.com") + self.assertEqual(params["flow"], "xtls-rprx-vision") + self.assertEqual(params["type"], "tcp") + + 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") + + def test_empty_short_id_is_omitted(self): + link = build_share_link(listener(reality=reality(shortIds=[""])), "vpn.example.com") + self.assertNotIn("sid=", link) + + def test_ipv6_server_address_is_bracketed(self): + link = build_share_link(listener(reality=reality()), "2001:db8::1") + self.assertIn("@[2001:db8::1]:443?", link) + + def test_label_becomes_fragment(self): + spec = listener(reality=reality()) + spec["users"][0]["name"] = "my phone" + link = build_share_link(spec, "vpn.example.com") + self.assertTrue(link.endswith("#test-in%20%28my%20phone%29")) + + def test_multi_user_links_select_each_user(self): + spec = listener( + users=[ + {"name": "phone", "uuid": "uuid-phone", "password": None, "passwordFile": None}, + {"name": "laptop", "uuid": "uuid-laptop", "password": None, "passwordFile": None}, + ] + ) + phone = build_share_link(spec, "vpn.example.com", 0) + laptop = build_share_link(spec, "vpn.example.com", 1) + self.assertTrue(phone.startswith("vless://uuid-phone@")) + self.assertTrue(laptop.startswith("vless://uuid-laptop@")) + self.assertTrue(phone.endswith("#test-in%20%28phone%29")) + self.assertTrue(laptop.endswith("#test-in%20%28laptop%29")) + + def test_multi_user_password_links_select_each_account(self): + spec = listener( + type="socks", + users=[ + {"name": "phone", "password": "pw-phone", "uuid": None, "uuidFile": None}, + {"name": "laptop", "password": "pw-laptop", "uuid": None, "uuidFile": None}, + ], + ) + link = build_share_link(spec, "vpn.example.com", 1) + userinfo = link[len("socks://") :].split("@", 1)[0] + decoded = base64.urlsafe_b64decode(userinfo + "=" * (-len(userinfo) % 4)).decode() + self.assertEqual(decoded, "laptop:pw-laptop") + + def test_vmess_link_blob(self): + spec = listener( + type="vmess", + transport={"type": "ws", "path": "/v", "host": "cdn.example.com", "serviceName": ""}, + tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": "cdn.example.com"}, + ) + link = build_share_link(spec, "vpn.example.com") + self.assertTrue(link.startswith("vmess://")) + payload = link[len("vmess://") :] + payload += "=" * (-len(payload) % 4) + blob = json.loads(base64.urlsafe_b64decode(payload)) + self.assertEqual(blob["add"], "vpn.example.com") + self.assertEqual(blob["id"], "uuid-1") + self.assertEqual(blob["net"], "ws") + self.assertEqual(blob["tls"], "tls") + + def test_shadowsocks_link_is_sip002(self): + spec = listener(type="shadowsocks", 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") + + +class RoundTripTests(unittest.TestCase): + """A generated link must parse back into a working outbound. + + This is what makes the links usable, including by proxy-suite itself as a + client, so the two halves are pinned against each other here. + """ + + def test_vless_reality_round_trip(self): + link = build_share_link( + listener(flow="xtls-rprx-vision", reality=reality()), "vpn.example.com" + ) + ob = build_outbound(link, "round-trip", backend="xray") + self.assertEqual(ob["protocol"], "vless") + settings = ob["settings"] + self.assertEqual(settings["address"], "vpn.example.com") + self.assertEqual(settings["port"], 443) + self.assertEqual(settings["id"], "uuid-1") + self.assertEqual(settings["flow"], "xtls-rprx-vision") + rs = ob["streamSettings"]["realitySettings"] + self.assertEqual(rs["publicKey"], "public-key") + self.assertEqual(rs["shortId"], "0123abcd") + self.assertEqual(rs["serverName"], "www.microsoft.com") + + def test_vless_ws_tls_round_trip(self): + link = build_share_link( + listener( + transport={"type": "ws", "path": "/download", "host": "cdn.example.com", "serviceName": ""}, + tls={ + "enable": True, + "certificateFile": "/c", + "keyFile": "/k", + "serverName": "cdn.example.com", + }, + ), + "vpn.example.com", + ) + ob = build_outbound(link, "round-trip", backend="sing-box") + self.assertEqual(ob["type"], "vless") + self.assertEqual(ob["transport"]["type"], "ws") + self.assertEqual(ob["transport"]["path"], "/download") + self.assertEqual(ob["tls"]["server_name"], "cdn.example.com") + + def test_trojan_round_trip(self): + link = build_share_link( + listener( + type="trojan", + users=[{"name": "", "password": "pw", "passwordFile": None}], + tls={"enable": False, "certificateFile": "/c", "keyFile": "/k", "serverName": None}, + ), + "vpn.example.com", + ) + ob = build_outbound(link, "round-trip", backend="sing-box") + self.assertEqual(ob["type"], "trojan") + self.assertEqual(ob["password"], "pw") + + def test_shadowsocks_round_trip(self): + link = build_share_link( + listener(type="shadowsocks", users=[{"name": "", "password": "psk", "passwordFile": None}]), + "vpn.example.com", + ) + ob = build_outbound(link, "round-trip", backend="sing-box") + self.assertEqual(ob["type"], "shadowsocks") + self.assertEqual(ob["method"], "2022-blake3-aes-128-gcm") + self.assertEqual(ob["password"], "psk") + + 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") + self.assertEqual(ob["type"], "vmess") + self.assertEqual(ob["uuid"], "uuid-1") + + +class BuildInboundsTests(unittest.TestCase): + def test_spec_renders_inbounds_and_links(self): + spec = { + "serverAddress": "vpn.example.com", + "shareLinks": True, + "listeners": [ + listener(tag="a", reality=reality()), + listener(tag="b", port=8443, type="socks", users=[{"name": "u", "password": "p"}]), + ], + } + result = build_inbounds(spec, "vpn.example.com") + self.assertEqual([ib["tag"] for ib in result["inbounds"]], ["a", "b"]) + self.assertEqual([entry["tag"] for entry in result["links"]], ["a", "b"]) + self.assertEqual(result["links"][1]["port"], 8443) + + def test_xhttp_mode_reaches_the_inbound_and_the_link(self): + spec = listener( + transport={"type": "xhttp", "path": "/p", "host": None, "mode": "packet-up", "serviceName": ""} + ) + stream = render_xray_inbound(spec)["streamSettings"] + self.assertEqual(stream["xhttpSettings"]["mode"], "packet-up") + # Without it in the link the client picks a mode on its own, which is + # what breaks XHTTP behind an HTTP/1.1 reverse proxy. + self.assertEqual(link_params(build_share_link(spec, "vpn.example.com"))["mode"], "packet-up") + + def test_share_port_overrides_the_bound_port(self): + spec = { + "serverAddress": "vpn.example.com", + "shareLinks": True, + "listeners": [ + listener( + port=10002, + sharePort=443, + listen="127.0.0.1", + tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None}, + transport={"type": "ws", "path": "/vpnjantit", "host": None, "serviceName": ""}, + ) + ], + } + result = build_inbounds(spec, "vpn.example.com") + # The listener still binds where it was told to; only the link moves. + self.assertEqual(result["inbounds"][0]["port"], 10002) + self.assertEqual(result["links"][0]["port"], 443) + link = result["links"][0]["link"] + self.assertTrue(link.startswith("vless://uuid-1@vpn.example.com:443?"), link) + self.assertEqual(link_params(link)["path"], "/vpnjantit") + + def test_spec_emits_one_link_per_user(self): + spec = { + "serverAddress": "vpn.example.com", + "shareLinks": True, + "listeners": [ + listener( + users=[ + {"name": "phone", "uuid": "uuid-phone", "password": None, "passwordFile": None}, + {"name": "laptop", "uuid": "uuid-laptop", "password": None, "passwordFile": None}, + ] + ) + ], + } + result = build_inbounds(spec, "vpn.example.com") + self.assertEqual([entry["user"] for entry in result["links"]], ["phone", "laptop"]) + self.assertTrue(result["links"][1]["link"].startswith("vless://uuid-laptop@")) + + def test_share_links_disabled_emits_no_links(self): + spec = { + "serverAddress": "vpn.example.com", + "shareLinks": False, + "listeners": [listener(reality=reality(publicKey=None))], + } + result = build_inbounds(spec, "vpn.example.com") + self.assertEqual(result["links"], []) + self.assertEqual(len(result["inbounds"]), 1) + + def test_raw_json_listener_passes_through_with_tag(self): + spec = { + "serverAddress": "vpn.example.com", + "shareLinks": True, + "listeners": [ + listener( + tag="raw", + type=None, + xrayJson={"protocol": "dokodemo-door", "tag": "ignored", "port": 8080}, + ) + ], + } + result = build_inbounds(spec, "vpn.example.com") + self.assertEqual(result["inbounds"][0]["protocol"], "dokodemo-door") + self.assertEqual(result["inbounds"][0]["tag"], "raw") + self.assertEqual(result["links"], []) + + def test_json_file_listener_is_read_at_runtime(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "inbound.json") + with open(path, "w", encoding="utf-8") as handle: + json.dump({"protocol": "vless", "port": 2053, "settings": {"clients": []}}, handle) + spec = { + "serverAddress": "vpn.example.com", + "shareLinks": True, + "listeners": [listener(tag="secret-in", type=None, jsonFile=path)], + } + result = build_inbounds(spec, "vpn.example.com") + self.assertEqual(result["inbounds"][0]["tag"], "secret-in") + self.assertEqual(result["inbounds"][0]["port"], 2053) + self.assertEqual(result["links"], []) + + +if __name__ == "__main__": + unittest.main()