diff --git a/README.md b/README.md index a250416..c938caf 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,21 @@ Changes and secrets need root or the userControl group. inbounds sub [user] [--qr] subscription users, or one user's URL inbounds stats [days] [--by user|inbound|outbound] traffic by user, listener or exit + inbounds users [list] users: order, serverSource address, listeners + (the rest below needs inbounds.runtime) + inbounds users add [--order N] [--listener ]... + add a user at runtime, with generated secrets + inbounds users rm remove a runtime user + inbounds users order a runtime user's order (serverSource number) + inbounds bind|unbind put a user on a listener, or take it off + (a runtime user, or a runtime listener) + inbounds add [--port N] [--via V] [--transport T] [--path P] [--host H] + [--reality SNI[,SNI]] [--tls ] [--alpn a,b] [--flow vision] [--method M] + [--listen A] [--user U]... [more: see inbounds add --help] + add a listener at runtime + inbounds add add one from JSON shaped like inbounds.listeners. + inbounds rm remove a runtime listener + inbounds show a runtime listener's JSON inbounds online who is online, and when others were last seen ``` diff --git a/docs/options/inbounds.md b/docs/options/inbounds.md index c2cfd47..b97b758 100644 --- a/docs/options/inbounds.md +++ b/docs/options/inbounds.md @@ -115,6 +115,16 @@ Part of the [proxy-suite options reference](./index.md). - [ipv6](#services-proxy-suite-inbounds-routing-serversource-ipv6) - [via](#services-proxy-suite-inbounds-routing-via) - [zapretDirect](#services-proxy-suite-inbounds-routing-zapretdirect) + - runtime + - [enable](#services-proxy-suite-inbounds-runtime-enable) + - [fallbackDests](#services-proxy-suite-inbounds-runtime-fallbackdests) + - [ports](#services-proxy-suite-inbounds-runtime-ports) + - [tlsCertificates](#services-proxy-suite-inbounds-runtime-tlscertificates) + - `` + - [certificateFile](#services-proxy-suite-inbounds-runtime-tlscertificates-name-certificatefile) + - [keyFile](#services-proxy-suite-inbounds-runtime-tlscertificates-name-keyfile) + - [serverName](#services-proxy-suite-inbounds-runtime-tlscertificates-name-servername) + - [vias](#services-proxy-suite-inbounds-runtime-vias) - [serverAddress](#services-proxy-suite-inbounds-serveraddress) - [serverAliases](#services-proxy-suite-inbounds-serveraliases) - [serverPorts](#services-proxy-suite-inbounds-serverports) @@ -1086,6 +1096,93 @@ Send zapret hostlist sites direct, so this host’s zapret unblocks them\. Only **Type:** boolean\ **Default:** `true` + +## services\.proxy-suite\.inbounds\.runtime\.enable + +Users and listeners added at runtime with ` proxy-ctl inbounds users add ` and +` inbounds add `, kept in ` inbounds.d ` in the state directory\. Runtime users can be +bound to any listener; declared users to runtime listeners only\. A change restarts +the inbounds, which drops every connection once\. Anything a runtime listener could +reach beyond its port is declared here: its ports, certificates, exits and +fallbacks\. Members of ` userControl.group ` need the “inbounds” scope\. + +**Type:** boolean\ +**Default:** `false` + + +## services\.proxy-suite\.inbounds\.runtime\.fallbackDests + +` dest ` values a runtime listener’s fallbacks may use, such as a decoy site\. A +fallback to a ` listener ` must name another runtime listener\. + +**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string)\ +**Default:** `[ ]`\ +**Example:** `[ "127.0.0.1:8080" ]` + + +## services\.proxy-suite\.inbounds\.runtime\.ports + +Ports runtime listeners may use, on any address: single ports and “from-to” ranges\. +Opened in the firewall (TCP and UDP) with ` openFirewall `, and reachable through the +tunnel like the listeners’ own\. Keep them clear of the declared listeners and of +other services here\. + +**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]±\[0-9]+)\ +**Default:** `[ ]`\ +**Example:** `[ 8443 "20000-20099" ]` + + +## services\.proxy-suite\.inbounds\.runtime\.tlsCertificates + +Certificates a runtime listener with TLS (trojan, hysteria2, ` tls.enable `) may use, +by name: it names one in ` tls.certificate ` (` --tls `), never a file\. + +**Type:** attribute set of (submodule)\ +**Default:** `{ }`\ +**Example:** + +```nix +{ + main = { + certificateFile = "/var/lib/acme/vpn.example.com/fullchain.pem"; + keyFile = "/var/lib/acme/vpn.example.com/key.pem"; + }; +} + +``` + + +## services\.proxy-suite\.inbounds\.runtime\.tlsCertificates\.\\.certificateFile + +File with the PEM certificate chain\. + +**Type:** string + + +## services\.proxy-suite\.inbounds\.runtime\.tlsCertificates\.\\.keyFile + +File with the PEM private key\. + +**Type:** string + + +## services\.proxy-suite\.inbounds\.runtime\.tlsCertificates\.\\.serverName + +SNI in share links\. ` null `: ` serverAddress `\. + +**Type:** null or string\ +**Default:** `null` + + +## services\.proxy-suite\.inbounds\.runtime\.vias + +Exits a runtime listener may pick with ` via `, besides ` routing.via ` and “block”: +“proxy”, “direct” or a ` proxy.outbounds ` tag, as in ` routing.via `\. + +**Type:** list of string\ +**Default:** `[ ]`\ +**Example:** `[ "direct" ]` + ## services\.proxy-suite\.inbounds\.serverAddress @@ -1204,7 +1301,7 @@ kept for as long as the user exists\. The user’s number, for good: their ` inbounds.routing.serverSource ` addresses are that many past the start of each range (5: 10\.78\.0\.5 in 10\.78\.0\.0/24)\. Users without one follow the highest number given, by name, and move when users are -added before them\. Unique\. +added before them\. Unique\. Runtime users (` inbounds.runtime `) go around these numbers\. **Type:** null or (positive integer, meaning >0)\ **Default:** `null`\ diff --git a/docs/options/index.md b/docs/options/index.md index 442fa30..f4e2720 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -89,6 +89,13 @@ services.proxy-suite = { via = "proxy"; zapretDirect = true; }; + runtime = { + enable = false; + fallbackDests = [ ]; + ports = [ ]; + tlsCertificates = { }; + vias = [ ]; + }; serverAddress = null; serverAliases = [ ]; serverPorts = [ ]; diff --git a/docs/options/userControl.md b/docs/options/userControl.md index fa98a4c..9f3d008 100644 --- a/docs/options/userControl.md +++ b/docs/options/userControl.md @@ -40,11 +40,13 @@ What the group may do\. Empty allows everything\. - “autoProxy”: see and change what autoProxy learned\. - “zapret”: change zapret2’s learned sites, and ` zapret cutoff probe `\. - “stats”: ` inbounds stats `\. + - “inbounds”: add, remove and bind runtime inbound users and listeners + (` inbounds.runtime `), and read the secrets they are given\. - “whitelistBypass”: everything under ` proxy-ctl wl `\. - “amneziaWg”: add and remove global AmneziaWG profiles (` proxy-ctl awg add `, ` awg rm `)\. A global profile takes over the host’s routes and DNS\. Starting and stopping one is “services”; an AmneziaWG outbound is “outbounds”\. -**Type:** list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “whitelistBypass”, “amneziaWg”)\ +**Type:** list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “inbounds”, “whitelistBypass”, “amneziaWg”)\ **Default:** `[ ]`\ **Example:** `[ "services" "routing" ]` diff --git a/docs/usage/.snippets/server-3.nix b/docs/usage/.snippets/server-3.nix new file mode 100644 index 0000000..58b1694 --- /dev/null +++ b/docs/usage/.snippets/server-3.nix @@ -0,0 +1,12 @@ +{ config, lib, pkgs, ... }: +{ + services.proxy-suite.inbounds.runtime = { + enable = true; + ports = [ "20000-20099" ]; # runtime listeners bind only here; opened in the firewall + vias = [ "direct" ]; # exits besides routing.via and "block" + tlsCertificates.main = { # named, so a runtime listener never points at a file + certificateFile = "/var/lib/acme/vpn.example.com/fullchain.pem"; + keyFile = "/var/lib/acme/vpn.example.com/key.pem"; + }; +}; +} diff --git a/docs/usage/control.md b/docs/usage/control.md index 76329e3..5ebbb0b 100644 --- a/docs/usage/control.md +++ b/docs/usage/control.md @@ -41,6 +41,7 @@ Members of the group get the listed scopes. An empty `scopes` list grants all of | `amneziaWg` | `awg add` and `awg rm`: global AmneziaWG profiles, which take over the host's routes and DNS | | `perApp` | `apps run` with `tun`, `tproxy` and `zapret` profiles | | `secrets` | reading share links, subscription URLs and running configs | +| `inbounds` | adding, removing and binding runtime inbound users and listeners, and their secrets | | `autoProxy`, `zapret`, `stats`, `whitelistBypass` | the matching `proxy-ctl` groups | Log out and back in after joining the group. Without `userControl`, a change asks for an @@ -52,6 +53,7 @@ admin password, or you run `proxy-ctl` with sudo. |---|---| | `proxy outbounds add`, `proxy subs add`, `awg add` | until removed with `rm`; kept across reboots | | `proxy outbounds disable` | until `enable`; works on outbounds from Nix too | +| `inbounds users add`, `inbounds add`, `inbounds bind` | until removed; kept across reboots | | `proxy pin` | until `unpin`; kept across reboots | | `proxy mode` | until the next reboot | | `… on` / `… off` | until the next reboot; boot state comes from the config | diff --git a/docs/usage/server.md b/docs/usage/server.md index 26e0563..0095130 100644 --- a/docs/usage/server.md +++ b/docs/usage/server.md @@ -88,6 +88,7 @@ hysteria2, vmess, …) and transports (ws, grpc, xhttp) are set per listener; se proxy-ctl inbounds # listeners proxy-ctl inbounds link vless-reality phone --qr # link as a QR code for the phone proxy-ctl inbounds link awg phone --config # AmneziaWG .conf +proxy-ctl inbounds users # users: order, address, listeners proxy-ctl inbounds stats # traffic per user proxy-ctl inbounds online # who is connected ``` @@ -106,6 +107,43 @@ services.nginx.virtualHosts."vpn.example.com".locations."/sub/".alias = Then `proxy-ctl inbounds sub phone --qr` prints that user's subscription. +## Add users and listeners at runtime + +With `inbounds.runtime`, users and listeners can be added with `proxy-ctl`, the TUI or the app, +without a rebuild. The config says what they may use: ports, exits and certificates. + +```nix +services.proxy-suite.inbounds.runtime = { + enable = true; + ports = [ "20000-20099" ]; # runtime listeners bind only here; opened in the firewall + vias = [ "direct" ]; # exits besides routing.via and "block" + tlsCertificates.main = { # named, so a runtime listener never points at a file + certificateFile = "/var/lib/acme/vpn.example.com/fullchain.pem"; + keyFile = "/var/lib/acme/vpn.example.com/key.pem"; + }; +}; +``` + +```sh +proxy-ctl inbounds users add alice --listener vless-reality # secrets are generated +proxy-ctl inbounds add friends vless --port 20001 --reality www.microsoft.com --user alice +proxy-ctl inbounds bind phone friends # a declared user on it too +proxy-ctl inbounds users # order, address, listeners +proxy-ctl inbounds link friends alice --qr +``` + +A runtime user can join any listener; a declared user only a runtime one (bind two declared +ones in the config). Each user's `order` is its `routing.serverSource` number, as in the +config: given with `--order` or the lowest free one, and kept. A listener takes JSON too, +shaped like an [`inbounds.listeners`](../options/inbounds.md#services-proxy-suite-inbounds-listeners) +entry: `proxy-ctl inbounds add friends listener.json`. It cannot name files, raw XRay JSON, +AmneziaWG or port hopping; REALITY keys and Shadowsocks 2022 server keys are generated. + +Every change restarts the inbounds, which drops the connections once. One that does not hold +up is refused, and anything that stops working later (a certificate removed from the config, +say) is left out with a warning in `proxy-ctl logs proxy-suite-inbounds` while the rest runs. +Without root, members of `userControl.group` need the `inbounds` scope. + ## Good to know - Clients cannot reach this host's LAN or Russian sites by default @@ -120,5 +158,6 @@ Then `proxy-ctl inbounds sub phone --qr` prints that user's subscription. - [`inbounds.listeners`](../options/inbounds.md#services-proxy-suite-inbounds-listeners) - [`inbounds.routing.via`](../options/inbounds.md#services-proxy-suite-inbounds-routing-via) +- [`inbounds.runtime`](../options/inbounds.md#services-proxy-suite-inbounds-runtime-enable) - [`inbounds.subscriptions`](../options/inbounds.md#services-proxy-suite-inbounds-subscriptions-enable) - [`tor.onionService`](../options/tor.md#services-proxy-suite-tor-onionservice-enable) diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index 25ce146..5885663 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -225,7 +225,9 @@ let # the main table by rule instead, which the kernel checks before it picks the source. repliesTable = profile: "proxy-suite-awg-${profile.interfaceName}"; serverUdpPorts = lib.unique ( - map toString (awgCfg.serverUdpPorts ++ derived.proxyInboundFirewallUdpPorts) + map toString ( + awgCfg.serverUdpPorts ++ derived.proxyInboundFirewallUdpPorts ++ derived.proxyInboundRuntimePorts + ) ++ cfg.host.openUdpPorts ); serverUdpRulesDown = '' diff --git a/modules/proxy-suite/config-templates/proxy-inbounds.nix b/modules/proxy-suite/config-templates/proxy-inbounds.nix index 921fad2..88057dd 100644 --- a/modules/proxy-suite/config-templates/proxy-inbounds.nix +++ b/modules/proxy-suite/config-templates/proxy-inbounds.nix @@ -32,38 +32,14 @@ let [ { action = "allow"; } ]; # inbounds.routing.serverSource: a user's connections to this host, from the user's own - # address on the dummy interface. Only ever to this host: its listed IPs where there are - # some, and never somewhere private. - serverIps = - builtins.filter - (a: !lib.hasPrefix "domain:" a && (lib.hasInfix ":" a || builtins.match "[0-9.]+" a != null)) - ( - lib.optional (derived.proxyInboundsCfg.serverAddress != null) derived.proxyInboundsCfg.serverAddress - ++ derived.proxyInboundsCfg.serverAliases - ); - selfFinalRules = - if serverIps != [ ] then - [ - { - action = "allow"; - ip = serverIps; - } - { action = "block"; } - ] - else - [ - { - action = "block"; - ip = [ "geoip:private" ]; - } - ]; + # address on the dummy interface. inbound_runtime.py makes the runtime users' the same way. mkSelfOutbound = family: address: id: { protocol = "freedom"; tag = "direct-self${family}-${id}"; sendThrough = address; settings = { domainStrategy = if family == "4" then "UseIPv4" else "UseIPv6"; - finalRules = selfFinalRules; + finalRules = inboundRules.selfFinalRules; }; }; selfOutbounds = lib.concatMap ( diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 3f47b08..94327d2 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -32,6 +32,9 @@ let proxyInboundsRouteOnion proxyInboundsResolveInSingBox proxyInboundsSelfSources + proxyInboundsRuntimeEnabled + proxyInboundsRuntimeVias + proxyInboundRuntimePorts ; inherit (rules) zapretDirectRules; }; @@ -67,9 +70,57 @@ let } ); + # A listener with nothing set: what inbound_runtime.py fills a runtime listener's JSON in + # with, so its defaults are the option's. Not the AmneziaWG part, which runtime listeners + # cannot have, nor what the JSON must not set. + listenerDefaults = + builtins.removeAttrs + (lib.evalModules { + modules = [ + { + options.listener = lib.mkOption { + type = (import ./options/types.nix { inherit lib; }).inboundType; + default = { }; + }; + } + ]; + }).config.listener + [ + "amneziaWg" + "users" + "xrayJson" + "jsonFile" + ]; + + # inbounds.runtime, for inbound_runtime.py: where the spool is and what it may use. + runtimeSpec = + let + rt = derived.proxyInboundsCfg.runtime; + in + { + spool = derived.constants.runtimeInboundsDir; + inherit (rt) ports fallbackDests tlsCertificates; + vias = derived.proxyInboundsRuntimeVias; + defaultVia = derived.proxyInboundsCfg.routing.via; + inherit (inboundRules) selfFinalRules; + salamanderStateDir = "${cfg.host.stateDir}/inbounds"; + inherit listenerDefaults; + }; + # Listener specification handed to build-inbound.py at service start. Secrets # appear here only as paths; the script reads them at runtime. proxyInboundsSpec = { + runtime = if derived.proxyInboundsRuntimeEnabled then runtimeSpec else null; + # Every declared user, on a listener or not, and their serverSource numbers: what + # `proxy-ctl inbounds users` lists, and what runtime users go around. Secrets as paths. + users = derived.proxyInboundsCfg.users; + serverSource = { + inherit (derived.proxyInboundsCfg.routing.serverSource) ipv4 ipv6; + declared = map (s: { + name = s.email; + inherit (s) number; + }) derived.proxyInboundsSelfSources; + }; serverAddress = derived.proxyInboundsCfg.serverAddress; shareLinks = derived.proxyInboundsCfg.shareLinks; # Listeners the onion service carries, which get a second set of links to it. @@ -77,8 +128,9 @@ let listeners = map ( ib: { - inherit (ib) tag; + inherit (ib) tag via; inherit (ib.listener) + order type port sharePort diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 82d74be..f944492 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -181,6 +181,15 @@ let }) proxyInboundsCfg.listeners ); + # inbounds.runtime: listeners added with proxy-ctl may exit by these, so everything built + # per exit (rules, outbounds, the local proxy, name resolution) is there for them too. + proxyInboundsRuntimeEnabled = proxyInboundsEnabled && proxyInboundsCfg.runtime.enable; + proxyInboundsRuntimeVias = lib.optionals proxyInboundsRuntimeEnabled ( + lib.unique ([ proxyInboundsCfg.routing.via ] ++ proxyInboundsCfg.runtime.vias ++ [ "block" ]) + ); + # Every exit a listener has or may get. + proxyInboundsVias = map (ib: ib.via) proxyInbounds ++ proxyInboundsRuntimeVias; + # inbounds.routing.serverSource: an address per inbound user (by XRay's email, the user's # name), which XRay sends that user's connections to this host from. proxyInboundsServerSource = proxyInboundsCfg.routing.serverSource; @@ -236,12 +245,16 @@ let # .onion names from clients go to the local proxy, whose rule hands them to Tor, whatever # the listener's via. AmneziaWG listeners never pass XRay's routing. proxyInboundsRouteOnion = - torRouteOnion && lib.any (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds; + torRouteOnion + && ( + lib.any (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds + || proxyInboundsRuntimeEnabled + ); # Whether any listener or inbounds.routing.proxy exception relays through the local SOCKS # listener. proxyInboundsNeedLocalProxy = - lib.any (ib: ib.via == "proxy") proxyInbounds + builtins.elem "proxy" proxyInboundsVias || proxyInboundsRouteOnion || lib.any (field: proxyInboundsCfg.routing.proxy.${field} != [ ]) [ "domains" @@ -251,7 +264,7 @@ let ]; # Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay). - proxyInboundsResolveInSingBox = !pureXrayEnabled && !lib.any (ib: ib.via == "direct") proxyInbounds; + proxyInboundsResolveInSingBox = !pureXrayEnabled && !builtins.elem "direct" proxyInboundsVias; # Even when XRay resolves (a direct listener), it hands sing-box the name, which sing-box # looks up again: guard there too. @@ -269,7 +282,7 @@ let # Other vias name static outbounds, rendered into the inbound service's own config. proxyInboundViaTags = lib.unique ( - builtins.filter (via: !builtins.elem via builtinTags) (map (ib: ib.via) proxyInbounds) + builtins.filter (via: !builtins.elem via builtinTags) proxyInboundsVias ); # The pinned outbounds and every hop they chain through, which the inbound service renders # too. A hop that is not a static outbound (a subscription entry, warp) has no tag here. @@ -351,6 +364,19 @@ let ) proxyInboundsPublic ) ); + # inbounds.runtime.ports, both protocols: what a runtime listener serves is not known here. + proxyInboundRuntimePorts = lib.optionals (proxyInboundsRuntimeEnabled) proxyInboundsCfg.runtime.ports; + proxyInboundRuntimeSinglePorts = builtins.filter builtins.isInt proxyInboundRuntimePorts; + proxyInboundRuntimePortRanges = map ( + range: + let + bounds = map lib.toInt (lib.splitString "-" range); + in + { + from = builtins.elemAt bounds 0; + to = builtins.elemAt bounds 1; + } + ) (builtins.filter builtins.isString proxyInboundRuntimePorts); # A raw-JSON listener could serve anything, so open both protocols for it. proxyInboundFirewallUdpPorts = lib.unique ( map (ib: ib.listener.port) ( @@ -492,6 +518,8 @@ let pinnedOutboundFile = "${stateDir}/pinned-outbound"; runtimeOutboundsDir = "${stateDir}/outbounds.d"; runtimeSubscriptionsDir = "${stateDir}/subscriptions.d"; + # inbounds.runtime: users/.json and listeners/.json (scripts/inbound_runtime.py). + runtimeInboundsDir = "${stateDir}/inbounds.d"; # Shell function for the scripts that read those spools as root. $1 a file: in a spool, # a regular file only, and never through a symlink, which would hand over any file root # can read (a share link or an error message then shows it), nor a FIFO, which would @@ -653,6 +681,11 @@ in proxyInboundsCfg proxyInboundsEnabled proxyInbounds + proxyInboundsRuntimeEnabled + proxyInboundsRuntimeVias + proxyInboundRuntimePorts + proxyInboundRuntimeSinglePorts + proxyInboundRuntimePortRanges proxyInboundsAwg proxyInboundIsUdpOnly proxyInboundsRouteOnion diff --git a/modules/proxy-suite/hosts/nixos.nix b/modules/proxy-suite/hosts/nixos.nix index 922216e..b1e8a8c 100644 --- a/modules/proxy-suite/hosts/nixos.nix +++ b/modules/proxy-suite/hosts/nixos.nix @@ -66,6 +66,8 @@ in networking.firewall = { allowedTCPPorts = forward internal.firewall.allowedTCPPorts; allowedUDPPorts = forward internal.firewall.allowedUDPPorts; + allowedTCPPortRanges = forward internal.firewall.allowedTCPPortRanges; + allowedUDPPortRanges = forward internal.firewall.allowedUDPPortRanges; extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules; extraInputRules = forward internal.firewall.extraInputRules; trustedInterfaces = forward internal.firewall.trustedInterfaces; diff --git a/modules/proxy-suite/options/host.nix b/modules/proxy-suite/options/host.nix index 163cfc2..2b3f5e1 100644 --- a/modules/proxy-suite/options/host.nix +++ b/modules/proxy-suite/options/host.nix @@ -74,6 +74,9 @@ in firewall = { allowedTCPPorts = internalOption (types.listOf types.port) [ ]; allowedUDPPorts = internalOption (types.listOf types.port) [ ]; + # { from; to; }, as networking.firewall takes them. + allowedTCPPortRanges = internalOption (types.listOf (types.attrsOf types.port)) [ ]; + allowedUDPPortRanges = internalOption (types.listOf (types.attrsOf types.port)) [ ]; extraReversePathFilterRules = internalOption types.lines ""; # nftables firewall only: iptables has no such hook. extraInputRules = internalOption types.lines ""; diff --git a/modules/proxy-suite/options/inbounds.nix b/modules/proxy-suite/options/inbounds.nix index 58fc6ac..27da540 100644 --- a/modules/proxy-suite/options/inbounds.nix +++ b/modules/proxy-suite/options/inbounds.nix @@ -150,6 +150,91 @@ in }; }; + # Consumed by scripts/inbound_runtime.py, which merges the spool into the spec at start, + # and by proxy-ctl, which writes the spool. + runtime = { + enable = mkEnableOption "" // { + description = '' + Users and listeners added at runtime with `proxy-ctl inbounds users add` and + `inbounds add`, kept in `inbounds.d` in the state directory. Runtime users can be + bound to any listener; declared users to runtime listeners only. A change restarts + the inbounds, which drops every connection once. Anything a runtime listener could + reach beyond its port is declared here: its ports, certificates, exits and + fallbacks. Members of `userControl.group` need the "inbounds" scope. + ''; + }; + + ports = mkOption { + type = types.listOf (types.either types.port (types.strMatching "[0-9]+-[0-9]+")); + default = [ ]; + description = '' + Ports runtime listeners may use, on any address: single ports and "from-to" ranges. + Opened in the firewall (TCP and UDP) with `openFirewall`, and reachable through the + tunnel like the listeners' own. Keep them clear of the declared listeners and of + other services here. + ''; + example = [ + 8443 + "20000-20099" + ]; + }; + + vias = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + Exits a runtime listener may pick with `via`, besides `routing.via` and "block": + "proxy", "direct" or a `proxy.outbounds` tag, as in `routing.via`. + ''; + example = [ "direct" ]; + }; + + tlsCertificates = mkOption { + type = types.attrsOf ( + types.submodule { + options = { + certificateFile = mkOption { + type = types.str; + description = "File with the PEM certificate chain."; + }; + keyFile = mkOption { + type = types.str; + description = "File with the PEM private key."; + }; + serverName = mkOption { + type = types.nullOr types.str; + default = null; + description = "SNI in share links. `null`: `serverAddress`."; + }; + }; + } + ); + default = { }; + description = '' + Certificates a runtime listener with TLS (trojan, hysteria2, `tls.enable`) may use, + by name: it names one in `tls.certificate` (`--tls `), never a file. + ''; + example = literalExpression '' + { + main = { + certificateFile = "/var/lib/acme/vpn.example.com/fullchain.pem"; + keyFile = "/var/lib/acme/vpn.example.com/key.pem"; + }; + } + ''; + }; + + fallbackDests = mkOption { + type = types.listOf (types.either types.port types.str); + default = [ ]; + description = '' + `dest` values a runtime listener's fallbacks may use, such as a decoy site. A + fallback to a `listener` must name another runtime listener. + ''; + example = [ "127.0.0.1:8080" ]; + }; + }; + users = mkOption { type = types.attrsOf (types.submodule t.userModule); default = { }; diff --git a/modules/proxy-suite/options/types/inbounds.nix b/modules/proxy-suite/options/types/inbounds.nix index c154b62..aec9906 100644 --- a/modules/proxy-suite/options/types/inbounds.nix +++ b/modules/proxy-suite/options/types/inbounds.nix @@ -16,7 +16,7 @@ let The user's number, for good: their `inbounds.routing.serverSource` addresses are that many past the start of each range (5: 10.78.0.5 in 10.78.0.0/24). Users without one follow the highest number given, by name, and move when users are - added before them. Unique. + added before them. Unique. Runtime users (`inbounds.runtime`) go around these numbers. ''; example = 1; }; diff --git a/modules/proxy-suite/options/user-control.nix b/modules/proxy-suite/options/user-control.nix index 5c89815..99aba81 100644 --- a/modules/proxy-suite/options/user-control.nix +++ b/modules/proxy-suite/options/user-control.nix @@ -24,6 +24,7 @@ in "autoProxy" "zapret" "stats" + "inbounds" "whitelistBypass" "amneziaWg" ] @@ -39,6 +40,8 @@ in - "autoProxy": see and change what autoProxy learned. - "zapret": change zapret2's learned sites, and `zapret cutoff probe`. - "stats": `inbounds stats`. + - "inbounds": add, remove and bind runtime inbound users and listeners + (`inbounds.runtime`), and read the secrets they are given. - "whitelistBypass": everything under `proxy-ctl wl`. - "amneziaWg": add and remove global AmneziaWG profiles (`proxy-ctl awg add`, `awg rm`). A global profile takes over the host's routes and DNS. Starting and stopping one is diff --git a/modules/proxy-suite/rules/proxy-inbounds.nix b/modules/proxy-suite/rules/proxy-inbounds.nix index e0544f9..0a89002 100644 --- a/modules/proxy-suite/rules/proxy-inbounds.nix +++ b/modules/proxy-suite/rules/proxy-inbounds.nix @@ -7,12 +7,26 @@ proxyInboundsRouteOnion, proxyInboundsResolveInSingBox, proxyInboundsSelfSources, + proxyInboundsRuntimeEnabled, + proxyInboundsRuntimeVias, + proxyInboundRuntimePorts, zapretDirectRules, }: let defaultVia = proxyInboundsCfg.routing.via; + # inbounds.runtime: the start script (inbound_runtime.py) adds the runtime listeners' tags + # to every rule marked with the listeners it is for, by their via, and drops the marked + # rules no listener is left in. So with runtime listeners possible, a rule stays even + # while no declared listener is in it. "_anchor" rules are where the runtime users' + # serverSource rules go; they are replaced whether or not there are any. + runtime = proxyInboundsRuntimeEnabled; + mark = members: rule: rule // lib.optionalAttrs runtime { _members = members; }; + forException = mark { notVia = [ "block" ]; }; + forDefault = mark { via = [ defaultVia ]; }; + any = tags: tags != [ ] || runtime; + # Listeners on the default egress are covered by the final rule. overrideInbounds = builtins.filter (ib: ib.via != defaultVia) proxyInbounds; defaultInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via == defaultVia) proxyInbounds); @@ -22,7 +36,7 @@ let # Only Tor reaches .onion: to the local proxy, whose own rule sends it there. First, so no # IP rule before it has XRay look the name up, which would leak it to a resolver. - onionRule = lib.optional proxyInboundsRouteOnion { + onionRule = lib.optional proxyInboundsRouteOnion (forException { type = "field"; ruleTag = "inbound-tor-onion"; domain = [ "domain:onion" ]; @@ -30,7 +44,7 @@ let builtins.filter (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds ); outboundTag = "proxy"; - }; + }); blockPrivateRule = lib.optional proxyInboundsCfg.routing.blockPrivate { type = "field"; @@ -66,19 +80,20 @@ let 443 ] ++ proxyInboundsCfg.serverPorts + ++ proxyInboundRuntimePorts ); # Names and IPs in rules of their own: XRay ANDs the fields of one rule. mkServerAddressRule = ruleTag: field: items: - lib.optional (items != [ ] && exceptionInboundTags != [ ]) { + lib.optional (items != [ ] && any exceptionInboundTags) (forException { type = "field"; inherit ruleTag; ${field} = items; inboundTag = exceptionInboundTags; port = serverPortList; outboundTag = "direct"; - }; + }); # Sniffing is routeOnly (proxy_inbound.py): a name rule also matches a connection to an IP # whose TLS SNI or HTTP Host carries that name, and "direct" then dials the IP, from this @@ -92,20 +107,25 @@ let "0.0.0.0/0" "::/0" ]; + # One rule per via; runtimeVias get theirs even with no declared listener on them. mkSniffGuard = - ruleTag: domains: inbounds: extra: + ruleTag: domains: inbounds: runtimeVias: extra: lib.mapAttrsToList ( via: ibs: - { - type = "field"; - ruleTag = "${ruleTag}-${via}"; - domain = domains; - ip = anyIp; - inboundTag = map (ib: ib.tag) ibs; - outboundTag = via; - } - // extra - ) (lib.groupBy (ib: ib.via) inbounds); + mark { via = [ via ]; } ( + { + type = "field"; + ruleTag = "${ruleTag}-${via}"; + domain = domains; + ip = anyIp; + inboundTag = map (ib: ib.tag) ibs; + outboundTag = via; + } + // extra + ) + ) (lib.genAttrs (lib.optionals runtime runtimeVias) (_: [ ]) // lib.groupBy (ib: ib.via) inbounds); + # Where a runtime listener that is not blocked may exit. + runtimeOpenVias = builtins.filter (via: via != "block") proxyInboundsRuntimeVias; serverNameDomains = map (name: if isSuffix name then name else "full:${name}") serverNames; serverPortList = lib.concatMapStringsSep "," toString serverAddressPorts; @@ -118,7 +138,7 @@ let serverIps6 = builtins.filter (lib.hasInfix ":") serverIps; mkSelfRule = ruleTag: field: items: source: outboundTag: - lib.optional (items != [ ] && exceptionInboundTags != [ ]) { + lib.optional (items != [ ] && any exceptionInboundTags) (forException { type = "field"; ruleTag = "${ruleTag}-${source.id}"; ${field} = items; @@ -126,7 +146,7 @@ let inboundTag = exceptionInboundTags; port = serverPortList; inherit outboundTag; - }; + }); selfIpRules = lib.concatMap ( s: lib.optionals (s.ipv4 != null) ( @@ -142,16 +162,40 @@ let if s.ipv4 != null then "direct-self4-${s.id}" else "direct-self6-${s.id}" ) ) proxyInboundsSelfSources; + # The runtime users' rules, as the declared users' are made: inbound_runtime.py numbers + # them and makes one of each per user from these. + serverSourceOn = + proxyInboundsCfg.routing.serverSource.ipv4 != null + || proxyInboundsCfg.routing.serverSource.ipv6 != null; + mkSelfAnchor = + anchor: fields: + lib.optional (runtime && serverSourceOn) ( + forException ( + { + _anchor = anchor; + ruleTag = "inbound-runtime-anchor-${anchor}"; + inboundTag = exceptionInboundTags; + port = serverPortList; + } + // fields + ) + ); serverNameGuarded = proxyInboundsResolveInSingBox || serverIps != [ ]; serverAddressRule = selfIpRules + ++ mkSelfAnchor "selfIp" { + ip4 = serverIps4; + ip6 = serverIps6; + } ++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps - ++ lib.optionals (serverNames != [ ] && serverNameGuarded && exceptionInboundTags != [ ]) ( + ++ lib.optionals (serverNames != [ ] && serverNameGuarded && any exceptionInboundTags) ( mkSniffGuard "inbound-server-address-sniffed" serverNameDomains (builtins.filter ( ib: ib.via != "block" - ) proxyInbounds) { port = serverPortList; } + ) proxyInbounds) runtimeOpenVias { port = serverPortList; } + ) + ++ lib.optionals (serverNames != [ ] && serverNameGuarded) ( + selfNameRules ++ mkSelfAnchor "selfName" { domain = serverNameDomains; } ) - ++ lib.optionals (serverNames != [ ] && serverNameGuarded) selfNameRules ++ mkServerAddressRule "inbound-server-address-direct" "domain" serverNameDomains; blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [ @@ -173,8 +217,8 @@ let proxyDomainRule = lib.optional - (exceptionInboundTags != [ ] && (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ])) - { + (any exceptionInboundTags && (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ])) + (forException { type = "field"; ruleTag = "inbound-proxy-domain"; domain = @@ -182,23 +226,22 @@ let ++ map (name: "geosite:${name}") inboundProxy.geosites; inboundTag = exceptionInboundTags; outboundTag = "proxy"; - }; + }); proxyIpRule = - lib.optional - (exceptionInboundTags != [ ] && (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ])) - { + lib.optional (any exceptionInboundTags && (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ])) + (forException { type = "field"; ruleTag = "inbound-proxy-ip"; ip = inboundProxy.ips ++ map (name: "geoip:${name}") inboundProxy.geoips; inboundTag = exceptionInboundTags; outboundTag = "proxy"; - }; + }); # Only when the default egress is a proxy, and only for its listeners. zapretDirectEnabled = proxyInboundsCfg.routing.zapretDirect - && defaultInboundTags != [ ] + && any defaultInboundTags && !builtins.elem defaultVia [ "direct" "block" @@ -206,13 +249,13 @@ let mkZapretRule = ruleTag: field: items: - lib.optional (zapretDirectEnabled && items != [ ]) { + lib.optional (zapretDirectEnabled && items != [ ]) (forDefault { type = "field"; inherit ruleTag; ${field} = items; inboundTag = defaultInboundTags; outboundTag = "direct"; - }; + }); zapretDomains = map (domain: "domain:${domain}") zapretDirectRules.domains; # Under IPOnDemand the guard would take every zapret name too: the domain rule stays off. @@ -221,7 +264,7 @@ let ++ lib.optionals (zapretDirectEnabled && zapretDomains != [ ] && proxyInboundsResolveInSingBox) ( mkSniffGuard "inbound-zapret-sniffed" zapretDomains (builtins.filter ( ib: builtins.elem ib.tag defaultInboundTags - ) proxyInbounds) { } + ) proxyInbounds) [ defaultVia ] { } ) ++ lib.optionals proxyInboundsResolveInSingBox ( mkZapretRule "inbound-zapret-direct-domain" "domain" zapretDomains @@ -253,9 +296,27 @@ let ++ zapretRules ++ overrideRules ++ [ finalRule ]; + # The serverSource outbounds' own last word: only ever to this host, its listed IPs where + # there are some, and never somewhere private. + selfFinalRules = + if serverIps != [ ] then + [ + { + action = "allow"; + ip = serverIps; + } + { action = "block"; } + ] + else + [ + { + action = "block"; + ip = [ "geoip:private" ]; + } + ]; in { - inherit xrayInboundRules; + inherit xrayInboundRules selfFinalRules; # Names of this host sent direct with no guard (IPOnDemand, and no IP aliases): a warning. unguardedServerNames = lib.optionals (!serverNameGuarded) serverNames; } diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index ff30d42..be0482c 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -210,7 +210,19 @@ let cfg.inbounds.routing.serverSource.ipv6 == null || lib.toInt (lib.last (lib.splitString "/" cfg.inbounds.routing.serverSource.ipv6)) <= 112 ) "proxy-suite: inbounds.routing.serverSource.ipv6 must be a prefix of /112 or shorter") - (mkAssertion (derived.proxyInboundsSelfSources == [ ] || cfg.host.privileged) + (mkAssertion + ( + ( + derived.proxyInboundsSelfSources == [ ] + && !( + derived.proxyInboundsRuntimeEnabled + && ( + cfg.inbounds.routing.serverSource.ipv4 != null || cfg.inbounds.routing.serverSource.ipv6 != null + ) + ) + ) + || cfg.host.privileged + ) "proxy-suite: inbounds.routing.serverSource needs a system install: it puts addresses on a dummy interface" ) # Daemon configs are readable by the service group; users must not share it. @@ -447,6 +459,11 @@ let builtins.filter (ob: ob.singBoxJson != null) derived.proxyInboundViaOutbounds ); + inRuntimePorts = + port: + builtins.elem port derived.proxyInboundRuntimeSinglePorts + || lib.any (range: range.from <= port && port <= range.to) derived.proxyInboundRuntimePortRanges; + proxyInboundAssertions = [ (mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ]) "proxy-suite: inbounds via targets, or the hops they chain through, are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies, warp, tor, ssh-proxy and AmneziaWG outbounds cannot be named here because the inbound service does not run them; use via = \"proxy\" to reach those." @@ -457,9 +474,40 @@ let (requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled "proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true" ) - (requireEnabled proxyInboundsEnabled ( - proxyInbounds != [ ] - ) "proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners") + (requireEnabled proxyInboundsEnabled (proxyInbounds != [ ] || derived.proxyInboundsRuntimeEnabled) + "proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners, or inbounds.runtime.enable" + ) + # Runtime listeners bind only there: clear of what is bound here already. + (mkAssertion + ( + !derived.proxyInboundsRuntimeEnabled + || !lib.any inRuntimePorts ( + derived.proxyInboundPorts + ++ reservedLoopbackPorts + ++ lib.optional proxyEnabled proxyCfg.listener.port + ++ lib.optional globalTproxy.enable globalTproxy.port + ) + ) + "proxy-suite: inbounds.runtime.ports cover a port a declared listener or proxy-suite itself uses (${ + lib.concatMapStringsSep ", " toString ( + builtins.filter inRuntimePorts ( + derived.proxyInboundPorts + ++ reservedLoopbackPorts + ++ lib.optional proxyEnabled proxyCfg.listener.port + ++ lib.optional globalTproxy.enable globalTproxy.port + ) + ) + })" + ) + (mkAssertion ( + !derived.proxyInboundsRuntimeEnabled + || lib.all ( + range: range.from >= 1 && range.from <= range.to && range.to <= 65535 + ) derived.proxyInboundRuntimePortRanges + ) "proxy-suite: inbounds.runtime.ports ranges must be \"from-to\" within 1-65535, from <= to") + (mkAssertion (!derived.proxyInboundsRuntimeEnabled || derived.proxyInboundRuntimePorts != [ ]) + "proxy-suite: inbounds.runtime.enable needs inbounds.runtime.ports, the ports runtime listeners may use" + ) (requireEnabled proxyInboundsNeedLocalProxy proxyEnabled "proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node." ) @@ -553,8 +601,8 @@ let !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") + !proxyInboundsEnabled || l.type == null || l.users != [ ] || derived.proxyInboundsRuntimeEnabled + ) "${prefix}: at least one entry in users is required (or inbounds.runtime, to add them there)") # XRay refuses to start on a repeated email, which is the user's name. (uniqueValues (proxyInboundsEnabled && l.type != null) (builtins.filter (n: n != "") ( map (user: user.name) l.users diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 38208ef..c7bdb7b 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -21,6 +21,8 @@ let userControlCfg proxyInboundsCfg proxyInboundsEnabled + proxyInboundsRuntimeEnabled + proxyInboundsSpecFile amneziaWgProfileNamesFile awgRuntimeGlobal awgRuntimeOutbounds @@ -111,6 +113,11 @@ in INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile; INBOUNDS_SUB_BASE_URL = if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl; + # inbounds.runtime: the users and listeners proxy-ctl adds go through this tool, which + # reads what it may use from the spec. + INBOUNDS_RUNTIME_ENABLED = flag proxyInboundsRuntimeEnabled; + INBOUNDS_RUNTIME_TOOL = "${proxySuiteScriptsDir}/inbound_runtime.py"; + INBOUNDS_SPEC_FILE = "${proxyInboundsSpecFile}"; # Only the system-wide instance reads the site lists; per-app zapret handles all traffic. ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2" && zapretGlobalEnabled); ZAPRET_STATE_DIR = constants.zapret2StateDir; diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 1b86822..3217395 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -117,9 +117,17 @@ lib.mkMerge [ # Inbound listeners are reached from outside, so their ports have to be open. firewall = lib.mkMerge [ (lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) { - allowedTCPPorts = proxyInboundFirewallPorts; - allowedUDPPorts = proxyInboundFirewallUdpPorts; + allowedTCPPorts = proxyInboundFirewallPorts ++ derived.proxyInboundRuntimeSinglePorts; + allowedUDPPorts = proxyInboundFirewallUdpPorts ++ derived.proxyInboundRuntimeSinglePorts; }) + # Only the NixOS adapter forwards ranges. + (lib.mkIf + (proxyInboundsEnabled && cfg.inbounds.openFirewall && derived.proxyInboundRuntimePortRanges != [ ]) + { + allowedTCPPortRanges = derived.proxyInboundRuntimePortRanges; + allowedUDPPortRanges = derived.proxyInboundRuntimePortRanges; + } + ) # Gateway clients' diverted packets reach input with their original destination, and # carry a mark whose table has no route back. Only those: the LAN is not trusted. (lib.mkIf (tproxyLanSysctl != { }) ( @@ -194,6 +202,27 @@ lib.mkMerge [ constants.runtimeSubscriptionsDir ] )) + # inbounds.runtime: the users' and listeners' files hold their secrets, so the dir is + # as closed as outbounds.d, and group-writable only with the inbounds scope. + (lib.mkIf (cfg.enable && derived.proxyInboundsRuntimeEnabled) ( + map + ( + dir: + "d ${dir} ${ + if userControlAllows "inbounds" then + "2770 root ${userControlCfg.group}" + else if constants.privileged then + "0700 root root" + else + "0700 - -" + } -" + ) + [ + constants.runtimeInboundsDir + "${constants.runtimeInboundsDir}/users" + "${constants.runtimeInboundsDir}/listeners" + ] + )) # Global AmneziaWG profiles added at runtime. Listable, so the tray and TUI show # their names to everyone; each file is 0600 (amneziawg_config.py writes it so). (lib.mkIf (cfg.enable && derived.awgRuntimeGlobal) [ diff --git a/modules/proxy-suite/service/polkit.nix b/modules/proxy-suite/service/polkit.nix index 0af7771..2d16073 100644 --- a/modules/proxy-suite/service/polkit.nix +++ b/modules/proxy-suite/service/polkit.nix @@ -29,6 +29,7 @@ let "proxy-suite-autoproxy-learn." = "autoProxy"; "proxy-suite-zapret2-cutoff." = "zapret"; "proxy-suite-inbound-stats." = "stats"; + "proxy-suite-inbounds-reload." = "inbounds"; "proxy-suite-wb-" = "whitelistBypass"; }; templates = lib.filter (lib.hasSuffix "@") unitNames; diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index e7422fc..9dee3e8 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -26,6 +26,7 @@ let proxyInboundsFile proxyInboundsSpecFile proxyInboundsSelfSources + proxyInboundsRuntimeEnabled builders constants ; @@ -40,7 +41,12 @@ let ip = "${pkgs.iproute2}/bin/ip"; selfInterface = lib.escapeShellArg proxyInboundsCfg.routing.serverSource.interface; selfInterfaceDown = "${ip} link del ${selfInterface} 2>/dev/null || true"; - selfInterfaceUp = lib.optionalString (proxyInboundsSelfSources != [ ]) '' + serverSource = proxyInboundsCfg.routing.serverSource; + # With inbounds.runtime, runtime users may get addresses too, whatever the declared have. + selfInterfaceWanted = + proxyInboundsSelfSources != [ ] + || (proxyInboundsRuntimeEnabled && (serverSource.ipv4 != null || serverSource.ipv6 != null)); + selfInterfaceUp = lib.optionalString selfInterfaceWanted '' ${selfInterfaceDown} ${ip} link add ${selfInterface} type dummy ${ip} link set ${selfInterface} up @@ -49,6 +55,14 @@ let lib.optionalString (s.ipv4 != null) "${ip} addr add ${s.ipv4}/32 dev ${selfInterface}\n" + lib.optionalString (s.ipv6 != null) "${ip} -6 addr add ${s.ipv6}/128 dev ${selfInterface} nodad\n" ) proxyInboundsSelfSources} + ${lib.optionalString proxyInboundsRuntimeEnabled '' + while IFS=$'\t' read -r family address; do + case "$family" in + 4) ${ip} addr add "$address/32" dev ${selfInterface} ;; + 6) ${ip} -6 addr add "$address/128" dev ${selfInterface} nodad ;; + esac + done < <(${jq} -r '.selfAddresses[]? | (select(.ipv4) | "4\t\(.ipv4)"), (select(.ipv6) | "6\t\(.ipv6)")' <<< "$RENDERED") + ''} ''; # Only listeners, and for AmneziaWG listeners transparent sockets (IP_TRANSPARENT). runXray = constants.runAsServiceUser pkgs ( @@ -173,7 +187,7 @@ let RENDERED=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildInboundPy} \ --spec ${proxyInboundsSpecFile} \ --server-address "$SERVER_ADDRESS" \ - --onion-address "$ONION_ADDRESS") + --onion-address "$ONION_ADDRESS"${lib.optionalString proxyInboundsRuntimeEnabled " \\\n --template ${proxyInboundsFile}"}) INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED") @@ -184,6 +198,8 @@ let LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" ''} + # With inbounds.runtime, the routing rules are build-inbound.py's: the template's with the + # runtime listeners and users in. Their serverSource outbounds come with them. ${jq} \ --slurpfile ibs <(printf '%s' "$INBOUNDS_JSON") \ --slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \ @@ -195,8 +211,14 @@ let else "--arg password ''" } \ + --argjson runtime ${if proxyInboundsRuntimeEnabled then "true" else "false"} \ + --slurpfile rendered <(printf '%s' "$RENDERED") \ '.inbounds += $ibs[0] | .outbounds = $obs[0] + .outbounds + | if $runtime then + .routing.rules = $rendered[0].rules + | .outbounds += $rendered[0].selfOutbounds + else . end | if $auth_enabled then (.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users) = [{user:$user,pass:$password}] @@ -306,8 +328,22 @@ let chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp" mv -f "$tmp" "$file" ''; + # inbounds.runtime: after proxy-ctl changes the spool. The AmneziaWG interfaces only when + # their peers changed: restarting them cuts off every one of their clients for a moment. + reloadInbounds = pkgs.writeShellScript "proxy-suite-inbounds" '' + set -euo pipefail + restart=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${parserScriptsPythonPath}/inbound_runtime.py \ + --spec ${proxyInboundsSpecFile} check${ + lib.optionalString ( + proxyInboundsAwg != [ ] + ) " --awg-users ${constants.runtimeDir}/proxy-suite-inbounds-awg/users.json" + }) + # shellcheck disable=SC2086 + ${constants.systemctl} try-restart $restart proxy-suite-inbounds.service + ''; + stopInboundsInterface = - if proxyInboundsSelfSources == [ ] then + if !selfInterfaceWanted then null else pkgs.writeShellScript "proxy-suite-inbounds" selfInterfaceDown; @@ -317,6 +353,7 @@ in startInbounds stopInboundsInterface collectInboundStats + reloadInbounds linksFile subscriptionsFile ; diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index fbf1f4e..89db03f 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -168,7 +168,12 @@ let inherit (startScripts) startSocks startTun startPerAppTun; proxyInboundsScripts = import ./proxy-inbounds-scripts.nix { ctx = sctx; }; - inherit (proxyInboundsScripts) startInbounds stopInboundsInterface collectInboundStats; + inherit (proxyInboundsScripts) + startInbounds + stopInboundsInterface + collectInboundStats + reloadInbounds + ; proxyInboundsLinksFile = proxyInboundsScripts.linksFile; proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile; @@ -206,6 +211,7 @@ in startInbounds stopInboundsInterface collectInboundStats + reloadInbounds ; inherit proxyInboundsLinksFile diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index 7b10632..5b63f31 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -22,6 +22,7 @@ let torOnionEnabled whitelistBypassJoiners proxyInboundsEnabled + proxyInboundsRuntimeEnabled proxyInboundsNeedLocalProxy scripts perAppRouting @@ -129,6 +130,16 @@ let }; }; } + { + enable = proxyInboundsRuntimeEnabled; + name = "proxy-suite-inbounds-reload"; + value = mkOneshotService { + description = "Apply proxy-suite inbound users and listeners added at runtime"; + execStart = scripts.reloadInbounds; + stateDirectory = "proxy-suite"; + extraServiceConfig.RemainAfterExit = false; + }; + } { enable = proxyInboundsEnabled; name = serviceNames.inboundStats; diff --git a/nix/checks/amnezia-wg-inbound-runtime.nix b/nix/checks/amnezia-wg-inbound-runtime.nix index ec89f4d..81e22b9 100644 --- a/nix/checks/amnezia-wg-inbound-runtime.nix +++ b/nix/checks/amnezia-wg-inbound-runtime.nix @@ -112,6 +112,11 @@ pkgs.testers.runNixOSTest { dns = [ ]; }; }; + # A peer added with proxy-ctl. + runtime = { + enable = true; + ports = [ "9000-9001" ]; + }; }; }; environment.systemPackages = [ pkgs.jq ]; @@ -215,5 +220,18 @@ pkgs.testers.runNixOSTest { server.wait_for_unit("proxy-suite-inbounds.service") assert server.succeed("jq -S .users /var/lib/proxy-suite/awg-inbounds/roam/state.json") == before through_server(alice, timeout=90) + + with subtest("a runtime user becomes a peer, and only its listener's interfaces restart"): + server.succeed("proxy-ctl inbounds users add ring --listener roam") + server.wait_until_succeeds("awg show awgi-roam peers | wc -l | grep -qx 3", timeout=30) + server.succeed("jq -e '.users.ring.publicKey' /var/lib/proxy-suite/awg-inbounds/roam/state.json") + server.succeed("proxy-ctl inbounds link roam ring --config | grep -q '^PrivateKey'") + # A change that leaves the peers alone restarts only XRay. + since = server.succeed("systemctl show -p ActiveEnterTimestampMonotonic --value proxy-suite-inbounds-awg.service").strip() + server.succeed("proxy-ctl inbounds users order ring 9") + assert server.succeed("systemctl show -p ActiveEnterTimestampMonotonic --value proxy-suite-inbounds-awg.service").strip() == since + server.succeed("proxy-ctl inbounds users rm ring") + server.wait_until_succeeds("awg show awgi-roam peers | wc -l | grep -qx 2", timeout=30) + server.succeed("jq -e '.users.ring == null' /var/lib/proxy-suite/awg-inbounds/roam/state.json") ''; } diff --git a/nix/checks/proxy-inbounds-runtime.nix b/nix/checks/proxy-inbounds-runtime.nix index 6474873..5c67ed9 100644 --- a/nix/checks/proxy-inbounds-runtime.nix +++ b/nix/checks/proxy-inbounds-runtime.nix @@ -63,6 +63,11 @@ pkgs.testers.runNixOSTest { method = "2022-blake3-aes-128-gcm"; users = [ "ss-user" ]; }; + # Users and listeners proxy-ctl adds below. + runtime = { + enable = true; + ports = [ "9000-9010" ]; + }; }; }; @@ -159,5 +164,38 @@ pkgs.testers.runNixOSTest { with subtest("a listener keeps serving after a restart"): server.succeed("systemctl restart proxy-suite-inbounds.service") server.wait_for_open_port(8443) + + with subtest("runtime users and listeners"): + cfg = "/run/proxy-suite-inbounds/config.json" + server.succeed("proxy-ctl inbounds users add friend --listener vless-in") + server.succeed(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\", \"friend\"]' {cfg}") + server.succeed("proxy-ctl inbounds add rt vless --port 9001 --user friend --user tester") + server.wait_for_open_port(9001) + server.succeed("proxy-ctl inbounds users | grep friend | grep -q rt") + # Refused, and nothing else disturbed. + server.fail("proxy-ctl inbounds add far vless --port 30000 --user friend") + server.fail("proxy-ctl inbounds bind tester vless-in") + server.succeed("test ! -e /var/lib/proxy-suite/inbounds.d/listeners/far.json") + # The runtime user's link works from the client, as a runtime outbound there. XRay + # refuses plain VLESS to a public IP, so it dials the private one. + link = server.succeed("proxy-ctl inbounds link rt friend").strip() + assert link.startswith("vless://") and ":9001" in link, link + link = link.replace("${serverAddress}", "${serverPrivateAddress}") + client.succeed(f"proxy-ctl proxy outbounds add rt-out '{link}'") + client.succeed("proxy-ctl proxy pin rt-out") + client.wait_until_succeeds( + "curl -sS --fail --max-time 20 --proxy socks5h://127.0.0.1:1080" + f" http://{'${serverAddress}'}/ | grep -q served-from-origin", + timeout=60, + ) + # A spool file that no longer holds up is left out; the declared listeners stay. + server.succeed("echo '{' > /var/lib/proxy-suite/inbounds.d/listeners/rt.json") + server.succeed("systemctl start proxy-suite-inbounds-reload.service") + server.wait_for_open_port(8443) + server.succeed(f"jq -e '[.inbounds[].tag] | index(\"rt\") == null' {cfg}") + server.succeed("journalctl -u proxy-suite-inbounds | grep -q \"ignoring runtime listener 'rt'\"") + server.succeed("rm /var/lib/proxy-suite/inbounds.d/listeners/rt.json") + server.succeed("proxy-ctl inbounds users rm friend") + server.succeed(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\"]' {cfg}") ''; } diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index b891dc7..6b91ecd 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -211,6 +211,46 @@ let lib.recursiveUpdate selfSourceInbounds { routing.serverSource.ipv4 = "10.78.0.5/24"; } ); + # inbounds.runtime: the rules runtime listeners join are marked, the runtime users' + # serverSource rules have their anchors, and the rest of the system is ready for them. + runtimeInbounds = selfSourceInbounds // { + runtime = { + enable = true; + ports = [ + 9443 + "20000-20010" + ]; + vias = [ "direct" ]; + }; + }; + runtimeFixture = mkInbounds runtimeInbounds; + runtimeConfig = mkInboundsConfig runtimeFixture; + runtimeSpec = mkInboundsSpec runtimeFixture; + hasFailed = + fixture: message: + builtins.any (a: !a.assertion && lib.hasInfix message a.message) fixture.config.assertions; + # Only this module's: a fixture has no root file system or boot loader. + failedMessages = + fixture: + builtins.filter (lib.hasPrefix "proxy-suite:") ( + map (a: a.message) (builtins.filter (a: !a.assertion) fixture.config.assertions) + ); + # A listener meant only for runtime users, and nothing but runtime listeners. + runtimeOnlyFixture = mkInbounds { + serverAddress = "vpn.example.com"; + runtime = { + enable = true; + ports = [ "20000-20010" ]; + }; + listeners.waiting = realityListener // { + users = [ ]; + }; + }; + runtimeClashFixture = mkInbounds ( + lib.recursiveUpdate runtimeInbounds { runtime.ports = [ "400-500" ]; } + ); + runtimeNoPortsFixture = mkInbounds (runtimeInbounds // { runtime.enable = true; }); + unguardedFixture = mkInbounds { routing = { blockRu = false; @@ -995,6 +1035,118 @@ let ) badSelfSourceFixture.config.assertions; true ) + # The declared users are in the spec without inbounds.runtime too, for `inbounds users`. + ( + let + spec = mkInboundsSpec selfSourceFixture; + in + assert spec.runtime == null; + assert + builtins.attrNames spec.users == [ + "a" + "alice" + "anon" + "b" + "bob" + "far" + "h3" + "hy2" + "laptop" + "phone" + "second" + "ss" + "user" + "ws" + ]; + assert + (builtins.head spec.serverSource.declared) == { + name = "bob"; + number = 1; + }; + true + ) + # Without inbounds.runtime nothing is marked for it. + (ok (!builtins.any (rule: rule ? _members || rule ? _anchor) selfSourceConfig.routing.rules)) + ( + let + rules = runtimeConfig.routing.rules; + anchors = builtins.filter (rule: rule ? _anchor) rules; + tags = ruleTags runtimeConfig; + at = tag: lib.lists.findFirstIndex (t: t == tag) null tags; + anchorAt = name: lib.lists.findFirstIndex (rule: (rule._anchor or null) == name) null rules; + startScript = (import ./read-generated.nix).readDerivation (service runtimeFixture) + .serviceConfig.ExecStart; + fw = runtimeFixture.config.networking.firewall; + in + assert + map (rule: rule._anchor) anchors == [ + "selfIp" + "selfName" + ]; + # Each after the declared users' own, before the host's. + assert anchorAt "selfIp" > at "inbound-server-address-self-ip4-6"; + assert anchorAt "selfIp" < at "inbound-server-address-direct-ip"; + assert anchorAt "selfName" > at "inbound-server-address-self-6"; + assert anchorAt "selfName" < at "inbound-server-address-direct"; + assert (builtins.head anchors).ip4 == [ "203.0.113.10" ]; + assert (builtins.head anchors).port == "8443,443,9443,20000-20010"; + assert + (ruleByTag runtimeConfig "inbound-server-address-direct")._members == { notVia = [ "block" ]; }; + # A guard for every exit a runtime listener may take, even with nobody on it yet. + assert (ruleByTag runtimeConfig "inbound-server-address-sniffed-direct").inboundTag == [ ]; + assert + (ruleByTag runtimeConfig "inbound-server-address-sniffed-direct")._members == { + via = [ "direct" ]; + }; + assert !builtins.elem "inbound-server-address-sniffed-block" tags; + assert + runtimeSpec.runtime.vias == [ + "proxy" + "direct" + "block" + ]; + assert + runtimeSpec.serverSource.declared == [ + { + name = "bob"; + number = 1; + } + { + name = "alice"; + number = 5; + } + { + name = "anon"; + number = 6; + } + ]; + assert runtimeSpec.runtime.spool == "/var/lib/proxy-suite/inbounds.d"; + assert !(runtimeSpec.runtime.listenerDefaults ? users); + assert runtimeSpec.runtime.listenerDefaults.port == 443; + assert + runtimeSpec.runtime.selfFinalRules + == (builtins.head (builtins.filter (ob: ob.tag == "direct-self4-1") runtimeConfig.outbounds)) + .settings.finalRules; + assert builtins.elem 9443 fw.allowedTCPPorts && builtins.elem 9443 fw.allowedUDPPorts; + assert + fw.allowedTCPPortRanges == [ + { + from = 20000; + to = 20010; + } + ]; + assert lib.hasInfix "--template" startScript; + assert runtimeFixture.config.systemd.services ? proxy-suite-inbounds-reload; + assert builtins.elem "d /var/lib/proxy-suite/inbounds.d 0700 root root -" + runtimeFixture.config.systemd.tmpfiles.rules; + assert !(selfSourceFixture.config.systemd.services ? proxy-suite-inbounds-reload); + true + ) + (ok (failedMessages runtimeOnlyFixture == [ ])) + (ok ( + hasFailed runtimeClashFixture "inbounds.runtime.ports cover a port a declared listener or proxy-suite itself uses (443)" + )) + (ok (hasFailed runtimeNoPortsFixture "inbounds.runtime.enable needs inbounds.runtime.ports")) (ok ((ruleByTag aliasedConfig "inbound-server-address-direct").port == "443,993,7882-7885")) (ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").port == "443,993,7882-7885")) (ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").outboundTag == "direct")) diff --git a/nix/checks/python-tests.nix b/nix/checks/python-tests.nix index 8382124..8838c03 100644 --- a/nix/checks/python-tests.nix +++ b/nix/checks/python-tests.nix @@ -62,6 +62,11 @@ pkgs.lib.mapAttrs mkPythonCheck { file = "${scripts}/test-awg-inbound.py"; env = withPath scripts; }; + # inbounds.runtime: the spool, its fences, the merge and the rules it expands. + inbound-runtime = { + file = "${scripts}/test-inbound-runtime.py"; + env = withPath scripts; + }; # The NFQWS_OPT rewrites the zapret v1 package build applies. patch-zapret-config = { file = "${scripts}/test-patch-zapret-config.py"; @@ -76,6 +81,7 @@ pkgs.lib.mapAttrs mkPythonCheck { # `awg add` and AmneziaWG outbounds hand their configs to it. env = singBox // { AWG_CONFIG_TOOL = "${scripts}/amneziawg_config.py"; + INBOUNDS_RUNTIME_TOOL = "${scripts}/inbound_runtime.py"; }; }; # proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped. diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 8888697..424a966 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -138,6 +138,21 @@ Changes and secrets need root or the userControl group. inbounds sub [user] [--qr] subscription users, or one user's URL inbounds stats [days] [--by user|inbound|outbound] traffic by user, listener or exit + inbounds users [list] users: order, serverSource address, listeners + (the rest below needs inbounds.runtime) + inbounds users add [--order N] [--listener ]... + add a user at runtime, with generated secrets + inbounds users rm remove a runtime user + inbounds users order a runtime user's order (serverSource number) + inbounds bind|unbind put a user on a listener, or take it off + (a runtime user, or a runtime listener) + inbounds add [--port N] [--via V] [--transport T] [--path P] [--host H] + [--reality SNI[,SNI]] [--tls ] [--alpn a,b] [--flow vision] [--method M] + [--listen A] [--user U]... [more: see inbounds add --help] + add a listener at runtime + inbounds add add one from JSON shaped like inbounds.listeners. + inbounds rm remove a runtime listener + inbounds show a runtime listener's JSON inbounds online who is online, and when others were last seen """ @@ -149,6 +164,33 @@ ROUTE_MODE_LABELS = { "all-bypass": "All Bypass (override)", } +# `inbounds add`: the listener types and flags scripts/inbound_runtime.py takes. +INBOUND_TYPES = ("vless", "vmess", "trojan", "hysteria2", "shadowsocks", "socks", "http") +INBOUND_ADD_FLAGS = { + "--port": "port, from inbounds.runtime.ports", + "--listen": "listening address (default ::)", + "--via": "where its traffic exits", + "--transport": "raw, ws, grpc, httpupgrade or xhttp", + "--path": "ws, httpupgrade or xhttp path", + "--host": "expected Host header", + "--mode": "xhttp mode", + "--service-name": "gRPC service name", + "--reality": "REALITY server names, comma-separated", + "--reality-dest": "REALITY dest host:port", + "--short-id": "REALITY short ID", + "--tls": "a certificate from inbounds.runtime.tlsCertificates", + "--alpn": "ALPN, comma-separated", + "--sni": "SNI in share links", + "--flow": "vless flow (vision)", + "--method": "shadowsocks cipher", + "--share-port": "port in share links", + "--share-address": "address in share links", + "--order": "position in links and subscriptions", + "--masquerade": "hysteria2: site shown to anything else", + "--salamander": "hysteria2: Salamander obfuscation", + "--user": "a user it accepts", +} + # A hostname: it lands in root-owned files and then in URLs. HOSTNAME = re.compile(r"[A-Za-z0-9.-]+\.[A-Za-z]{2,}") @@ -690,9 +732,31 @@ COMPLETE = { "sub": "subscription users, or one user's URL", "stats": "traffic per user, listener or exit", "online": "who is connected now", + "users": "users, and adding them at runtime", + "bind": "put a user on a listener", + "unbind": "take a user off a listener", + "add": "add a listener at runtime", + "rm": "remove a runtime listener", + "show": "a runtime listener's JSON", } }, "inbounds stats": {"flags": {"--by": "user, inbound or outbound"}}, + "inbounds users": { + "words": { + "list": "users, their order, address and listeners", + "add": "add a user at runtime", + "rm": "remove a runtime user", + "order": "set a runtime user's order", + } + }, + "inbounds users add": {"flags": {"--order": "its serverSource number", "--listener": "a listener to put it on"}}, + "inbounds users rm": {"args": lambda: _inbound_runtime_names("users", "runtime")}, + "inbounds users order": {"args": lambda: _inbound_runtime_names("users", "runtime")}, + "inbounds bind": {"args": lambda: {**_inbound_runtime_names("users"), **_inbound_runtime_names("listeners")}, "repeat": True}, + "inbounds unbind": {"args": lambda: {**_inbound_runtime_names("users"), **_inbound_runtime_names("listeners")}, "repeat": True}, + "inbounds add": {"args": lambda: {t: "" for t in INBOUND_TYPES}, "repeat": True, "flags": INBOUND_ADD_FLAGS}, + "inbounds rm": {"args": lambda: _inbound_runtime_names("listeners", "runtime")}, + "inbounds show": {"args": lambda: _inbound_runtime_names("listeners", "runtime")}, "inbounds link": { "args": _inbound_link_choices, "flags": { @@ -3720,15 +3784,115 @@ def _inbound_subscriptions(*args): print("Set inbounds.subscriptions.baseUrl to get a URL instead of a path.", file=sys.stderr) +# --- runtime inbound users and listeners --------------------------------------- +# +# inbounds.runtime: users/.json and listeners/.json in a spool the "inbounds" scope +# may write. scripts/inbound_runtime.py checks and writes them, with what the spec allows; +# the reload unit restarts the inbounds, which merge them in when they start. + +def _inbound_runtime(*args, stdin=None, quiet=False, listing=False): + """scripts/inbound_runtime.py with the spec: its output, or its complaint as ours. + + listing: a read, which works without inbounds.runtime (the declared users and listeners). + """ + if not (listing and env("INBOUNDS_ENABLED") == "1") and env("INBOUNDS_RUNTIME_ENABLED") != "1": + die("Runtime inbound users and listeners are not enabled in this configuration (inbounds.runtime.enable).") + argv = [sys.executable, env("INBOUNDS_RUNTIME_TOOL"), "--spec", env("INBOUNDS_SPEC_FILE"), "--xray", env("INBOUNDS_XRAY", "xray"), *args] + try: + p = subprocess.run(argv, input=stdin, capture_output=True, text=True) + except OSError as e: + die(f"Cannot run {argv[1]}: {e}") + if p.returncode and not quiet: + message = p.stderr.strip() or f"{argv[1]} exited with {p.returncode}" + die(f"{message} - {ask_group()}." if p.returncode == 77 else message) + if not quiet and p.stderr: + sys.stderr.write(p.stderr) + return p.returncode, p.stdout + + +def _inbound_runtime_rows(kind): + """Users or listeners, declared and runtime, as the tool lists them; [] when it cannot.""" + if env("INBOUNDS_ENABLED") != "1": + return [] + status, out = _inbound_runtime(kind, "--json", quiet=True, listing=True) + try: + rows = json.loads(out) if not status else [] + except ValueError: + rows = [] + return rows if isinstance(rows, list) else [] + + +def _inbound_runtime_names(kind, source=""): + key = "name" if kind == "users" else "tag" + return {_s(r[key]): _s(r.get("source") or "") for r in _inbound_runtime_rows(kind) if not source or r.get("source") == source} + + +def _inbound_runtime_change(*args, stdin=None): + """A change to the spool, then the reload that applies it, then what it left out.""" + _, out = _inbound_runtime(*args, stdin=stdin) + sys.stdout.write(out) + if systemctl("start", "proxy-suite-inbounds-reload.service")[0]: + die("Saved, but applying it failed - see: proxy-ctl logs proxy-suite-inbounds-reload") + p = subprocess.run( + [sys.executable, env("INBOUNDS_RUNTIME_TOOL"), "--spec", env("INBOUNDS_SPEC_FILE"), "check"], + capture_output=True, + text=True, + ) + for line in lines(p.stderr): + print(f"warning: {line}", file=sys.stderr) + + +def _inbound_users(verb="list", *args): + if verb in ("list", "--json"): + sys.stdout.write(_inbound_runtime("users", *(["--json"] if "--json" in (verb, *args) else []), listing=True)[1]) + elif verb == "add" and args: + _inbound_runtime_change("users", "add", *args) + elif verb == "rm" and len(args) == 1: + _inbound_runtime_change("users", "rm", *args) + elif verb == "order" and len(args) == 2: + _inbound_runtime_change("users", "order", *args) + else: + usage("inbounds users [list] | add [--order N] [--listener ]... | rm | order ") + + def cmd_inbounds(verb="list", *args): require_enabled("INBOUNDS_ENABLED", "inbounds") + if verb == "users": + _inbound_users(*args) + return + if verb in ("bind", "unbind"): + if len(args) != 2: + usage(f"inbounds {verb} ") + _inbound_runtime_change(verb, *args) + return + if verb == "add": + if "--help" in args or "-h" in args: + sys.stdout.write(_inbound_runtime("add", "--help")[1]) + return + if len(args) < 2: + usage("inbounds add [flags] | ") + _inbound_runtime_change("add", *args, stdin=sys.stdin.read() if args[1:2] == ("-",) else None) + return + if verb == "rm": + if len(args) != 1: + usage("inbounds rm ") + _inbound_runtime_change("rm", *args) + return + if verb == "show": + if len(args) != 1: + usage("inbounds show ") + sys.stdout.write(_inbound_runtime("show", *args)[1]) + return if verb == "list": state = svc_state("proxy-suite-inbounds") - row = " {:<24} {:<16} {:<14} {:<8} {}" - print(row.format("TAG", "USER", "TYPE", "PORT", "STATE")) + # Which listeners were added at runtime, when they can be. + sources = _inbound_runtime_names("listeners") if env("INBOUNDS_RUNTIME_ENABLED") == "1" else {} + row = " {:<24} {:<16} {:<14} {:<8} {:<8}" + (" {}" if sources else "") + print(row.format("TAG", "USER", "TYPE", "PORT", "STATE", "SOURCE").rstrip()) for x in _inbound_links(): kind = _s(x.get("type")) + (" (onion)" if x.get("variant") == "onion" else "") - print(row.format(_s(x.get("tag")), _s(x.get("user")), kind, _s(x.get("port")), state)) + tag = _s(x.get("tag")) + print(row.format(tag, _s(x.get("user")), kind, _s(x.get("port")), state, sources.get(tag, "nix")).rstrip()) elif verb in ("link", "qr"): rest = [a for a in args if not a.startswith("--")] if not rest: diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index 0004a42..6c00b0e 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -28,7 +28,7 @@ def _die(message, status=1): # Clash API calls and systemctl spawns that several readers repeat within one load. -MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state", "_wl") +MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state", "_wl", "_inbound_runtime_rows") # proxy_ctl as the CLI has it, before the patching below: its own tests put these back. CLI_FUNCTIONS = {name: getattr(ctl, name) for name in ("die", *MEMOIZED)} @@ -396,17 +396,50 @@ def inbound_rows(_): # so a per-listener row could only repeat the same verdict once per listener. The # "who is online" action shows it once per user, which is the shape the data has. # A listener behind the onion service has a second row, for its .onion link. + sources = ctl._inbound_runtime_names("listeners") return [ { # The TUI titles its menu with the key: no trailing "/" for the plain link. "key": "/".join(ctl._s(x.get(k)) for k in ("tag", "user", "variant") if x.get(k)), **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port", "variant")}, **({"type": f"{ctl._s(x.get('type') or '')} (onion)"} if x.get("variant") == "onion" else {}), + "source": sources.get(ctl._s(x.get("tag")), "nix"), } for x in ctl._inbound_links() ] +def inbound_user_rows(_): + """Inbound users as `inbounds users` lists them: the declared ones, and with + inbounds.runtime the runtime ones too.""" + return [ + { + "key": ctl._s(u.get("name")), + "name": ctl._s(u.get("name")), + "order": ctl._s(u.get("order") if u.get("order") is not None else ""), + "address": ctl._s(u.get("address") or ""), + "source": ctl._s(u.get("source") or ""), + "listeners": ",".join(ctl._s(t) for t in u.get("listeners") or []), + "problems": "; ".join(ctl._s(p) for p in u.get("problems") or []), + } + for u in ctl._inbound_runtime_rows("users") + ] + + +def _inbounds_runtime(): + return ctl.env("INBOUNDS_RUNTIME_ENABLED") == "1" + + +def _runtime_row(row): + return row.get("source") == "runtime" + + +def _user_add_argv(text): + words = shlex.split(text) + order = ["--order", words[1]] if len(words) > 1 else [] + return ["inbounds", "users", "add", *words[:1], *order, *(a for t in words[2:] for a in ("--listener", t))] + + def app_rows(_): return [ {"key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route"))} @@ -753,6 +786,36 @@ TABS = [ Action("I", "traffic per inbound", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"), Action("O", "traffic per exit", lambda r, *_: ["inbounds", "stats", "--by", "outbound"], mode="dialog"), Action("n", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"), + Action( + "a", + "add a listener…", + lambda r, t, _: ["inbounds", "add", *shlex.split(t)], + prompt=" [--port N] [--reality SNI] [--tls ] [--user U]... - e.g. friends vless --port 20001 --reality www.microsoft.com", + offered=_inbounds_runtime, + ), + Action("d", "remove this listener", lambda r, *_: ["inbounds", "rm", r["tag"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime), + Action("b", "bind a user to it…", lambda r, t, _: ["inbounds", "bind", t.strip(), r["tag"]], when=ROW, prompt="", offered=_inbounds_runtime), + Action("u", "unbind a user from it…", lambda r, t, _: ["inbounds", "unbind", t.strip(), r["tag"]], when=ROW, prompt="", offered=_inbounds_runtime), + ], + ), + Tab( + "inbound-users", + "Users", + _enabled("INBOUNDS_ENABLED"), + [("name", "User"), ("order", "Order"), ("address", "Address"), ("source", "Source"), ("listeners", "Listeners"), ("problems", "Problems")], + inbound_user_rows, + summary=lambda: ( + "Runtime users get generated secrets; a change restarts the inbounds, which drops every connection once." + if _inbounds_runtime() + else "Users from the configuration. inbounds.runtime would let you add and bind them here." + ), + actions=[ + Action("n", "add a user…", lambda r, t, _: _user_add_argv(t), prompt=" [order] [listener]... - e.g. alice 7 vless-in", offered=_inbounds_runtime), + Action("d", "remove this user", lambda r, *_: ["inbounds", "users", "rm", r["name"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime), + Action("e", "set its order…", lambda r, t, _: ["inbounds", "users", "order", r["name"], t.strip()], when=_runtime_row, prompt="", offered=_inbounds_runtime), + Action("b", "bind it to a listener…", lambda r, t, _: ["inbounds", "bind", r["name"], t.strip()], when=ROW, prompt="", offered=_inbounds_runtime), + Action("u", "unbind it from a listener…", lambda r, t, _: ["inbounds", "unbind", r["name"], t.strip()], when=ROW, prompt="", offered=_inbounds_runtime), + Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"), ], ), Tab( diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index ad5d158..a9136c1 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -1157,6 +1157,103 @@ class OutboundTestTest(EnvTest): self.assertIn("proxy-suite group, or re-run with sudo", err) +class InboundRuntimeTest(EnvTest): + """inbounds.runtime through proxy-ctl: the tool does the work, proxy-ctl reloads after.""" + + def setUp(self): + super().setUp() + tool = os.environ.get("INBOUNDS_RUNTIME_TOOL") + if not tool: + self.skipTest("INBOUNDS_RUNTIME_TOOL is not set") + spool = self.path("inbounds.d") + os.makedirs(spool) + spec = { + "serverAddress": "vpn.example.com", + "shareLinks": True, + "users": {"bob": {"order": 1, "uuid": "11111111-1111-4111-8111-111111111111"}, "idle": {"order": None}}, + "serverSource": {"ipv4": None, "ipv6": None, "declared": []}, + "listeners": [ + {"tag": "vless-in", "type": "vless", "port": 443, "order": 1000, "via": "proxy", "listen": "::", + "users": [{"name": "bob", "uuid": "11111111-1111-4111-8111-111111111111"}]}, + ], + "runtime": { + "spool": spool, + "ports": ["20000-20010"], + "vias": ["proxy", "block"], + "defaultVia": "proxy", + "fallbackDests": [], + "tlsCertificates": {}, + "listenerDefaults": { + "address": "::", "acceptProxyProtocol": False, "fallbacks": [], "flow": None, "order": 1000, "port": 443, + "method": "2022-blake3-aes-128-gcm", "serverPassword": None, "sharePort": None, "shareAddress": None, + "hysteria": {"masquerade": None, "salamander": {"enable": False, "password": None}}, + "reality": {"enable": False, "dest": "www.microsoft.com:443", "serverNames": [], "privateKey": None, + "publicKey": None, "shortIds": [""], "xver": 0}, + "tls": {"enable": False, "alpn": None, "serverName": None}, + "transport": {"type": "raw", "path": "/", "host": None, "mode": None, "serviceName": "", "trustedXForwardedFor": []}, + }, + }, + } + os.environ.update( + INBOUNDS_ENABLED="1", + INBOUNDS_RUNTIME_ENABLED="1", + INBOUNDS_SPEC_FILE=self.write("spec.json", spec), + ) + self.started = [] + + def systemctl(*args, **kw): + self.started.append(args) + return 0, "" + + self.patch("systemctl", systemctl) + + def test_users_and_listeners(self): + out = ok(ctl.cmd_inbounds, "users", "add", "alice", "--listener", "vless-in") + self.assertEqual(out, "Added user alice (order 2) on vless-in\n") + self.assertEqual(self.started, [("start", "proxy-suite-inbounds-reload.service")]) + out = ok(ctl.cmd_inbounds, "add", "friends", "vless", "--port", "20001", "--user", "alice") + self.assertIn("Added listener friends", out) + rows = {r["name"]: r for r in json.loads(ok(ctl.cmd_inbounds, "users", "--json"))} + self.assertEqual(rows["alice"]["listeners"], ["friends", "vless-in"]) + self.assertEqual(rows["bob"]["source"], "nix") + self.assertEqual(ctl._inbound_runtime_names("listeners", "runtime"), {"friends": "runtime"}) + status, _, err = run(ctl.cmd_inbounds, "bind", "bob", "vless-in") + self.assertEqual(status, 1) + self.assertIn("declared in the configuration", err) + # A refusal changes nothing, so nothing is reloaded. + self.assertEqual(len(self.started), 2) + ok(ctl.cmd_inbounds, "rm", "friends") + self.assertIn("vless-in", ok(ctl.cmd_inbounds, "users")) + + def test_bad_listener_is_refused(self): + status, _, err = run(ctl.cmd_inbounds, "add", "far", "vless", "--port", "30000") + self.assertEqual(status, 1) + self.assertIn("not in inbounds.runtime.ports", err) + self.assertEqual(self.started, []) + + def test_off(self): + os.environ["INBOUNDS_RUNTIME_ENABLED"] = "0" + spec = ctl.read_json(os.environ["INBOUNDS_SPEC_FILE"]) + spec["runtime"] = None + os.environ["INBOUNDS_SPEC_FILE"] = self.write("spec-off.json", spec) + status, _, err = run(ctl.cmd_inbounds, "users", "add", "alice") + self.assertEqual(status, 1) + self.assertIn("inbounds.runtime.enable", err) + # The declared users are still listed, on a listener or not. + rows = {r["name"]: r for r in ctl._inbound_runtime_rows("users")} + self.assertEqual(rows["bob"]["listeners"], ["vless-in"]) + self.assertEqual(rows["idle"]["listeners"], []) + self.assertIn("idle", ok(ctl.cmd_inbounds, "users")) + os.environ["INBOUNDS_ENABLED"] = "0" + self.assertEqual(ctl._inbound_runtime_rows("users"), []) + + def test_completion(self): + ok(ctl.cmd_inbounds, "users", "add", "alice") + self.assertIn("alice", ctl._complete_tree("inbounds", "users", "rm", "")) + self.assertNotIn("bob", ctl._complete_tree("inbounds", "users", "rm", "")) + self.assertIn("--reality", ctl._complete_tree("inbounds", "add", "x", "vless", "")) + + class ShareTest(EnvTest): def setUp(self): super().setUp() diff --git a/pkgs/proxy-ctl/test_proxy_model.py b/pkgs/proxy-ctl/test_proxy_model.py index 6993376..93785de 100644 --- a/pkgs/proxy-ctl/test_proxy_model.py +++ b/pkgs/proxy-ctl/test_proxy_model.py @@ -103,6 +103,37 @@ class ModelTest(unittest.TestCase): self.assertTrue(actions["k"].when(awg) and actions["K"].when(awg) and actions["J"].when(vless)) self.assertFalse(actions["k"].when(vless) or actions["K"].when(vless) or actions["J"].when(awg)) + def test_runtime_inbound_users_and_listeners(self): + users = next(t for t in model.TABS if t.id == "inbound-users") + inbounds = next(t for t in model.TABS if t.id == "inbounds") + with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "1", "INBOUNDS_RUNTIME_ENABLED": "0"}): + # Listed from the configuration; nothing to change them with. + self.assertTrue(users.available({})) + self.assertEqual([a.key for a in users.actions if model.offered(a)], ["t"]) + self.assertNotIn("a", [a.key for a in inbounds.actions if model.offered(a)]) + with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "0"}): + self.assertFalse(users.available({})) + with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "1", "INBOUNDS_RUNTIME_ENABLED": "1"}): + self.assertTrue(users.available({})) + rows = [{"name": "bob", "source": "nix", "order": 1, "address": "10.78.0.1", "listeners": ["in"], "problems": []}, + {"name": "alice", "source": "runtime", "order": 4, "address": "", "listeners": [], "problems": ["no listeners"]}] + with mock.patch.object(ctl, "_inbound_runtime_rows", lambda kind: rows): + bob, alice = model.inbound_user_rows({}) + self.assertEqual((bob["listeners"], alice["problems"]), ("in", "no listeners")) + actions = {a.key: a for a in users.actions} + self.assertEqual(actions["n"].argv(None, "carol 7 in ws", {}), + ["inbounds", "users", "add", "carol", "--order", "7", "--listener", "in", "--listener", "ws"]) + self.assertEqual(actions["n"].argv(None, "carol", {}), ["inbounds", "users", "add", "carol"]) + self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "u", "t"]) + self.assertEqual(actions["e"].argv(alice, " 9 ", {}), ["inbounds", "users", "order", "alice", "9"]) + self.assertEqual(actions["b"].argv(alice, "in", {}), ["inbounds", "bind", "alice", "in"]) + actions = {a.key: a for a in inbounds.actions} + row = {"key": "friends/alice", "tag": "friends", "user": "alice", "type": "vless", "port": "20001", "source": "runtime"} + self.assertEqual(actions["a"].argv(None, "friends vless --port 20001", {}), ["inbounds", "add", "friends", "vless", "--port", "20001"]) + self.assertEqual(actions["d"].argv(row), ["inbounds", "rm", "friends"]) + self.assertFalse(actions["d"].when({**row, "source": "nix"})) + self.assertEqual(actions["b"].argv(row, "bob", {}), ["inbounds", "bind", "bob", "friends"]) + def test_inbound_rows_carry_no_presence(self): """XRay keys the online map by user, not by inbound, so a per-listener row could only repeat one verdict per listener; it must not claim to have one.""" diff --git a/scripts/awg_inbound.py b/scripts/awg_inbound.py index cbb5233..c266aab 100644 --- a/scripts/awg_inbound.py +++ b/scripts/awg_inbound.py @@ -21,6 +21,7 @@ import sys from pathlib import Path from typing import Any +import inbound_runtime from amneziawg_config import ( ConfigError, _apply_awg3_mtu_default, @@ -359,9 +360,21 @@ def prepare(spec: dict, awg_binary: str, runtime_dir: str) -> list[dict]: "implementation": transport_implementation(config), } ) + # Who is on which interface now: inbound_runtime.py's check tells from it whether a + # runtime change needs these interfaces restarted too. + write_private(os.path.join(runtime_dir, "users.json"), json.dumps(awg_users(spec)) + "\n") return prepared +def awg_users(spec: dict) -> dict[str, list[str]]: + """Each AmneziaWG listener's users, by tag.""" + return { + listener["tag"]: sorted(user["name"] for user in listener["users"]) + for listener in spec["listeners"] + if listener.get("type") == "amneziawg" + } + + def peer_names(spec: dict) -> dict[str, dict]: """By interface: the listener's tag and its users' names by public key.""" result: dict[str, dict] = {} @@ -431,6 +444,8 @@ def main() -> int: with open(args.spec, encoding="utf-8") as handle: spec = json.load(handle) try: + # Runtime users on AmneziaWG listeners are peers like the declared ones. + spec, _, _ = inbound_runtime.merge(spec) if args.command == "prepare": # One line per listener, for the start script to read. for entry in prepare(spec, args.awg, args.runtime_dir): diff --git a/scripts/build-inbound.py b/scripts/build-inbound.py index 864791a..a36fffd 100644 --- a/scripts/build-inbound.py +++ b/scripts/build-inbound.py @@ -5,6 +5,7 @@ import argparse import json import sys +import inbound_runtime from proxy_inbound import build_inbounds @@ -25,6 +26,11 @@ def main() -> None: dest="onion_address", help="the onion service's address, for a second set of links to its listeners", ) + ap.add_argument( + "--template", + help="the XRay config template: with inbounds.runtime, the result also carries its " + "routing rules with the runtime listeners and users in", + ) args = ap.parse_args() with open(args.spec, encoding="utf-8") as handle: @@ -36,7 +42,14 @@ def main() -> None: sys.exit(1) try: + spec, runtime, warnings = inbound_runtime.merge(spec, check_ports=True) + for warning in warnings: + print(f"proxy-suite: warning: {warning}", file=sys.stderr) result = build_inbounds(spec, server_address, args.onion_address) + if args.template and spec.get("runtime"): + with open(args.template, encoding="utf-8") as handle: + template = json.load(handle) + result.update(inbound_runtime.routing(spec, runtime, template["routing"]["rules"])) except (ValueError, OSError) as exc: print(f"error: {exc}", file=sys.stderr) sys.exit(1) diff --git a/scripts/inbound_runtime.py b/scripts/inbound_runtime.py new file mode 100644 index 0000000..56fb9bb --- /dev/null +++ b/scripts/inbound_runtime.py @@ -0,0 +1,1317 @@ +#!/usr/bin/env python3 +"""Inbound users and listeners added at runtime (services.proxy-suite.inbounds.runtime). + +They live in a spool directory, one JSON file each: users/.json and +listeners/.json. proxy-ctl writes them through this script's commands, as the user +who runs it; the inbound services merge them into the spec Nix generated when they start +(merge()), as root, so XRay, the AmneziaWG interfaces and the share links all see the same +set. + +A runtime user holds its own secrets, generated when it is added, and the listeners it is +bound to: any listener, declared or runtime. A runtime listener has the shape of an +`inbounds.listeners.` entry, filled in with the option's defaults, plus the users it +accepts, declared or runtime. Whatever such a listener could reach beyond its port is +fenced by the spec: its ports, exits, certificates (by name, never a path) and fallbacks. + +Runtime entries never break the declared configuration: one that does not hold up is left +out with a warning when the services start, and refused when proxy-ctl adds it. +""" + +from __future__ import annotations + +import argparse +import base64 +import copy +import hashlib +import ipaddress +import json +import os +import re +import secrets +import socket +import stat +import subprocess +import sys +import uuid + +# User names and listener tags: they become file names, XRay emails and tags, and URL parts. +NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,31}") +MAX_ENTRY_BYTES = 65536 +# The stats API's inbound, in the same config. +RESERVED_TAGS = ("api-in",) + +UUID_TYPES = ("vless", "vmess") +PASSWORD_TYPES = ("trojan", "hysteria2", "shadowsocks", "socks", "http") +TYPES = UUID_TYPES + PASSWORD_TYPES +TRANSPORTS = ("raw", "ws", "grpc", "httpupgrade", "xhttp") +XHTTP_MODES = ("auto", "packet-up", "stream-up", "stream-one") +ALPNS = ("h3", "h2", "http/1.1") +# Shadowsocks 2022 keys, by method: bytes of base64 key. +SS2022_KEY_BYTES = { + "2022-blake3-aes-128-gcm": 16, + "2022-blake3-aes-256-gcm": 32, + "2022-blake3-chacha20-poly1305": 32, +} +SS_METHODS = ( + *SS2022_KEY_BYTES, + "aes-128-gcm", + "aes-256-gcm", + "chacha20-poly1305", + "chacha20-ietf-poly1305", + "xchacha20-poly1305", + "xchacha20-ietf-poly1305", + "none", +) + + +class RuntimeError_(ValueError): + """A runtime entry that cannot be used, or a command that cannot be carried out.""" + + +# --- the spool ------------------------------------------------------------------------ + + +def _read_entry(path: str) -> dict: + """One spool file, as root reads it: a regular file only, never through a symlink, + which would hand over any file root can read, nor a FIFO, which would hang the start.""" + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError as exc: + raise RuntimeError_(f"cannot read {path}: {exc.strerror}") from None + with os.fdopen(fd, "rb") as handle: + info = os.fstat(handle.fileno()) + if not stat.S_ISREG(info.st_mode): + raise RuntimeError_(f"{path} is not a regular file") + if info.st_size > MAX_ENTRY_BYTES: + raise RuntimeError_(f"{path} is larger than {MAX_ENTRY_BYTES} bytes") + data = handle.read(MAX_ENTRY_BYTES + 1) + try: + value = json.loads(data.decode("utf-8")) + except (UnicodeDecodeError, ValueError) as exc: + raise RuntimeError_(f"{path} is not valid JSON: {exc}") from None + if not isinstance(value, dict): + raise RuntimeError_(f"{path} must hold a JSON object") + return value + + +def _entries(directory: str, warnings: list[str], what: str) -> dict[str, dict]: + try: + names = sorted(os.listdir(directory)) + except FileNotFoundError: + return {} + except OSError as exc: + warnings.append(f"cannot list {directory}: {exc.strerror}") + return {} + entries = {} + for file_name in names: + if file_name.startswith(".") or not file_name.endswith(".json"): + continue + name = file_name[: -len(".json")] + if not NAME.fullmatch(name): + warnings.append(f"ignoring runtime {what} '{name}': not a valid name") + continue + try: + entries[name] = _read_entry(os.path.join(directory, file_name)) + except RuntimeError_ as exc: + warnings.append(f"ignoring runtime {what} '{name}': {exc}") + return entries + + +def load_spool(spool: str) -> tuple[dict, list[str]]: + """{"users": {name: entry}, "listeners": {tag: entry}} and what could not be read.""" + warnings: list[str] = [] + if not spool: # no inbounds.runtime: nothing but the declared + return {"users": {}, "listeners": {}}, warnings + state = { + "users": _entries(os.path.join(spool, "users"), warnings, "user"), + "listeners": _entries(os.path.join(spool, "listeners"), warnings, "listener"), + } + return state, warnings + + +def write_entry(spool: str, kind: str, name: str, entry: dict) -> None: + """Replace one spool file whole. Group-readable: the setgid spool gives it the + userControl group, whose "inbounds" scope added it.""" + directory = os.path.join(spool, kind) + old = os.umask(0o027) + try: + os.makedirs(directory, exist_ok=True) + path = os.path.join(directory, f"{name}.json") + tmp = os.path.join(directory, f".{name}.json.tmp") + with open(tmp, "w", encoding="utf-8") as handle: + handle.write(json.dumps(entry, indent=2, sort_keys=True) + "\n") + os.replace(tmp, path) + finally: + os.umask(old) + + +def remove_entry(spool: str, kind: str, name: str) -> None: + os.unlink(os.path.join(spool, kind, f"{name}.json")) + + +# --- the shape of entries ------------------------------------------------------------- + + +def _is_port(value) -> bool: + return type(value) is int and 1 <= value <= 65535 + + +def _nonspace(value) -> bool: + return isinstance(value, str) and value != "" and not re.search(r"\s", value) + + +def _strings(value) -> bool: + return isinstance(value, list) and all(isinstance(item, str) for item in value) + + +def _nullable(check): + return lambda value: value is None or check(value) + + +def _one_of(*choices): + return lambda value: value in choices + + +def _is_bool(value) -> bool: + return type(value) is bool + + +def _is_str(value) -> bool: + return isinstance(value, str) + + +def _is_alpn(value) -> bool: + return isinstance(value, list) and all(item in ALPNS for item in value) + + +# What a runtime listener's JSON may set, and how. The file fields of the option are not +# here: a runtime listener names nothing on disk. Nor raw JSON, AmneziaWG or port hopping, +# which need more than XRay (interfaces, nftables) and are built in Nix. +LISTENER_SCHEMA = { + "type": _one_of(*TYPES), + "port": _is_port, + "sharePort": _nullable(_is_port), + "shareAddress": _nullable(_nonspace), + "address": _nonspace, + "acceptProxyProtocol": _is_bool, + "via": _nullable(_nonspace), + "order": lambda value: type(value) is int, + "users": lambda value: isinstance(value, list) and all(isinstance(n, str) and NAME.fullmatch(n) for n in value), + "flow": _nullable(_one_of("xtls-rprx-vision")), + "method": _one_of(*SS_METHODS), + "serverPassword": _nullable(_nonspace), + "transport": { + "type": _one_of(*TRANSPORTS), + "path": _is_str, + "host": _nullable(_nonspace), + "mode": _nullable(_one_of(*XHTTP_MODES)), + "serviceName": _is_str, + "trustedXForwardedFor": _strings, + }, + "tls": { + "enable": _is_bool, + "certificate": _nullable(_nonspace), + "serverName": _nullable(_nonspace), + "alpn": _nullable(_is_alpn), + }, + "reality": { + "enable": _is_bool, + "dest": _nonspace, + "serverNames": _strings, + "privateKey": _nullable(_nonspace), + "publicKey": _nullable(_nonspace), + "shortIds": lambda value: _strings(value) and all(re.fullmatch(r"[0-9a-fA-F]{0,16}", i) for i in value), + "xver": _one_of(0, 1, 2), + }, + "fallbacks": "fallbacks", + "hysteria": { + "masquerade": _nullable(_nonspace), + "salamander": { + "enable": _is_bool, + "password": _nullable(_nonspace), + }, + }, +} + +FALLBACK_SCHEMA = { + "name": _nullable(_nonspace), + "alpn": _nullable(_one_of("h2", "http/1.1")), + "path": _nullable(_is_str), + "dest": _nullable(lambda value: _is_port(value) or _nonspace(value)), + "listener": _nullable(lambda value: isinstance(value, str) and bool(NAME.fullmatch(value))), + "xver": _one_of(0, 1, 2), +} + +USER_SCHEMA = { + "order": lambda value: type(value) is int and value >= 1, + "uuid": lambda value: isinstance(value, str) and _is_uuid(value), + "password": _nonspace, + "listeners": lambda value: isinstance(value, list) and all(isinstance(n, str) and NAME.fullmatch(n) for n in value), +} + + +def _is_uuid(value: str) -> bool: + try: + uuid.UUID(value) + except ValueError: + return False + return True + + +def _check_shape(value: dict, schema: dict, where: str) -> None: + for key, item in value.items(): + rule = schema.get(key) + if rule is None: + raise RuntimeError_(f"{where}{key}: not something a runtime entry can set") + if rule == "fallbacks": + if not isinstance(item, list) or not all(isinstance(fb, dict) for fb in item): + raise RuntimeError_(f"{where}{key}: must be a list of objects") + for index, fallback in enumerate(item): + _check_shape(fallback, FALLBACK_SCHEMA, f"{where}{key}[{index}].") + elif isinstance(rule, dict): + if not isinstance(item, dict): + raise RuntimeError_(f"{where}{key}: must be an object") + _check_shape(item, rule, f"{where}{key}.") + elif not rule(item): + raise RuntimeError_(f"{where}{key}: invalid value {json.dumps(item)}") + + +def check_user_shape(entry: dict) -> None: + _check_shape(entry, USER_SCHEMA, "") + for key in ("order", "uuid", "password"): + if key not in entry: + raise RuntimeError_(f"{key} is missing") + + +def check_listener_shape(entry: dict) -> None: + _check_shape(entry, LISTENER_SCHEMA, "") + if "type" not in entry: + raise RuntimeError_("type is missing") + + +def _deep_merge(base, override): + if isinstance(base, dict) and isinstance(override, dict): + merged = dict(base) + for key, value in override.items(): + merged[key] = _deep_merge(base.get(key), value) + return merged + return copy.deepcopy(override) + + +# --- ports ---------------------------------------------------------------------------- + + +def _port_ranges(ports: list) -> list[tuple[int, int]]: + ranges = [] + for item in ports: + if isinstance(item, int): + ranges.append((item, item)) + else: + low, high = (int(part) for part in str(item).split("-", 1)) + ranges.append((low, high)) + return ranges + + +def _port_allowed(port: int, ports: list) -> bool: + return any(low <= port <= high for low, high in _port_ranges(ports)) + + +def _udp_only(listener: dict) -> bool: + tls = listener["tls"] + return listener["type"] == "hysteria2" or ( + listener["transport"]["type"] == "xhttp" and tls["enable"] and tls.get("alpn") == ["h3"] + ) + + +def _protocols(listener: dict) -> list[int]: + if _udp_only(listener): + return [socket.SOCK_DGRAM] + if listener["type"] in ("shadowsocks", "socks"): + return [socket.SOCK_STREAM, socket.SOCK_DGRAM] + return [socket.SOCK_STREAM] + + +def port_free(address: str, port: int, kinds: list[int]) -> bool: + """Whether XRay could bind this: a runtime listener on a port something else holds would + stop XRay, and every declared listener with it.""" + try: + infos = socket.getaddrinfo(address, port, 0, 0, 0, socket.AI_PASSIVE) + except OSError: + return False + for kind in kinds: + for family, _, _, _, sockaddr in infos: + try: + with socket.socket(family, kind) as sock: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if family == socket.AF_INET6: + sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) + sock.bind(sockaddr) + except OSError: + return False + break + return True + + +def _loopback(address: str) -> bool: + return address.startswith("127.") or address in ("::1", "localhost") + + +# --- users ---------------------------------------------------------------------------- + + +def _ss_key(method: str, password: str) -> str: + """A runtime user's key for a Shadowsocks 2022 listener: its password stretched or cut + to the method's key length, so one stored password serves every cipher.""" + size = SS2022_KEY_BYTES[method] + digest = hashlib.sha256(("proxy-suite-shadowsocks\n" + password).encode("utf-8")).digest() + return base64.b64encode(digest[:size]).decode("ascii") + + +def _runtime_user(name: str, entry: dict) -> dict: + """A runtime user as the renderers take a declared one.""" + return { + "name": name, + "order": entry["order"], + "uuid": entry["uuid"], + "uuidFile": None, + "password": entry["password"], + "passwordFile": None, + "publicKey": None, + "privateKeyFile": None, + "presharedKeyFile": None, + "address": None, + "runtime": True, + } + + +def _user_for(user: dict, listener: dict) -> dict: + """The user as this listener takes it: a Shadowsocks 2022 listener, a key of its length.""" + if user.get("runtime") and listener.get("type") == "shadowsocks" and listener.get("method") in SS2022_KEY_BYTES: + return {**user, "password": _ss_key(listener["method"], user["password"])} + return user + + +def _user_problem(user: dict, listener_type: str) -> str | None: + """Why a user cannot be on a listener of this type, or None.""" + if listener_type in UUID_TYPES and user.get("uuid") is None and user.get("uuidFile") is None: + return f"user '{user['name']}' has no uuid, which {listener_type} needs" + if listener_type in PASSWORD_TYPES and user.get("password") is None and user.get("passwordFile") is None: + return f"user '{user['name']}' has no password, which {listener_type} needs" + return None + + +def new_user(order: int, listeners: list[str]) -> dict: + return { + "order": order, + "uuid": str(uuid.uuid4()), + "password": secrets.token_urlsafe(18), + "listeners": listeners, + } + + +# --- listeners ------------------------------------------------------------------------ + + +def listener_problems(listener: dict, runtime: dict, share_links: bool) -> list[str]: + """The declared listeners' assertions (service-assertions.nix), for a runtime listener + filled in with the defaults and its users, plus the fences of inbounds.runtime.""" + problems = [] + + def need(condition: bool, message: str) -> None: + if not condition: + problems.append(message) + + kind = listener["type"] + transport = listener["transport"] + tls = listener["tls"] + reality = listener["reality"] + hysteria = listener["hysteria"] + users = listener["users"] + tls_terminated = tls["enable"] or kind in ("trojan", "hysteria2") + + need(_port_allowed(listener["port"], runtime.get("ports") or []), + f"port {listener['port']} is not in inbounds.runtime.ports") + need(listener["via"] in runtime.get("vias") or [], + f"via '{listener['via']}' is not routing.via, \"block\" or in inbounds.runtime.vias") + need(not (tls["enable"] and reality["enable"]), "tls and reality are mutually exclusive") + need(len({user["name"] for user in users}) == len(users), "users must each have a distinct name") + multi_ss = kind == "shadowsocks" and len(users) > 1 + need(not multi_ss or listener["method"].startswith("2022-blake3-aes-"), + "shadowsocks with more than one user needs a 2022-blake3-aes-* method") + need(not multi_ss or listener.get("serverPassword") is not None, + "shadowsocks with more than one user needs serverPassword") + need(not reality["enable"] or transport["type"] in ("raw", "xhttp", "grpc"), + "reality only runs over the raw, xhttp and grpc transports") + need(not share_links or not reality["enable"] or kind in ("vless", "trojan"), + "share links carry reality only for vless and trojan") + need(not share_links or not tls["enable"] or kind not in ("shadowsocks", "socks"), + f"share links cannot carry tls for {kind}") + if reality["enable"]: + need(reality.get("privateKey") is not None, "reality needs privateKey") + need(bool(reality["serverNames"]), "reality.serverNames must not be empty") + need(not share_links or reality.get("publicKey") is not None, "reality needs publicKey for share links") + if tls_terminated and not reality["enable"]: + certificate = tls.get("certificate") + need(certificate is not None, "TLS needs tls.certificate, one of inbounds.runtime.tlsCertificates") + need(certificate is None or certificate in (runtime.get("tlsCertificates") or {}), + f"tls.certificate '{certificate}' is not in inbounds.runtime.tlsCertificates") + need(listener.get("flow") is None or (kind == "vless" and transport["type"] == "raw"), + 'flow is only valid on a vless listener with transport.type = "raw"') + alpn = tls.get("alpn") + need(alpn is None or "h3" not in alpn or kind == "hysteria2" + or (transport["type"] == "xhttp" and tls["enable"] and not reality["enable"]), + 'tls.alpn "h3" is served only by hysteria2, and by the xhttp transport with tls') + need(kind != "hysteria2" or (not reality["enable"] and transport["type"] == "raw"), + "hysteria2 takes no reality or transport") + need(hysteria.get("masquerade") is None or kind == "hysteria2", + "hysteria.masquerade is for hysteria2 listeners only") + need(not hysteria["salamander"]["enable"] or kind == "hysteria2", + "hysteria.salamander is for hysteria2 listeners only") + need(not listener["acceptProxyProtocol"] or not _udp_only(listener), + "acceptProxyProtocol is for TCP listeners") + need(not listener["fallbacks"] or (kind in ("vless", "trojan") and transport["type"] == "raw"), + 'fallbacks run only on a vless or trojan listener with transport.type = "raw"') + for fallback in listener["fallbacks"]: + has_dest = fallback.get("dest") is not None + has_listener = fallback.get("listener") is not None + need(has_dest != has_listener, "fallbacks each need exactly one of dest or listener") + if has_dest: + need(fallback["dest"] in (runtime.get("fallbackDests") or []), + f"fallback dest {json.dumps(fallback['dest'])} is not in inbounds.runtime.fallbackDests") + return problems + + +def _fallback_target_problems(listener: dict, target: dict | None, fallback: dict) -> list[str]: + name = fallback["listener"] + if target is None or target["tag"] == listener["tag"]: + return [f"fallback listener '{name}' must be another runtime listener"] + problems = [] + if not ( + target["type"] == "vless" + and not target["tls"]["enable"] + and not target["reality"]["enable"] + and (target["listen"].startswith("127.") or target["listen"] == "::1") + ): + problems.append(f"fallback listener '{name}' must be a vless listener, without tls or reality, on a loopback address") + if fallback.get("path") is not None and not ( + target["transport"]["type"] in ("ws", "httpupgrade") and fallback["path"] == target["transport"]["path"] + ): + problems.append(f"fallback path matches only a ws or httpupgrade listener '{name}', and must be its transport.path") + if listener["reality"]["enable"] and target["transport"]["type"] not in ("xhttp", "grpc"): + problems.append(f"a REALITY listener's fallback listener '{name}' must use the xhttp or grpc transport") + return problems + + +def _render_listener(tag: str, entry: dict, runtime: dict) -> dict: + """A runtime listener, filled in with the defaults, in the spec's shape (config.nix).""" + filled = _deep_merge(runtime.get("listenerDefaults") or {}, {k: v for k, v in entry.items() if k != "users"}) + filled["tag"] = tag + filled["runtime"] = True + filled["via"] = filled.get("via") or runtime.get("defaultVia") or "proxy" + filled["listen"] = filled.pop("address", "::") + tls = filled.setdefault("tls", {}) + certificate = (runtime.get("tlsCertificates") or {}).get(tls.get("certificate") or "") + tls["certificateFile"] = certificate["certificateFile"] if certificate else None + tls["keyFile"] = certificate["keyFile"] if certificate else None + if certificate and tls.get("serverName") is None: + tls["serverName"] = certificate.get("serverName") + hysteria = filled.setdefault("hysteria", {}) + hysteria["portHopping"] = None + hysteria.setdefault("salamander", {})["passwordFile"] = None + filled["serverPasswordFile"] = None + filled["xrayJson"] = None + filled["jsonFile"] = None + filled["front"] = None + filled["salamanderStateFile"] = os.path.join(runtime.get("salamanderStateDir") or "/var/lib/proxy-suite/inbounds", tag, "salamander-password") + filled["users"] = [] + return filled + + +def _render_fallbacks(listener: dict, by_tag: dict) -> None: + rendered = [] + for fallback in listener["fallbacks"]: + entry = {key: fallback.get(key) for key in ("name", "alpn", "path")} + if fallback.get("listener") is None: + entry.update({"dest": fallback.get("dest"), "xver": fallback.get("xver", 0)}) + else: + target = by_tag[fallback["listener"]] + host = f"[{target['listen']}]" if ":" in target["listen"] else target["listen"] + entry.update({"dest": f"{host}:{target['port']}", "xver": 2}) + target["front"] = { + key: listener[key] for key in ("tag", "type", "port", "sharePort", "shareAddress", "tls", "reality") + } + rendered.append(entry) + listener["fallbacks"] = rendered + + +# --- the merge ------------------------------------------------------------------------ + + +# The declared users and their serverSource numbers are the spec's own, there with runtime +# or without: `inbounds users` lists them either way. + + +def _declared_users(spec: dict) -> dict[str, dict]: + return spec.get("users") or {} + + +def _declared_numbers(spec: dict) -> dict[str, int]: + return {entry["name"]: entry["number"] for entry in (spec.get("serverSource") or {}).get("declared", [])} + + +def taken_orders(spec: dict) -> set[int]: + """Numbers a runtime user cannot have: the declared users' orders and serverSource numbers.""" + taken = set(_declared_numbers(spec).values()) + taken.update(user["order"] for user in _declared_users(spec).values() if user.get("order") is not None) + return taken + + +def number_users(spec: dict, names: list[str], state_users: dict, warnings: list[str]) -> list[dict]: + """The runtime users' serverSource numbers and addresses: their own order, unless a + declared user holds it, which moves them to the next free one.""" + source = spec.get("serverSource") or {} + if source.get("ipv4") is None and source.get("ipv6") is None: + return [] + taken = taken_orders(spec) + size = None + if source.get("ipv4") is not None: + size = ipaddress.ip_network(source["ipv4"], strict=False).num_addresses + numbered = [] + for name in sorted(names, key=lambda n: (state_users[n]["order"], n)): + wanted = number = state_users[name]["order"] + while number in taken: + number += 1 + if number != wanted: + warnings.append(f"runtime user '{name}': order {wanted} is taken; using {number} until it is free") + if size is not None and number + 2 > size: + warnings.append(f"runtime user '{name}': number {number} does not fit in serverSource.ipv4; no own address") + continue + taken.add(number) + numbered.append( + { + "email": name, + "number": number, + "id": str(number), + "ipv4": None if source.get("ipv4") is None + else str(ipaddress.ip_network(source["ipv4"], strict=False).network_address + number), + "ipv6": None if source.get("ipv6") is None + else source["ipv6"].split("/", 1)[0] + format(number, "x"), + } + ) + return numbered + + +def merge_state(spec: dict, state: dict, check_ports: bool = False) -> tuple[dict, dict, list[str]]: + """The spec with the runtime entries merged in, what was made of them, and warnings. + + The result's "runtime" key holds {"listeners": [runtime tags kept], "users": [runtime + names kept], "selfSources": [...], "problems": {("user"|"listener", name): [why]}}. + """ + runtime = spec.get("runtime") + merged = copy.deepcopy(spec) + result = {"listeners": [], "users": [], "selfSources": [], "problems": {}} + if not runtime: + return merged, result, [] + warnings: list[str] = [] + problems: dict = result["problems"] + + def problem(kind: str, name: str, message: str) -> None: + problems.setdefault((kind, name), []).append(message) + warnings.append(f"runtime {kind} '{name}': {message}") + + share_links = spec.get("shareLinks", True) + declared_users = _declared_users(spec) + declared = {listener["tag"]: listener for listener in merged["listeners"]} + + users: dict[str, dict] = {} + for name, entry in state["users"].items(): + try: + check_user_shape(entry) + except RuntimeError_ as exc: + problem("user", name, str(exc)) + continue + if name in declared_users: + problem("user", name, "a declared user has this name") + continue + users[name] = _runtime_user(name, entry) + + def user_named(name: str) -> dict | None: + if name in users: + return users[name] + if name in declared_users: + return {**declared_users[name], "name": name} + return None + + # Runtime listeners: shape, fences, users. + runtime_listeners: dict[str, dict] = {} + for tag, entry in sorted(state["listeners"].items()): + try: + check_listener_shape(entry) + except RuntimeError_ as exc: + problem("listener", tag, str(exc)) + continue + if tag in declared or tag in RESERVED_TAGS: + problem("listener", tag, "a declared listener has this tag") + continue + listener = _render_listener(tag, entry, runtime) + for name in entry.get("users", []): + user = user_named(name) + if user is None: + problem("listener", tag, f"user '{name}' does not exist; left out") + continue + why = _user_problem(user, listener["type"]) + if why: + problem("listener", tag, f"{why}; left out") + continue + listener["users"].append(user) + runtime_listeners[tag] = listener + + # Runtime users onto the listeners they name, declared or runtime. + for name in sorted(users): + for tag in state["users"][name].get("listeners", []): + target = declared.get(tag) or runtime_listeners.get(tag) + if target is None: + problem("user", name, f"listener '{tag}' does not exist; not bound") + continue + if any(user["name"] == name for user in target["users"]): + continue + why = _user_problem(users[name], target["type"]) if target.get("type") else "it is a raw JSON listener" + if why: + problem("user", name, f"cannot be on '{tag}': {why}") + continue + candidate = users[name] + if tag in declared and target["type"] == "shadowsocks" and target["users"]: + if not target["method"].startswith("2022-blake3-aes-") or ( + target.get("serverPassword") is None and target.get("serverPasswordFile") is None + ): + problem("user", name, f"cannot be on '{tag}': a second shadowsocks user needs a 2022-blake3-aes method and a server password") + continue + target["users"].append(candidate) + + # Ports, fences and the declared assertions, on the listeners as they now stand. + declared_ports = {listener["port"] for listener in merged["listeners"]} + used_ports: set[int] = set() + for tag in sorted(runtime_listeners, key=lambda t: (runtime_listeners[t]["order"], t)): + listener = runtime_listeners[tag] + why = listener_problems(listener, runtime, share_links) + if listener["port"] in declared_ports or listener["port"] in used_ports: + why.append(f"port {listener['port']} is taken by another listener") + if not why and check_ports and not port_free(listener["listen"], listener["port"], _protocols(listener)): + why.append(f"port {listener['port']} is in use on this host") + if why: + for message in why: + problem("listener", tag, message) + del runtime_listeners[tag] + continue + used_ports.add(listener["port"]) + + # Fallbacks to other runtime listeners, which must be there and fit, each behind one front + # only. Until nothing changes: a front left out can leave another's target without it. + changed = True + while changed: + changed = False + fronted: dict[str, str] = {} + for tag in sorted(runtime_listeners): + listener = runtime_listeners[tag] + targets = [fb for fb in listener["fallbacks"] if fb.get("listener") is not None] + why = [] + for fallback in targets: + why += _fallback_target_problems(listener, runtime_listeners.get(fallback["listener"]), fallback) + if fallback["listener"] in fronted: + why.append(f"'{fallback['listener']}' is already the fallback listener of '{fronted[fallback['listener']]}'") + if why: + for message in why: + problem("listener", tag, message) + del runtime_listeners[tag] + changed = True + break + fronted.update({fb["listener"]: tag for fb in targets}) + for listener in runtime_listeners.values(): + _render_fallbacks(listener, runtime_listeners) + + # Every listener's users as it takes them; listeners without any are left out. + kept = [] + for listener in merged["listeners"] + list(runtime_listeners.values()): + listener["users"] = [_user_for(user, listener) for user in listener["users"]] + if not listener["users"] and listener.get("type") not in (None, "amneziawg"): + if listener.get("runtime"): + warnings.append(f"runtime listener '{listener['tag']}' has no users yet; not started") + else: + warnings.append(f"listener '{listener['tag']}' has no users yet; not started") + continue + kept.append(listener) + merged["listeners"] = sorted(kept, key=lambda listener: (listener.get("order", 1000), listener["tag"])) + result["listeners"] = sorted(t for t in runtime_listeners if any(l["tag"] == t for l in kept)) + + # serverSource numbers, for the users XRay's listeners accept. + on_xray = { + user["name"] + for listener in merged["listeners"] + if listener.get("type") != "amneziawg" + for user in listener["users"] + if user.get("runtime") + } + result["users"] = sorted(users) + result["selfSources"] = number_users(spec, sorted(on_xray), state["users"], warnings) + return merged, result, warnings + + +def merge(spec: dict, check_ports: bool = False) -> tuple[dict, dict, list[str]]: + """merge_state() on the spool the spec names, as the services read it at start.""" + runtime = spec.get("runtime") + if not runtime: + return spec, {"listeners": [], "users": [], "selfSources": [], "problems": {}}, [] + state, warnings = load_spool(runtime["spool"]) + merged, result, more = merge_state(spec, state, check_ports) + return merged, result, warnings + more + + +# --- routing -------------------------------------------------------------------------- + + +def _member(rule: dict, via: str) -> bool: + members = rule["_members"] + if "via" in members and via not in members["via"]: + return False + return not ("notVia" in members and via in members["notVia"]) + + +def _self_rules(anchor: dict, source: dict) -> list[dict]: + """A runtime user's serverSource rules, as rules/proxy-inbounds.nix makes a declared one's.""" + common = { + "type": "field", + "user": [source["email"]], + "inboundTag": list(anchor["inboundTag"]), + "port": anchor["port"], + "_members": anchor["_members"], + } + rules = [] + if anchor["_anchor"] == "selfIp": + if source["ipv4"] is not None and anchor.get("ip4"): + rules.append({**common, "ruleTag": f"inbound-server-address-self-ip4-{source['id']}", "ip": anchor["ip4"], + "outboundTag": f"direct-self4-{source['id']}"}) + if source["ipv6"] is not None and anchor.get("ip6"): + rules.append({**common, "ruleTag": f"inbound-server-address-self-ip6-{source['id']}", "ip": anchor["ip6"], + "outboundTag": f"direct-self6-{source['id']}"}) + elif anchor.get("domain"): + family = "4" if source["ipv4"] is not None else "6" + rules.append({**common, "ruleTag": f"inbound-server-address-self-{source['id']}", "domain": anchor["domain"], + "outboundTag": f"direct-self{family}-{source['id']}"}) + return rules + + +def expand_rules(rules: list[dict], listeners: list[dict], self_sources: list[dict], default_via: str) -> list[dict]: + """The template's routing rules with the runtime listeners and users in: their tags added + to the rules marked for their via, their serverSource rules at the anchors, their own + via rules before the final one. Marked rules nobody is left in go.""" + expanded = [] + for rule in rules: + if "_anchor" in rule: + for source in self_sources: + expanded.extend(_self_rules(rule, source)) + continue + expanded.append(dict(rule)) + result = [] + for rule in expanded: + if "_members" in rule: + tags = list(rule.get("inboundTag") or []) + tags += [listener["tag"] for listener in listeners if _member(rule, listener["via"]) and listener["tag"] not in tags] + rule.pop("_members") + if not tags: + continue + rule["inboundTag"] = tags + result.append(rule) + overrides = [ + {"type": "field", "ruleTag": f"inbound-via-{listener['tag']}", "inboundTag": [listener["tag"]], "outboundTag": listener["via"]} + for listener in listeners + if listener["via"] != default_via + ] + final = next((index for index, rule in enumerate(result) if rule.get("ruleTag") == "inbound-final"), len(result)) + return result[:final] + overrides + result[final:] + + +def self_outbounds(self_sources: list[dict], final_rules: list) -> list[dict]: + outbounds = [] + for source in self_sources: + for family, address in (("4", source["ipv4"]), ("6", source["ipv6"])): + if address is not None: + outbounds.append( + { + "protocol": "freedom", + "tag": f"direct-self{family}-{source['id']}", + "sendThrough": address, + "settings": {"domainStrategy": f"UseIPv{family}", "finalRules": final_rules}, + } + ) + return outbounds + + +def routing(spec: dict, result: dict, template_rules: list[dict]) -> dict: + """What the start script splices into the XRay config: the rules, the runtime users' + serverSource outbounds, and their addresses for the dummy interface.""" + runtime = spec.get("runtime") or {} + listeners = [listener for listener in spec["listeners"] if listener.get("runtime")] + return { + "rules": expand_rules(template_rules, listeners, result["selfSources"], runtime.get("defaultVia", "proxy")), + "selfOutbounds": self_outbounds(result["selfSources"], runtime.get("selfFinalRules") or []), + "selfAddresses": [{"ipv4": s["ipv4"], "ipv6": s["ipv6"]} for s in result["selfSources"]], + } + + +# --- proxy-ctl's commands ------------------------------------------------------------- + + +def _free_order(spec: dict, state: dict, skip: str = "") -> int: + taken = taken_orders(spec) | {entry.get("order") for name, entry in state["users"].items() if name != skip} + order = 1 + while order in taken: + order += 1 + return order + + +def _check_order(spec: dict, state: dict, order: int, name: str) -> None: + if order < 1: + raise RuntimeError_("An order is a number from 1 up.") + declared = {v: k for k, v in _declared_numbers(spec).items()} + declared.update({user["order"]: k for k, user in _declared_users(spec).items() if user.get("order") is not None}) + if order in declared: + raise RuntimeError_(f"Order {order} belongs to declared user '{declared[order]}'.") + for other, entry in state["users"].items(): + if other != name and entry.get("order") == order: + raise RuntimeError_(f"Order {order} belongs to runtime user '{other}'.") + + +def _listener_tags(spec: dict, state: dict) -> set[str]: + return {listener["tag"] for listener in spec["listeners"]} | set(state["listeners"]) + + +def _commit(spec: dict, state: dict, before: dict, changed: list[tuple[str, str]]) -> None: + """Refuse the change if it leaves one of the changed entries, or any entry that was + fine before, not holding up.""" + _, result_before, _ = merge_state(spec, before) + _, result, _ = merge_state(spec, state) + new = {key: msgs for key, msgs in result["problems"].items() if key in changed or key not in result_before["problems"]} + if new: + messages = [f"{kind} '{name}': {message}" for (kind, name), msgs in sorted(new.items()) for message in msgs] + raise RuntimeError_("\n".join(messages)) + + +def _require_name(name: str, what: str) -> None: + if not NAME.fullmatch(name or ""): + raise RuntimeError_(f"Invalid {what} '{name}': letters, digits, dot, dash and underscore, up to 32.") + + +def cmd_users_add(spec: dict, spool: str, name: str, order: int | None, listeners: list[str]) -> str: + state, _ = load_spool(spool) + before = copy.deepcopy(state) + _require_name(name, "user name") + if name in _declared_users(spec): + raise RuntimeError_(f"'{name}' is a declared user.") + if name in state["users"]: + raise RuntimeError_(f"A runtime user named '{name}' already exists.") + tags = _listener_tags(spec, state) + for tag in listeners: + if tag not in tags: + raise RuntimeError_(f"Unknown listener: {tag}") + if order is None: + order = _free_order(spec, state) + else: + _check_order(spec, state, order, name) + entry = new_user(order, list(dict.fromkeys(listeners))) + state["users"][name] = entry + _commit(spec, state, before, [("user", name)]) + write_entry(spool, "users", name, entry) + return f"Added user {name} (order {order})" + (f" on {', '.join(entry['listeners'])}" if entry["listeners"] else "") + + +def cmd_users_rm(spec: dict, spool: str, name: str) -> str: + state, _ = load_spool(spool) + if name in _declared_users(spec): + raise RuntimeError_(f"'{name}' is declared in the configuration; remove it there.") + if name not in state["users"]: + raise RuntimeError_(f"Unknown runtime user: {name}") + remove_entry(spool, "users", name) + for tag, entry in state["listeners"].items(): + if name in entry.get("users", []): + entry["users"] = [n for n in entry["users"] if n != name] + write_entry(spool, "listeners", tag, entry) + return f"Removed user {name}" + + +def cmd_users_order(spec: dict, spool: str, name: str, order: int) -> str: + state, _ = load_spool(spool) + if name in _declared_users(spec): + raise RuntimeError_(f"'{name}' is declared in the configuration; set its order there.") + if name not in state["users"]: + raise RuntimeError_(f"Unknown runtime user: {name}") + _check_order(spec, state, order, name) + state["users"][name]["order"] = order + write_entry(spool, "users", name, state["users"][name]) + return f"{name}: order {order}" + + +def cmd_bind(spec: dict, spool: str, user: str, tag: str, bind: bool) -> str: + state, _ = load_spool(spool) + before = copy.deepcopy(state) + declared_users = _declared_users(spec) + if user not in state["users"] and user not in declared_users: + raise RuntimeError_(f"Unknown user: {user}") + if tag not in _listener_tags(spec, state): + raise RuntimeError_(f"Unknown listener: {tag}") + if user in state["users"]: + kind, name, field, value = "users", user, "listeners", tag + elif tag in state["listeners"]: + kind, name, field, value = "listeners", tag, "users", user + else: + raise RuntimeError_(f"Both {user} and {tag} are declared in the configuration; bind them there.") + entry = state[kind][name] + current = entry.get(field, []) + if bind: + if value in current: + return f"{user} is already on {tag}" + entry[field] = [*current, value] + _commit(spec, state, before, [(kind[:-1], name)]) + else: + if value not in current: + raise RuntimeError_(f"{user} is not bound to {tag} at runtime.") + entry[field] = [v for v in current if v != value] + write_entry(spool, kind, name, entry) + return f"{'Bound' if bind else 'Unbound'} {user} {'to' if bind else 'from'} {tag}" + + +def _x25519(xray: str) -> tuple[str, str]: + """A REALITY key pair from `xray x25519`, whose labels vary between versions.""" + try: + out = subprocess.run([xray, "x25519"], capture_output=True, text=True, check=True).stdout + except (OSError, subprocess.CalledProcessError) as exc: + raise RuntimeError_(f"cannot generate a REALITY key pair with {xray}: {exc}") from None + private = public = None + for line in out.splitlines(): + label, _, value = line.partition(":") + label = re.sub(r"[^a-z]", "", label.lower()) + if label == "privatekey": + private = value.strip() + elif "publickey" in label or label == "password": + public = value.strip() + if not private or not public: + raise RuntimeError_(f"cannot read the key pair `{xray} x25519` printed") + return private, public + + +def complete_listener(entry: dict, xray: str) -> dict: + """Generate what a new listener leaves out: a REALITY key pair and short ID, and a + Shadowsocks 2022 server key.""" + entry = copy.deepcopy(entry) + reality = entry.get("reality") or {} + if reality.get("enable"): + if reality.get("privateKey") is None: + reality["privateKey"], reality["publicKey"] = _x25519(xray) + reality.setdefault("shortIds", [secrets.token_hex(4)]) + entry["reality"] = reality + method = entry.get("method") + if entry.get("type") == "shadowsocks" and method in SS2022_KEY_BYTES and method.startswith("2022-blake3-aes-"): + entry.setdefault("serverPassword", base64.b64encode(secrets.token_bytes(SS2022_KEY_BYTES[method])).decode("ascii")) + return entry + + +def listener_from_flags(kind: str, args: argparse.Namespace) -> dict: + """A listener entry from `add [flags]`.""" + entry: dict = {"type": kind} + for flag, key in (("port", "port"), ("listen", "address"), ("via", "via"), ("share_port", "sharePort"), + ("share_address", "shareAddress"), ("order", "order"), ("method", "method")): + if getattr(args, flag) is not None: + entry[key] = getattr(args, flag) + if args.flow: + entry["flow"] = "xtls-rprx-vision" if args.flow in ("vision", "xtls-rprx-vision") else args.flow + transport = {} + for flag, key in (("transport", "type"), ("path", "path"), ("host", "host"), ("mode", "mode"), ("service_name", "serviceName")): + if getattr(args, flag) is not None: + transport[key] = getattr(args, flag) + if transport: + entry["transport"] = transport + tls = {} + if args.tls: + tls.update({"enable": True, "certificate": args.tls}) + if args.alpn: + tls["alpn"] = [part for part in args.alpn.split(",") if part] + if args.sni: + tls["serverName"] = args.sni + if tls: + entry["tls"] = tls + if args.reality: + reality = {"enable": True, "serverNames": [part for part in args.reality.split(",") if part]} + # The site the names belong to, unless it is somewhere else. + if args.reality_dest: + reality["dest"] = args.reality_dest + elif reality["serverNames"]: + reality["dest"] = f"{reality['serverNames'][0]}:443" + if args.short_id is not None: + reality["shortIds"] = [args.short_id] + entry["reality"] = {k: v for k, v in reality.items() if v is not None} + hysteria: dict = {} + if args.masquerade: + hysteria["masquerade"] = args.masquerade + if args.salamander: + hysteria["salamander"] = {"enable": True} + if hysteria: + entry["hysteria"] = hysteria + if args.user: + entry["users"] = list(dict.fromkeys(args.user)) + return entry + + +def cmd_add(spec: dict, spool: str, tag: str, entry: dict, xray: str) -> str: + state, _ = load_spool(spool) + before = copy.deepcopy(state) + _require_name(tag, "listener tag") + if tag in RESERVED_TAGS or tag in {listener["tag"] for listener in spec["listeners"]}: + raise RuntimeError_(f"A listener named '{tag}' is declared in the configuration.") + if tag in state["listeners"]: + raise RuntimeError_(f"A runtime listener named '{tag}' already exists; remove it first.") + entry.pop("tag", None) + check_listener_shape(entry) + for name in entry.get("users", []): + if name not in state["users"] and name not in _declared_users(spec): + raise RuntimeError_(f"Unknown user: {name}") + entry = complete_listener(entry, xray) + state["listeners"][tag] = entry + _commit(spec, state, before, [("listener", tag)]) + write_entry(spool, "listeners", tag, entry) + users = entry.get("users", []) + note = f" for {', '.join(users)}" if users else "; bind users to it with: proxy-ctl inbounds bind " + tag + return f"Added listener {tag} ({entry['type']}, port {entry.get('port', 443)}){note}" + + +def cmd_rm(spec: dict, spool: str, tag: str) -> str: + state, _ = load_spool(spool) + if tag in {listener["tag"] for listener in spec["listeners"]}: + raise RuntimeError_(f"'{tag}' is declared in the configuration; remove it there.") + if tag not in state["listeners"]: + raise RuntimeError_(f"Unknown runtime listener: {tag}") + remove_entry(spool, "listeners", tag) + for name, entry in state["users"].items(): + if tag in entry.get("listeners", []): + entry["listeners"] = [t for t in entry["listeners"] if t != tag] + write_entry(spool, "users", name, entry) + return f"Removed listener {tag}" + + +def users_view(spec: dict, state: dict) -> list[dict]: + """Every user, declared and runtime: its order, serverSource address, listeners and + where it comes from, and what keeps a runtime one from working.""" + merged, result, _ = merge_state(spec, state) + on: dict[str, list[str]] = {} + for listener in merged["listeners"]: + for user in listener["users"]: + on.setdefault(user["name"], []).append(listener["tag"]) + declared_numbers = _declared_numbers(spec) + runtime_numbers = {s["email"]: s for s in result["selfSources"]} + source = spec.get("serverSource") or {} + + def address(number: int | None) -> str: + if number is None or source.get("ipv4") is None: + return "" + return str(ipaddress.ip_network(source["ipv4"], strict=False).network_address + number) + + rows = [] + for name, user in sorted(_declared_users(spec).items()): + number = declared_numbers.get(name) + rows.append({"name": name, "source": "nix", "order": user.get("order") if user.get("order") is not None else number, + "address": address(number), "listeners": on.get(name, []), "problems": []}) + for name, entry in sorted(state["users"].items()): + numbered = runtime_numbers.get(name) + rows.append( + { + "name": name, + "source": "runtime", + "order": entry.get("order"), + "address": address(numbered["number"]) if numbered else "", + "listeners": on.get(name, []), + "problems": result["problems"].get(("user", name), []), + } + ) + return rows + + +def listeners_view(spec: dict, state: dict) -> list[dict]: + """Every listener, declared and runtime: tag, type, port, via, users, source.""" + merged, result, _ = merge_state(spec, state) + started = {listener["tag"]: listener for listener in merged["listeners"]} + rows = [] + for listener in spec["listeners"]: + current = started.get(listener["tag"], listener) + rows.append({"tag": listener["tag"], "type": listener.get("type") or "json", "port": listener["port"], + "via": listener.get("via") or "", "users": [u["name"] for u in current["users"]], + "source": "nix", "problems": []}) + for tag, entry in sorted(state["listeners"].items()): + current = started.get(tag) + rows.append( + { + "tag": tag, + "type": entry.get("type", ""), + "port": entry.get("port", (spec["runtime"].get("listenerDefaults") or {}).get("port", 443)), + "via": entry.get("via") or spec["runtime"].get("defaultVia", ""), + "users": [u["name"] for u in current["users"]] if current else entry.get("users", []), + "source": "runtime", + "problems": result["problems"].get(("listener", tag), []), + } + ) + return rows + + +def _table(rows: list[dict], columns: list[tuple[str, str]]) -> str: + def cell(row: dict, key: str) -> str: + value = row.get(key) + if isinstance(value, list): + return ",".join(str(v) for v in value) or "-" + return "-" if value in (None, "") else str(value) + + widths = {key: max([len(heading)] + [len(cell(row, key)) for row in rows]) for key, heading in columns} + lines = [" " + " ".join(heading.ljust(widths[key]) for key, heading in columns).rstrip()] + for row in rows: + lines.append(" " + " ".join(cell(row, key).ljust(widths[key]) for key, _ in columns).rstrip()) + for problem in row.get("problems") or []: + lines.append(f" ! {problem}") + return "\n".join(lines) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="inbound-runtime", description=__doc__.split("\n", 1)[0]) + parser.add_argument("--spec", required=True, help="the generated inbound spec JSON") + parser.add_argument("--xray", default="xray", help="XRay, for REALITY key pairs") + commands = parser.add_subparsers(dest="command", required=True) + + users = commands.add_parser("users", help="inbound users, declared and runtime") + users.add_argument("--json", action="store_true") + user_verbs = users.add_subparsers(dest="verb") + add_user = user_verbs.add_parser("add") + add_user.add_argument("name") + add_user.add_argument("--order", type=int) + add_user.add_argument("--listener", action="append", default=[]) + rm_user = user_verbs.add_parser("rm") + rm_user.add_argument("name") + order_user = user_verbs.add_parser("order") + order_user.add_argument("name") + order_user.add_argument("order", type=int) + + for verb in ("bind", "unbind"): + bind = commands.add_parser(verb) + bind.add_argument("user") + bind.add_argument("tag") + + listeners = commands.add_parser("listeners", help="listeners, declared and runtime") + listeners.add_argument("--json", action="store_true") + + add = commands.add_parser("add", help="add a runtime listener") + add.add_argument("tag") + add.add_argument("source", help="a listener type, a JSON file, or - for JSON on stdin") + for flag, kind in (("--port", int), ("--listen", str), ("--via", str), ("--share-port", int), ("--share-address", str), + ("--order", int), ("--method", str), ("--flow", str), ("--transport", str), ("--path", str), + ("--host", str), ("--mode", str), ("--service-name", str), ("--tls", str), ("--alpn", str), + ("--sni", str), ("--reality", str), ("--reality-dest", str), ("--short-id", str), + ("--masquerade", str)): + add.add_argument(flag, type=kind) + add.add_argument("--salamander", action="store_true") + add.add_argument("--user", action="append", default=[]) + + for verb in ("rm", "show"): + commands.add_parser(verb).add_argument("tag") + check = commands.add_parser( + "check", help="merge the spool as the services would; warnings on stderr, units to restart on stdout" + ) + check.add_argument("--awg-users", help="users.json of the AmneziaWG listeners' unit, as it last started") + check.add_argument("--awg-unit", default="proxy-suite-inbounds-awg.service") + + args = parser.parse_args(argv) + try: + with open(args.spec, encoding="utf-8") as handle: + spec = json.load(handle) + except (OSError, ValueError) as exc: + print(f"cannot read the inbound spec {args.spec}: {exc}", file=sys.stderr) + return 1 + # Listing works without inbounds.runtime: the declared users and listeners, as they are. + listing = args.command in ("users", "listeners") and getattr(args, "verb", None) in (None, "list") + if not spec.get("runtime") and not listing: + print("inbounds.runtime is not enabled in this configuration.", file=sys.stderr) + return 1 + spool = (spec.get("runtime") or {}).get("spool", "") + changes = args.command in ("add", "rm", "bind", "unbind") or (args.command == "users" and args.verb in ("add", "rm", "order")) + kinds = [os.path.join(spool, kind) for kind in ("users", "listeners")] + writable = [spool, *(path for path in kinds if os.path.isdir(path))] + if changes and not all(os.access(path, os.W_OK | os.X_OK) for path in writable): + print(f"Cannot write {spool}", file=sys.stderr) + return 77 + try: + if args.command == "users" and args.verb in (None, "list"): + state, warnings = load_spool(spool) + for warning in warnings: + print(warning, file=sys.stderr) + rows = users_view(spec, state) + print(json.dumps(rows) if args.json else _table(rows, [("name", "USER"), ("order", "ORDER"), ("address", "ADDRESS"), + ("source", "SOURCE"), ("listeners", "LISTENERS")])) + elif args.command == "users" and args.verb == "add": + print(cmd_users_add(spec, spool, args.name, args.order, args.listener)) + elif args.command == "users" and args.verb == "rm": + print(cmd_users_rm(spec, spool, args.name)) + elif args.command == "users" and args.verb == "order": + print(cmd_users_order(spec, spool, args.name, args.order)) + elif args.command in ("bind", "unbind"): + print(cmd_bind(spec, spool, args.user, args.tag, args.command == "bind")) + elif args.command == "listeners": + state, warnings = load_spool(spool) + for warning in warnings: + print(warning, file=sys.stderr) + rows = listeners_view(spec, state) + print(json.dumps(rows) if args.json else _table(rows, [("tag", "TAG"), ("type", "TYPE"), ("port", "PORT"), ("via", "VIA"), + ("source", "SOURCE"), ("users", "USERS")])) + elif args.command == "add": + if args.source in TYPES: + entry = listener_from_flags(args.source, args) + else: + text = sys.stdin.read() if args.source == "-" else open(args.source, encoding="utf-8").read() + try: + entry = json.loads(text) + except ValueError as exc: + raise RuntimeError_(f"not a listener type, and not valid JSON: {exc}") from None + if not isinstance(entry, dict): + raise RuntimeError_("the JSON must be one listener object") + entry.setdefault("users", []).extend(u for u in args.user if u not in entry["users"]) + print(cmd_add(spec, spool, args.tag, entry, args.xray)) + elif args.command == "rm": + print(cmd_rm(spec, spool, args.tag)) + elif args.command == "show": + state, _ = load_spool(spool) + if args.tag not in state["listeners"]: + raise RuntimeError_(f"Unknown runtime listener: {args.tag}") + print(json.dumps(state["listeners"][args.tag], indent=2, sort_keys=True)) + elif args.command == "check": + merged, _, warnings = merge(spec) + for warning in warnings: + print(warning, file=sys.stderr) + if args.awg_users: + awg = { + listener["tag"]: sorted(user["name"] for user in listener["users"]) + for listener in merged["listeners"] + if listener.get("type") == "amneziawg" + } + try: + with open(args.awg_users, encoding="utf-8") as handle: + running = json.load(handle) + except (OSError, ValueError): + running = None + if awg and awg != running: + print(args.awg_unit) + except RuntimeError_ as exc: + print(exc, file=sys.stderr) + return 1 + except PermissionError as exc: + print(f"Cannot write {exc.filename}: permission denied.", file=sys.stderr) + return 77 + except OSError as exc: + print(f"{exc.filename or ''}: {exc.strerror}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test-inbound-runtime.py b/scripts/test-inbound-runtime.py new file mode 100644 index 0000000..97308e9 --- /dev/null +++ b/scripts/test-inbound-runtime.py @@ -0,0 +1,405 @@ +#!/usr/bin/env python3 + +import base64 +import contextlib +import copy +import io +import json +import os +import stat +import tempfile +import unittest + +import inbound_runtime as rt + +# What config.nix renders as runtime.listenerDefaults: the option with nothing set. +LISTENER_DEFAULTS = { + "acceptProxyProtocol": False, + "address": "::", + "fallbacks": [], + "flow": None, + "hysteria": {"masquerade": None, "portHopping": None, "salamander": {"enable": False, "password": None, "passwordFile": None}}, + "method": "2022-blake3-aes-128-gcm", + "order": 1000, + "port": 443, + "reality": { + "dest": "www.microsoft.com:443", + "enable": False, + "privateKey": None, + "privateKeyFile": None, + "publicKey": None, + "serverNames": [], + "shortIds": [""], + "xver": 0, + }, + "serverPassword": None, + "serverPasswordFile": None, + "shareAddress": None, + "sharePort": None, + "tls": {"alpn": None, "certificateFile": None, "enable": False, "keyFile": None, "serverName": None}, + "transport": {"host": None, "mode": None, "path": "/", "serviceName": "", "trustedXForwardedFor": [], "type": "raw"}, + "type": None, + "via": None, +} + + +def declared_user(name, **fields): + user = { + "name": name, + "order": None, + "uuid": None, + "uuidFile": None, + "password": None, + "passwordFile": None, + "publicKey": None, + "privateKeyFile": None, + "presharedKeyFile": None, + "address": None, + } + user.update(fields) + return user + + +def declared_listener(tag, users, **fields): + listener = copy.deepcopy(LISTENER_DEFAULTS) + listener.pop("address") + listener.update({"tag": tag, "type": "vless", "listen": "::", "via": "proxy", "users": users, "front": None, + "xrayJson": None, "jsonFile": None, "salamanderStateFile": f"/tmp/{tag}"}) + listener.update(fields) + return listener + + +BOB = declared_user("bob", order=1, uuid="11111111-1111-4111-8111-111111111111") +ANON = declared_user("anon", uuid="22222222-2222-4222-8222-222222222222") +SS = declared_user("ss", password="c2VydmVyLWtleS0xNmJ5dGU=") + + +def make_spec(spool, **runtime): + spec = { + "serverAddress": "vpn.example.com", + "shareLinks": True, + "users": {u["name"]: {k: v for k, v in u.items() if k != "name"} for u in (BOB, ANON, SS)}, + "serverSource": {"ipv4": "10.78.0.0/24", "ipv6": "fd78::/64", + "declared": [{"name": "bob", "number": 1}, {"name": "anon", "number": 2}, {"name": "ss", "number": 3}]}, + "listeners": [ + declared_listener("vless-in", [BOB, ANON], order=1000), + declared_listener("ss-in", [SS], type="shadowsocks", port=8388, method="aes-128-gcm"), + declared_listener("awg", [], type="amneziawg", port=51820), + ], + "runtime": { + "spool": spool, + "ports": [8443, "20000-20010"], + "vias": ["proxy", "direct", "block"], + "defaultVia": "proxy", + "fallbackDests": ["127.0.0.1:8080"], + "tlsCertificates": {"main": {"certificateFile": "/run/cert", "keyFile": "/run/key", "serverName": None}}, + "selfFinalRules": [{"action": "block", "ip": ["geoip:private"]}], + "salamanderStateDir": "/tmp/salamander", + "listenerDefaults": LISTENER_DEFAULTS, + }, + } + spec["runtime"].update(runtime) + return spec + + +class RuntimeTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.spool = os.path.join(self.tmp.name, "spool") + os.makedirs(self.spool) + self.spec = make_spec(self.spool) + # `xray x25519` as XRay 26 prints it. + self.xray = os.path.join(self.tmp.name, "xray") + with open(self.xray, "w", encoding="utf-8") as f: + f.write("#!/bin/sh\necho 'PrivateKey: private-x'\necho 'Password (PublicKey): public-x'\necho 'Hash32: h'\n") + os.chmod(self.xray, 0o755) + + def tearDown(self): + self.tmp.cleanup() + + def state(self): + return rt.load_spool(self.spool)[0] + + def write(self, kind, name, entry): + rt.write_entry(self.spool, kind, name, entry) + + def add_listener(self, tag, **entry): + return rt.cmd_add(self.spec, self.spool, tag, entry, self.xray) + + # --- users ------------------------------------------------------------------- + + def test_user_orders_go_around_declared_numbers(self): + rt.cmd_users_add(self.spec, self.spool, "alice", None, ["vless-in"]) + rt.cmd_users_add(self.spec, self.spool, "carol", 9, []) + users = self.state()["users"] + self.assertEqual(users["alice"]["order"], 4) # bob 1, anon 2, ss 3 + self.assertEqual(users["carol"]["order"], 9) + self.assertRegex(users["alice"]["uuid"], r"^[0-9a-f-]{36}$") + self.assertTrue(users["alice"]["password"]) + with self.assertRaisesRegex(rt.RuntimeError_, "declared user 'anon'"): + rt.cmd_users_add(self.spec, self.spool, "dave", 2, []) + with self.assertRaisesRegex(rt.RuntimeError_, "runtime user 'carol'"): + rt.cmd_users_order(self.spec, self.spool, "alice", 9) + with self.assertRaisesRegex(rt.RuntimeError_, "declared user"): + rt.cmd_users_add(self.spec, self.spool, "bob", None, []) + with self.assertRaisesRegex(rt.RuntimeError_, "Unknown listener"): + rt.cmd_users_add(self.spec, self.spool, "erin", None, ["nope"]) + with self.assertRaisesRegex(rt.RuntimeError_, "Invalid user name"): + rt.cmd_users_add(self.spec, self.spool, "a b", None, []) + rt.cmd_users_order(self.spec, self.spool, "alice", 12) + self.assertEqual(self.state()["users"]["alice"]["order"], 12) + + def test_runtime_users_join_declared_listeners(self): + rt.cmd_users_add(self.spec, self.spool, "alice", None, ["vless-in", "awg"]) + merged, result, warnings = rt.merge(self.spec) + by_tag = {l["tag"]: l for l in merged["listeners"]} + self.assertEqual([u["name"] for u in by_tag["vless-in"]["users"]], ["bob", "anon", "alice"]) + # An AmneziaWG listener takes it as a peer, its keys and address left to awg_inbound.py. + self.assertEqual([u["name"] for u in by_tag["awg"]["users"]], ["alice"]) + self.assertIsNone(by_tag["awg"]["users"][0]["address"]) + self.assertEqual(result["users"], ["alice"]) + self.assertEqual(result["selfSources"][0]["ipv4"], "10.78.0.4") + self.assertEqual(result["selfSources"][0]["ipv6"], "fd78::4") + self.assertEqual(warnings, []) + + def test_a_second_user_on_a_plain_shadowsocks_listener_is_refused(self): + with self.assertRaisesRegex(rt.RuntimeError_, "2022-blake3-aes method"): + rt.cmd_users_add(self.spec, self.spool, "alice", None, ["ss-in"]) + self.assertEqual(self.state()["users"], {}) + + def test_shadowsocks_2022_keys_fit_the_method(self): + rt.cmd_users_add(self.spec, self.spool, "alice", None, []) + self.add_listener("ss2", type="shadowsocks", port=20003, method="2022-blake3-aes-128-gcm", users=["alice"]) + entry = self.state()["listeners"]["ss2"] + self.assertEqual(len(base64.b64decode(entry["serverPassword"])), 16) + merged, _, _ = rt.merge(self.spec) + alice = next(l for l in merged["listeners"] if l["tag"] == "ss2")["users"][0] + self.assertEqual(len(base64.b64decode(alice["password"])), 16) + self.assertNotEqual(alice["password"], self.state()["users"]["alice"]["password"]) + + def test_a_taken_order_moves_the_runtime_user_with_a_warning(self): + # Written by hand, or the configuration gave the number to a declared user since. + self.write("users", "zed", {"order": 1, "uuid": "33333333-3333-4333-8333-333333333333", "password": "p", "listeners": ["vless-in"]}) + _, result, warnings = rt.merge(self.spec) + self.assertEqual(result["selfSources"][0]["number"], 4) + self.assertTrue(any("order 1 is taken; using 4" in w for w in warnings)) + + def test_bind_writes_the_runtime_side(self): + rt.cmd_users_add(self.spec, self.spool, "alice", None, []) + self.add_listener("friends", type="vless", port=20001) + rt.cmd_bind(self.spec, self.spool, "alice", "vless-in", True) + rt.cmd_bind(self.spec, self.spool, "bob", "friends", True) + state = self.state() + self.assertEqual(state["users"]["alice"]["listeners"], ["vless-in"]) + self.assertEqual(state["listeners"]["friends"]["users"], ["bob"]) + with self.assertRaisesRegex(rt.RuntimeError_, "Both bob and vless-in are declared"): + rt.cmd_bind(self.spec, self.spool, "bob", "vless-in", True) + rt.cmd_bind(self.spec, self.spool, "bob", "friends", False) + self.assertEqual(self.state()["listeners"]["friends"]["users"], []) + with self.assertRaisesRegex(rt.RuntimeError_, "not bound"): + rt.cmd_bind(self.spec, self.spool, "bob", "friends", False) + # A declared user without the secret the protocol needs. + self.add_listener("tro", type="trojan", port=20002, tls={"enable": True, "certificate": "main"}) + with self.assertRaisesRegex(rt.RuntimeError_, "no password"): + rt.cmd_bind(self.spec, self.spool, "bob", "tro", True) + + def test_removing_takes_the_bindings_along(self): + rt.cmd_users_add(self.spec, self.spool, "alice", None, []) + self.add_listener("friends", type="vless", port=20001, users=["alice", "bob"]) + rt.cmd_bind(self.spec, self.spool, "alice", "friends", True) + rt.cmd_users_rm(self.spec, self.spool, "alice") + self.assertEqual(self.state()["listeners"]["friends"]["users"], ["bob"]) + rt.cmd_users_add(self.spec, self.spool, "carol", None, ["friends", "vless-in"]) + rt.cmd_rm(self.spec, self.spool, "friends") + self.assertEqual(self.state()["users"]["carol"]["listeners"], ["vless-in"]) + with self.assertRaisesRegex(rt.RuntimeError_, "declared in the configuration"): + rt.cmd_rm(self.spec, self.spool, "vless-in") + with self.assertRaisesRegex(rt.RuntimeError_, "declared in the configuration"): + rt.cmd_users_rm(self.spec, self.spool, "bob") + + # --- listeners --------------------------------------------------------------- + + def test_reality_listener_gets_generated_keys(self): + args = rt.main.__globals__["argparse"].Namespace( + port=20001, listen=None, via=None, share_port=None, share_address=None, order=None, method=None, + flow="vision", transport=None, path=None, host=None, mode=None, service_name=None, tls=None, alpn=None, + sni=None, reality="www.example.com,example.com", reality_dest=None, short_id=None, masquerade=None, + salamander=False, user=["bob"], + ) + entry = rt.listener_from_flags("vless", args) + self.assertEqual(entry["reality"]["dest"], "www.example.com:443") + self.assertEqual(entry["flow"], "xtls-rprx-vision") + rt.cmd_add(self.spec, self.spool, "friends", entry, self.xray) + saved = self.state()["listeners"]["friends"] + self.assertEqual((saved["reality"]["privateKey"], saved["reality"]["publicKey"]), ("private-x", "public-x")) + self.assertRegex(saved["reality"]["shortIds"][0], r"^[0-9a-f]{8}$") + merged, result, _ = rt.merge(self.spec) + friends = next(l for l in merged["listeners"] if l["tag"] == "friends") + self.assertEqual(friends["listen"], "::") + self.assertEqual(friends["via"], "proxy") + self.assertTrue(friends["runtime"]) + self.assertEqual(result["listeners"], ["friends"]) + + def test_fences(self): + cases = [ + ({"type": "vless", "port": 30000}, "not in inbounds.runtime.ports"), + ({"type": "vless", "port": 443}, "not in inbounds.runtime.ports"), + ({"type": "vless", "port": 20001, "via": "elsewhere"}, "via 'elsewhere'"), + ({"type": "trojan", "port": 20001}, "TLS needs tls.certificate"), + ({"type": "trojan", "port": 20001, "tls": {"enable": True, "certificate": "other"}}, "'other' is not in"), + ({"type": "vless", "port": 20001, "tls": {"certificateFile": "/etc/shadow"}}, "not something a runtime entry can set"), + ({"type": "vless", "port": 20001, "xrayJson": {}}, "not something a runtime entry can set"), + ({"type": "amneziawg", "port": 20001}, "type: invalid value"), + ({"type": "hysteria2", "port": 20001, "hysteria": {"portHopping": "1-2"}}, "not something"), + ({"type": "vless", "port": 20001, "fallbacks": [{"dest": 22}]}, "not in inbounds.runtime.fallbackDests"), + ({"type": "vless", "port": 20001, "fallbacks": [{"listener": "vless-in"}]}, "must be another runtime listener"), + ({"type": "vless", "port": 20001, "flow": "xtls-rprx-vision", "transport": {"type": "ws"}}, "flow is only valid"), + ({"type": "vmess", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"]}}, "reality only for vless"), + ] + for entry, message in cases: + with self.subTest(entry=entry), self.assertRaisesRegex(rt.RuntimeError_, message): + self.add_listener("x", **entry) + self.assertEqual(self.state()["listeners"], {}) + with self.assertRaisesRegex(rt.RuntimeError_, "declared in the configuration"): + self.add_listener("vless-in", type="vless", port=20001) + self.add_listener("a", type="vless", port=20001) + with self.assertRaisesRegex(rt.RuntimeError_, "taken by another listener"): + self.add_listener("b", type="vless", port=20001) + + def test_fallback_to_a_runtime_listener(self): + self.add_listener("ws", type="vless", port=20002, address="127.0.0.1", transport={"type": "ws", "path": "/ws"}, users=["bob"]) + self.add_listener("front", type="vless", port=8443, tls={"enable": True, "certificate": "main"}, + fallbacks=[{"path": "/ws", "listener": "ws"}, {"dest": "127.0.0.1:8080"}], users=["bob"]) + merged, _, warnings = rt.merge(self.spec) + self.assertEqual(warnings, []) + by_tag = {l["tag"]: l for l in merged["listeners"]} + self.assertEqual(by_tag["front"]["fallbacks"][0], {"name": None, "alpn": None, "path": "/ws", "dest": "127.0.0.1:20002", "xver": 2}) + self.assertEqual(by_tag["ws"]["front"]["port"], 8443) + self.assertEqual(by_tag["front"]["tls"]["certificateFile"], "/run/cert") + with self.assertRaisesRegex(rt.RuntimeError_, "already the fallback listener"): + self.add_listener("front2", type="vless", port=20003, fallbacks=[{"path": "/ws", "listener": "ws"}], users=["bob"]) + + def test_listener_without_users_waits(self): + self.add_listener("empty", type="vless", port=20001) + merged, result, warnings = rt.merge(self.spec) + self.assertNotIn("empty", [l["tag"] for l in merged["listeners"]]) + self.assertTrue(any("'empty' has no users yet" in w for w in warnings)) + # AmneziaWG listeners run with no peers. + self.assertIn("awg", [l["tag"] for l in merged["listeners"]]) + + # --- the spool --------------------------------------------------------------- + + def test_bad_spool_entries_are_left_out(self): + os.makedirs(os.path.join(self.spool, "users")) + target = os.path.join(self.tmp.name, "secret.json") + with open(target, "w", encoding="utf-8") as f: + f.write(json.dumps({"order": 5, "uuid": "44444444-4444-4444-8444-444444444444", "password": "p", "listeners": []})) + os.symlink(target, os.path.join(self.spool, "users", "link.json")) + with open(os.path.join(self.spool, "users", "broken.json"), "w", encoding="utf-8") as f: + f.write("{") + os.mkfifo(os.path.join(self.spool, "users", "fifo.json")) + self.write("users", "noorder", {"uuid": "44444444-4444-4444-8444-444444444444", "password": "p"}) + state, warnings = rt.load_spool(self.spool) + self.assertEqual(sorted(state["users"]), ["noorder"]) + self.assertEqual(len(warnings), 3) + _, result, more = rt.merge_state(self.spec, state) + self.assertIn(("user", "noorder"), result["problems"]) + + def test_entries_are_group_readable_only(self): + self.write("users", "alice", {"order": 5}) + mode = stat.S_IMODE(os.stat(os.path.join(self.spool, "users", "alice.json")).st_mode) + self.assertEqual(mode & 0o027, 0) + + # --- routing ----------------------------------------------------------------- + + def test_expand_rules(self): + exception = {"notVia": ["block"]} + rules = [ + {"ruleTag": "inbound-block-private", "ip": ["geoip:private"], "outboundTag": "block"}, + {"ruleTag": "inbound-server-address-self-ip4-1", "user": ["bob"], "inboundTag": ["vless-in"], "_members": exception}, + {"_anchor": "selfIp", "inboundTag": ["vless-in"], "port": "443,20000-20010", "ip4": ["203.0.113.10"], "ip6": [], "_members": exception}, + {"ruleTag": "inbound-server-address-sniffed-direct", "inboundTag": [], "_members": {"via": ["direct"]}}, + {"ruleTag": "inbound-server-address-sniffed-proxy", "inboundTag": ["vless-in"], "_members": {"via": ["proxy"]}}, + {"_anchor": "selfName", "inboundTag": ["vless-in"], "port": "443", "domain": ["full:vpn.example.com"], "_members": exception}, + {"ruleTag": "inbound-final", "outboundTag": "proxy"}, + ] + listeners = [{"tag": "friends", "via": "proxy"}, {"tag": "out", "via": "direct"}, {"tag": "shut", "via": "block"}] + sources = [{"email": "alice", "number": 4, "id": "4", "ipv4": "10.78.0.4", "ipv6": None}] + expanded = rt.expand_rules(rules, listeners, sources, "proxy") + tags = [r.get("ruleTag") for r in expanded] + self.assertEqual(tags, [ + "inbound-block-private", + "inbound-server-address-self-ip4-1", + "inbound-server-address-self-ip4-4", + "inbound-server-address-sniffed-direct", + "inbound-server-address-sniffed-proxy", + "inbound-server-address-self-4", + "inbound-via-out", + "inbound-via-shut", + "inbound-final", + ]) + by_tag = {r.get("ruleTag"): r for r in expanded} + self.assertEqual(by_tag["inbound-server-address-self-ip4-4"]["inboundTag"], ["vless-in", "friends", "out"]) + self.assertEqual(by_tag["inbound-server-address-self-ip4-4"]["outboundTag"], "direct-self4-4") + self.assertEqual(by_tag["inbound-server-address-self-ip4-4"]["user"], ["alice"]) + self.assertEqual(by_tag["inbound-server-address-sniffed-direct"]["inboundTag"], ["out"]) + self.assertEqual(by_tag["inbound-server-address-self-4"]["domain"], ["full:vpn.example.com"]) + self.assertFalse(any("_members" in r or "_anchor" in r for r in expanded)) + # Nobody on direct: its guard goes. + again = rt.expand_rules(rules, listeners[:1], [], "proxy") + self.assertNotIn("inbound-server-address-sniffed-direct", [r.get("ruleTag") for r in again]) + + def test_self_outbounds(self): + outbounds = rt.self_outbounds([{"email": "a", "number": 4, "id": "4", "ipv4": "10.78.0.4", "ipv6": "fd78::4"}], [{"action": "block"}]) + self.assertEqual([o["tag"] for o in outbounds], ["direct-self4-4", "direct-self6-4"]) + self.assertEqual(outbounds[1]["settings"]["domainStrategy"], "UseIPv6") + + # --- the command line -------------------------------------------------------- + + def run_main(self, *argv, stdin=None): + spec_path = os.path.join(self.tmp.name, "spec.json") + with open(spec_path, "w", encoding="utf-8") as f: + json.dump(self.spec, f) + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + status = rt.main(["--spec", spec_path, "--xray", self.xray, *argv]) + return status, out.getvalue(), err.getvalue() + + def test_main(self): + status, out, _ = self.run_main("users", "add", "alice", "--listener", "vless-in") + self.assertEqual((status, out), (0, "Added user alice (order 4) on vless-in\n")) + status, out, _ = self.run_main("add", "hy", "hysteria2", "--port", "20005", "--tls", "main", "--salamander", "--user", "alice") + self.assertEqual(status, 0, out) + status, out, _ = self.run_main("users", "--json") + rows = {r["name"]: r for r in json.loads(out)} + self.assertEqual(rows["alice"]["listeners"], ["hy", "vless-in"]) # in listing order + self.assertEqual(rows["alice"]["address"], "10.78.0.4") + self.assertEqual(rows["anon"]["order"], 2) + status, _, err = self.run_main("users", "add", "alice") + self.assertEqual(status, 1) + self.assertIn("already exists", err) + status, out, _ = self.run_main("show", "hy") + self.assertTrue(json.loads(out)["hysteria"]["salamander"]["enable"]) + + def test_check_names_the_awg_unit_when_its_peers_change(self): + users = os.path.join(self.tmp.name, "users.json") + with open(users, "w", encoding="utf-8") as f: + json.dump({"awg": []}, f) + self.assertEqual(self.run_main("check", "--awg-users", users)[1], "") + rt.cmd_users_add(self.spec, self.spool, "alice", None, ["awg"]) + self.assertEqual(self.run_main("check", "--awg-users", users)[1], "proxy-suite-inbounds-awg.service\n") + + def test_no_write_access(self): + os.chmod(self.spool, 0o500) + try: + if os.access(self.spool, os.W_OK): + self.skipTest("running as root") + status, _, err = self.run_main("users", "add", "alice") + self.assertEqual(status, 77) + self.assertIn("Cannot write", err) + finally: + os.chmod(self.spool, 0o700) + + +if __name__ == "__main__": + unittest.main()