diff --git a/deploy/server-module.nix b/deploy/server-module.nix index 90a0625..ad7cb1f 100644 --- a/deploy/server-module.nix +++ b/deploy/server-module.nix @@ -43,12 +43,7 @@ let }; }; - user = [ - { - name = cfg.user; - uuidFile = "${cfg.secretsDir}/uuid"; - } - ]; + user = [ cfg.user ]; tls = { enable = true; certificateFile = "${certDir}/fullchain.pem"; @@ -355,6 +350,7 @@ in }; inbounds = { enable = true; + users.${cfg.user}.uuidFile = "${cfg.secretsDir}/uuid"; serverAddress = certName; routing.via = "direct"; listeners = { diff --git a/docs/options/inbounds.md b/docs/options/inbounds.md index 2f6ce97..c2cfd47 100644 --- a/docs/options/inbounds.md +++ b/docs/options/inbounds.md @@ -98,16 +98,6 @@ Part of the [proxy-suite options reference](./index.md). - [type](#services-proxy-suite-inbounds-listeners-name-transport-type) - [type](#services-proxy-suite-inbounds-listeners-name-type) - [users](#services-proxy-suite-inbounds-listeners-name-users) - - item - - [address](#services-proxy-suite-inbounds-listeners-name-users-address) - - [name](#services-proxy-suite-inbounds-listeners-name-users-name) - - [password](#services-proxy-suite-inbounds-listeners-name-users-password) - - [passwordFile](#services-proxy-suite-inbounds-listeners-name-users-passwordfile) - - [presharedKeyFile](#services-proxy-suite-inbounds-listeners-name-users-presharedkeyfile) - - [privateKeyFile](#services-proxy-suite-inbounds-listeners-name-users-privatekeyfile) - - [publicKey](#services-proxy-suite-inbounds-listeners-name-users-publickey) - - [uuid](#services-proxy-suite-inbounds-listeners-name-users-uuid) - - [uuidFile](#services-proxy-suite-inbounds-listeners-name-users-uuidfile) - [via](#services-proxy-suite-inbounds-listeners-name-via) - [xrayJson](#services-proxy-suite-inbounds-listeners-name-xrayjson) - [openFirewall](#services-proxy-suite-inbounds-openfirewall) @@ -119,6 +109,10 @@ Part of the [proxy-suite options reference](./index.md). - [geoips](#services-proxy-suite-inbounds-routing-proxy-geoips) - [geosites](#services-proxy-suite-inbounds-routing-proxy-geosites) - [ips](#services-proxy-suite-inbounds-routing-proxy-ips) + - serverSource + - [interface](#services-proxy-suite-inbounds-routing-serversource-interface) + - [ipv4](#services-proxy-suite-inbounds-routing-serversource-ipv4) + - [ipv6](#services-proxy-suite-inbounds-routing-serversource-ipv6) - [via](#services-proxy-suite-inbounds-routing-via) - [zapretDirect](#services-proxy-suite-inbounds-routing-zapretdirect) - [serverAddress](#services-proxy-suite-inbounds-serveraddress) @@ -129,6 +123,17 @@ Part of the [proxy-suite options reference](./index.md). - [enable](#services-proxy-suite-inbounds-subscriptions-enable) - [baseUrl](#services-proxy-suite-inbounds-subscriptions-baseurl) - [group](#services-proxy-suite-inbounds-subscriptions-group) + - [users](#services-proxy-suite-inbounds-users) + - `` + - [address](#services-proxy-suite-inbounds-users-name-address) + - [order](#services-proxy-suite-inbounds-users-name-order) + - [password](#services-proxy-suite-inbounds-users-name-password) + - [passwordFile](#services-proxy-suite-inbounds-users-name-passwordfile) + - [presharedKeyFile](#services-proxy-suite-inbounds-users-name-presharedkeyfile) + - [privateKeyFile](#services-proxy-suite-inbounds-users-name-privatekeyfile) + - [publicKey](#services-proxy-suite-inbounds-users-name-publickey) + - [uuid](#services-proxy-suite-inbounds-users-name-uuid) + - [uuidFile](#services-proxy-suite-inbounds-users-name-uuidfile) ## services\.proxy-suite\.inbounds\.enable @@ -161,7 +166,7 @@ Server listeners, by tag\. vless-reality = { type = "vless"; port = 443; - users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]; + users = [ "phone" ]; flow = "xtls-rprx-vision"; reality = { enable = true; @@ -175,7 +180,7 @@ Server listeners, by tag\. home = { type = "amneziawg"; port = 51820; - users = [ { name = "phone"; } { name = "laptop"; } ]; + users = [ "phone" "laptop" ]; amneziaWg.mode = "lan"; }; } @@ -941,94 +946,11 @@ Protocol\. Set exactly one of ` type `, ` xrayJson ` or ` jsonFile `\. ## services\.proxy-suite\.inbounds\.listeners\.\\.users -Accepted users\. +Accepted users, by their names in ` inbounds.users `\. -**Type:** list of (submodule)\ +**Type:** list of string matching the pattern \[^\[:space:]]+\ **Default:** `[ ]`\ -**Example:** `[ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]` - - -## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.address - -AmneziaWG tunnel IPv4 address, inside ` amneziaWg.subnet `\. ` null `: the lowest free one, -kept for as long as the user exists\. - -**Type:** null or string\ -**Default:** `null`\ -**Example:** `"10.66.0.10"` - - -## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.name - -User name, shown in share links, subscriptions and stats\. - -**Type:** string\ -**Default:** `""`\ -**Example:** `"phone"` - - -## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.password - -Password (trojan, shadowsocks, socks, http)\. Ends up in the Nix store; prefer ` passwordFile `\. - -**Type:** null or string\ -**Default:** `null`\ -**Example:** `"hunter2"` - - -## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.passwordFile - -File with the password\. - -**Type:** null or string\ -**Default:** `null`\ -**Example:** `"/run/secrets/proxy-inbound-password"` - - -## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.presharedKeyFile - -File with the AmneziaWG preshared key, instead of a generated one\. - -**Type:** null or string\ -**Default:** `null`\ -**Example:** `"/run/secrets/awg-phone-psk"` - - -## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.privateKeyFile - -File with the AmneziaWG client private key, instead of a generated one\. - -**Type:** null or string\ -**Default:** `null`\ -**Example:** `"/run/secrets/awg-phone-key"` - - -## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.publicKey - -AmneziaWG public key, for a client that keeps its own private key (no config or link is -generated for it)\. ` null `: generate a key pair\. - -**Type:** null or string\ -**Default:** `null`\ -**Example:** `"jNXH..."` - - -## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.uuid - -UUID (vless, vmess)\. Ends up in the Nix store; prefer ` uuidFile `\. - -**Type:** null or string\ -**Default:** `null`\ -**Example:** `"b831381d-6324-4d53-ad4f-8cda48b30811"` - - -## services\.proxy-suite\.inbounds\.listeners\.\\.users\.\*\.uuidFile - -File with the UUID\. - -**Type:** null or string\ -**Default:** `null`\ -**Example:** `"/run/secrets/proxy-inbound-uuid"` +**Example:** `[ "phone" "laptop" ]` ## services\.proxy-suite\.inbounds\.listeners\.\\.via @@ -1108,6 +1030,40 @@ IP ranges (CIDR) that clients always reach through the local proxy, whatever the **Default:** `[ ]`\ **Example:** `[ "1.1.1.0/24" ]` + +## services\.proxy-suite\.inbounds\.routing\.serverSource\.interface + +Dummy interface the ` serverSource ` addresses are put on\. + +**Type:** string matching the pattern \[a-zA-Z0-9_-]{1,15}\ +**Default:** `"ps-self"` + + +## services\.proxy-suite\.inbounds\.routing\.serverSource\.ipv4 + +Range each inbound user gets an address from, for the connections they make to this +host itself (` serverAddress `, ` serverAliases `, ` serverPorts `)\. Otherwise those come +from this host’s own address, and its services (mail, the web server, their rate +limits and bans) see every user as one\. They see neither the users’ real addresses\. +The addresses sit on a dummy interface and reach nothing but this host\. Pick a range +nothing here routes or trusts\. Users are numbered by their ` order `, then name, from +the range’s second address: set ` order ` to keep each user’s address as users come +and go\. + +**Type:** null or string matching the pattern (\[0-9]{1,3}\\\.){3}\[0-9]{1,3}/\[0-9]{1,2}\ +**Default:** `null`\ +**Example:** `"10.78.0.0/24"` + + +## services\.proxy-suite\.inbounds\.routing\.serverSource\.ipv6 + +The same for IPv6: a prefix written with “::”, such as a ULA /64\. Needed as well when +` serverAliases ` lists an IPv6 address, which is otherwise dialed from this host’s own\. + +**Type:** null or string matching the pattern \[0-9a-fA-F:]\*::/\[0-9]{1,3}\ +**Default:** `null`\ +**Example:** `"fd78:78:78::/64"` + ## services\.proxy-suite\.inbounds\.routing\.via @@ -1125,7 +1081,7 @@ Where client traffic exits by default\. Each listener can override it\. ## services\.proxy-suite\.inbounds\.routing\.zapretDirect -Send zapret hostlist sites direct, so this host’s zapret unblocks them\. Only for the default ` via `\. +Send zapret hostlist sites direct, so this host’s zapret unblocks them\. Only for the default ` via `\. With a direct listener or the XRay backend, only by IP: XRay matches names by what a client puts in its handshake, whatever address it connects to\. **Type:** boolean\ **Default:** `true` @@ -1209,3 +1165,111 @@ Group of the web server that serves the subscription files\. **Type:** string\ **Default:** `"nginx"`\ **Example:** `"caddy"` + + +## services\.proxy-suite\.inbounds\.users + +Inbound users, by name, which listeners accept by naming them in their ` users `\. Each +listener takes the secret its protocol wants: ` uuid `/` uuidFile ` for vless and vmess, +` password `/` passwordFile ` for the others, the keys for AmneziaWG\. + +**Type:** attribute set of (submodule)\ +**Default:** `{ }`\ +**Example:** + +```nix +{ + phone = { + order = 1; + uuidFile = "/run/secrets/proxy-inbound-uuid"; + }; + laptop.order = 2; +} + +``` + + +## services\.proxy-suite\.inbounds\.users\.\\.address + +AmneziaWG tunnel IPv4 address, inside ` amneziaWg.subnet `\. ` null `: the lowest free one, +kept for as long as the user exists\. + +**Type:** null or string\ +**Default:** `null`\ +**Example:** `"10.66.0.10"` + + +## services\.proxy-suite\.inbounds\.users\.\\.order + +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\. + +**Type:** null or (positive integer, meaning >0)\ +**Default:** `null`\ +**Example:** `1` + + +## services\.proxy-suite\.inbounds\.users\.\\.password + +Password (trojan, shadowsocks, socks, http)\. Ends up in the Nix store; prefer ` passwordFile `\. + +**Type:** null or string\ +**Default:** `null`\ +**Example:** `"hunter2"` + + +## services\.proxy-suite\.inbounds\.users\.\\.passwordFile + +File with the password\. + +**Type:** null or string\ +**Default:** `null`\ +**Example:** `"/run/secrets/proxy-inbound-password"` + + +## services\.proxy-suite\.inbounds\.users\.\\.presharedKeyFile + +File with the AmneziaWG preshared key, instead of a generated one\. + +**Type:** null or string\ +**Default:** `null`\ +**Example:** `"/run/secrets/awg-phone-psk"` + + +## services\.proxy-suite\.inbounds\.users\.\\.privateKeyFile + +File with the AmneziaWG client private key, instead of a generated one\. + +**Type:** null or string\ +**Default:** `null`\ +**Example:** `"/run/secrets/awg-phone-key"` + + +## services\.proxy-suite\.inbounds\.users\.\\.publicKey + +AmneziaWG public key, for a client that keeps its own private key (no config or link is +generated for it)\. ` null `: generate a key pair\. + +**Type:** null or string\ +**Default:** `null`\ +**Example:** `"jNXH..."` + + +## services\.proxy-suite\.inbounds\.users\.\\.uuid + +UUID (vless, vmess)\. Ends up in the Nix store; prefer ` uuidFile `\. + +**Type:** null or string\ +**Default:** `null`\ +**Example:** `"b831381d-6324-4d53-ad4f-8cda48b30811"` + + +## services\.proxy-suite\.inbounds\.users\.\\.uuidFile + +File with the UUID\. + +**Type:** null or string\ +**Default:** `null`\ +**Example:** `"/run/secrets/proxy-inbound-uuid"` diff --git a/docs/options/index.md b/docs/options/index.md index 00bbf30..442fa30 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -81,6 +81,11 @@ services.proxy-suite = { geosites = [ ]; ips = [ ]; }; + serverSource = { + interface = "ps-self"; + ipv4 = null; + ipv6 = null; + }; via = "proxy"; zapretDirect = true; }; @@ -93,6 +98,7 @@ services.proxy-suite = { enable = false; group = "nginx"; }; + users = { }; }; killSwitch = { enable = false; diff --git a/docs/options/whitelistBypass.md b/docs/options/whitelistBypass.md index 865d56e..25af33a 100644 --- a/docs/options/whitelistBypass.md +++ b/docs/options/whitelistBypass.md @@ -34,7 +34,7 @@ host serves one joiner on a censored one\. ## services\.proxy-suite\.whitelistBypass\.package -whitelist-bypass package\. +whitelist-bypass package\. It must take the call link and the proxy password from WB_LINK and WB_UPSTREAM_PASS, as ` pkgs/whitelist-bypass.nix ` patches it to\. **Type:** package\ **Default:** proxy-suite’s ` whitelist-bypass ` (` pkgs/whitelist-bypass.nix `) diff --git a/docs/usage/.snippets/examples-private-vpn-1.nix b/docs/usage/.snippets/examples-private-vpn-1.nix index 6d84da5..e10a8c4 100644 --- a/docs/usage/.snippets/examples-private-vpn-1.nix +++ b/docs/usage/.snippets/examples-private-vpn-1.nix @@ -15,15 +15,16 @@ in inbounds = { enable = true; routing.via = "proxy"; + # Fixed addresses, so firewall rules and DNS can name each device. + # Keys are generated on first start. + users = { + laptop.address = "10.77.77.2"; + phone.address = "10.77.77.3"; + }; listeners.vpn = { type = "amneziawg"; port = 51820; - # Fixed addresses, so firewall rules and DNS can name each device. - # Keys are generated on first start. - users = [ - { name = "laptop"; address = "10.77.77.2"; } - { name = "phone"; address = "10.77.77.3"; } - ]; + users = [ "laptop" "phone" ]; amneziaWg = { # Devices also reach this host, its LAN and each other, directly. mode = "lan"; diff --git a/docs/usage/.snippets/examples-relay-server-1.nix b/docs/usage/.snippets/examples-relay-server-1.nix index c8b850c..e524ee7 100644 --- a/docs/usage/.snippets/examples-relay-server-1.nix +++ b/docs/usage/.snippets/examples-relay-server-1.nix @@ -3,7 +3,7 @@ let domain = "vpn.example.com"; certDir = config.security.acme.certs.${domain}.directory; - users = map (name: { inherit name; uuidFile = "/run/secrets/proxy-uuid-${name}"; }) [ + users = [ "alice" "bob" "carol" @@ -54,6 +54,7 @@ in }; inbounds = { + users = lib.genAttrs users (name: { uuidFile = "/run/secrets/proxy-uuid-${name}"; }); enable = true; serverAddress = domain; routing.via = "proxy"; diff --git a/docs/usage/.snippets/server-1.nix b/docs/usage/.snippets/server-1.nix index 21f67fb..26bb9cc 100644 --- a/docs/usage/.snippets/server-1.nix +++ b/docs/usage/.snippets/server-1.nix @@ -6,15 +6,17 @@ enable = true; serverAddress = "vpn.example.com"; # null: this host's public IPv4 routing.via = "direct"; # clients exit straight from this host + # Each user once; listeners name the ones they accept, and take the secret they need. + users = { + phone.uuidFile = "/run/secrets/uuid-phone"; + laptop.uuidFile = "/run/secrets/uuid-laptop"; + }; listeners = { vless-reality = { type = "vless"; port = 443; flow = "xtls-rprx-vision"; - users = [ - { name = "phone"; uuidFile = "/run/secrets/uuid-phone"; } - { name = "laptop"; uuidFile = "/run/secrets/uuid-laptop"; } - ]; + users = [ "phone" "laptop" ]; reality = { enable = true; serverNames = [ "www.microsoft.com" ]; @@ -27,7 +29,7 @@ awg = { type = "amneziawg"; port = 51820; - users = [ { name = "phone"; } ]; + users = [ "phone" ]; }; }; }; diff --git a/docs/usage/examples/private-vpn.md b/docs/usage/examples/private-vpn.md index 09a86df..bc9c738 100644 --- a/docs/usage/examples/private-vpn.md +++ b/docs/usage/examples/private-vpn.md @@ -26,15 +26,16 @@ in inbounds = { enable = true; routing.via = "proxy"; + # Fixed addresses, so firewall rules and DNS can name each device. + # Keys are generated on first start. + users = { + laptop.address = "10.77.77.2"; + phone.address = "10.77.77.3"; + }; listeners.vpn = { type = "amneziawg"; port = 51820; - # Fixed addresses, so firewall rules and DNS can name each device. - # Keys are generated on first start. - users = [ - { name = "laptop"; address = "10.77.77.2"; } - { name = "phone"; address = "10.77.77.3"; } - ]; + users = [ "laptop" "phone" ]; amneziaWg = { # Devices also reach this host, its LAN and each other, directly. mode = "lan"; diff --git a/docs/usage/examples/relay-server.md b/docs/usage/examples/relay-server.md index 1f7e1f3..dbf7967 100644 --- a/docs/usage/examples/relay-server.md +++ b/docs/usage/examples/relay-server.md @@ -23,7 +23,7 @@ let domain = "vpn.example.com"; certDir = config.security.acme.certs.${domain}.directory; - users = map (name: { inherit name; uuidFile = "/run/secrets/proxy-uuid-${name}"; }) [ + users = [ "alice" "bob" "carol" @@ -74,6 +74,7 @@ in }; inbounds = { + users = lib.genAttrs users (name: { uuidFile = "/run/secrets/proxy-uuid-${name}"; }); enable = true; serverAddress = domain; routing.via = "proxy"; diff --git a/docs/usage/server.md b/docs/usage/server.md index 89567c7..26e0563 100644 --- a/docs/usage/server.md +++ b/docs/usage/server.md @@ -40,15 +40,17 @@ services.proxy-suite = { enable = true; serverAddress = "vpn.example.com"; # null: this host's public IPv4 routing.via = "direct"; # clients exit straight from this host + # Each user once; listeners name the ones they accept, and take the secret they need. + users = { + phone.uuidFile = "/run/secrets/uuid-phone"; + laptop.uuidFile = "/run/secrets/uuid-laptop"; + }; listeners = { vless-reality = { type = "vless"; port = 443; flow = "xtls-rprx-vision"; - users = [ - { name = "phone"; uuidFile = "/run/secrets/uuid-phone"; } - { name = "laptop"; uuidFile = "/run/secrets/uuid-laptop"; } - ]; + users = [ "phone" "laptop" ]; reality = { enable = true; serverNames = [ "www.microsoft.com" ]; @@ -61,7 +63,7 @@ services.proxy-suite = { awg = { type = "amneziawg"; port = 51820; - users = [ { name = "phone"; } ]; + users = [ "phone" ]; }; }; }; diff --git a/modules/proxy-suite/config-templates/proxy-inbounds.nix b/modules/proxy-suite/config-templates/proxy-inbounds.nix index 873d8c2..921fad2 100644 --- a/modules/proxy-suite/config-templates/proxy-inbounds.nix +++ b/modules/proxy-suite/config-templates/proxy-inbounds.nix @@ -16,6 +16,62 @@ let localProxyAddress = derived.localProxy.host; + # Checked on the address actually dialed, so a name resolving private is caught too + # (routing's geoip:private sees only literal IPs under AsIs). Explicit either way: + # XRay's own default blocks private for vless/vmess/trojan/shadowsocks only, which + # left socks/http open and ignored blockPrivate = false. + directFinalRules = + if derived.proxyInboundsCfg.routing.blockPrivate then + [ + { + action = "block"; + ip = [ "geoip:private" ]; + } + ] + else + [ { 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" ]; + } + ]; + mkSelfOutbound = family: address: id: { + protocol = "freedom"; + tag = "direct-self${family}-${id}"; + sendThrough = address; + settings = { + domainStrategy = if family == "4" then "UseIPv4" else "UseIPv6"; + finalRules = selfFinalRules; + }; + }; + selfOutbounds = lib.concatMap ( + s: + lib.optional (s.ipv4 != null) (mkSelfOutbound "4" s.ipv4 s.id) + ++ lib.optional (s.ipv6 != null) (mkSelfOutbound "6" s.ipv6 s.id) + ) derived.proxyInboundsSelfSources; + # The client stack's SOCKS listener; credentials are injected at start. localProxyOutbound = lib.optional proxyInboundsNeedLocalProxy { protocol = "socks"; @@ -72,31 +128,21 @@ in }; }; - outbounds = localProxyOutbound ++ [ - { - protocol = "freedom"; - tag = "direct"; - # Checked on the address actually dialed, so a name resolving private is caught too - # (routing's geoip:private sees only literal IPs under AsIs). Explicit either way: - # XRay's own default blocks private for vless/vmess/trojan/shadowsocks only, which - # left socks/http open and ignored blockPrivate = false. - settings.finalRules = - if derived.proxyInboundsCfg.routing.blockPrivate then - [ - { - action = "block"; - ip = [ "geoip:private" ]; - } - ] - else - [ { action = "allow"; } ]; - } - { - protocol = "blackhole"; - tag = "block"; - settings = { }; - } - ]; + outbounds = + localProxyOutbound + ++ [ + { + protocol = "freedom"; + tag = "direct"; + settings.finalRules = directFinalRules; + } + { + protocol = "blackhole"; + tag = "block"; + settings = { }; + } + ] + ++ selfOutbounds; routing = { # AsIs where sing-box dials: resolving here made every new site wait on a diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 2d8e5f1..3f47b08 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -26,7 +26,13 @@ let inboundRules = import ./rules/proxy-inbounds.nix { inherit lib; - inherit (derived) proxyInboundsCfg proxyInbounds proxyInboundsRouteOnion; + inherit (derived) + proxyInboundsCfg + proxyInbounds + proxyInboundsRouteOnion + proxyInboundsResolveInSingBox + proxyInboundsSelfSources + ; inherit (rules) zapretDirectRules; }; diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index b561596..82d74be 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -181,6 +181,58 @@ let }) proxyInboundsCfg.listeners ); + # 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; + proxyInboundsSelfSources = + let + src = proxyInboundsServerSource; + # The users XRay's listeners accept (by name, XRay's email): numbered by their order, + # the rest after the highest order, by name. + names = lib.unique ( + lib.concatMap (ib: map (user: user.name) ib.listener.users) ( + builtins.filter (ib: ib.listener.type != "amneziawg") proxyInbounds + ) + ); + orderOf = name: proxyInboundsCfg.users.${name}.order; + ordered = builtins.filter (name: orderOf name != null) names; + highest = lib.foldl lib.max 0 (map orderOf ordered); + numbered = + map (name: { + email = name; + number = orderOf name; + }) ordered + ++ lib.imap1 (i: name: { + email = name; + number = highest + i; + }) (lib.sort lib.lessThan (builtins.filter (name: orderOf name == null) names)); + octets = + cidr: + map lib.toInt (lib.take 4 (builtins.match "([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)/[0-9]+" cidr)); + v4Int = cidr: lib.foldl (acc: o: acc * 256 + o) 0 (octets cidr); + v4String = + n: + lib.concatMapStringsSep "." (shift: toString (lib.mod (n / shift) 256)) [ + 16777216 + 65536 + 256 + 1 + ]; + v6Prefix = cidr: builtins.head (lib.splitString "/" cidr); + in + lib.optionals (src.ipv4 != null || src.ipv6 != null) ( + map ( + { email, number }: + { + inherit email number; + id = toString number; + ipv4 = if src.ipv4 == null then null else v4String (v4Int src.ipv4 + number); + ipv6 = + if src.ipv6 == null then null else "${v6Prefix src.ipv6}${lib.toLower (lib.toHexString number)}"; + } + ) (lib.sort (a: b: a.number < b.number) numbered) + ); + # .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 = @@ -606,6 +658,8 @@ in proxyInboundsRouteOnion proxyInboundsNeedLocalProxy proxyInboundsResolveInSingBox + proxyInboundsServerSource + proxyInboundsSelfSources proxyInboundsGuardPrivate proxyInboundsGuardStrategy proxyInboundViaTags diff --git a/modules/proxy-suite/options/inbounds.nix b/modules/proxy-suite/options/inbounds.nix index a82560c..58fc6ac 100644 --- a/modules/proxy-suite/options/inbounds.nix +++ b/modules/proxy-suite/options/inbounds.nix @@ -1,4 +1,9 @@ -{ lib, proxySuiteUpstream, ... }: +{ + config, + lib, + proxySuiteUpstream, + ... +}: let inherit (lib) @@ -108,19 +113,88 @@ in blockRu = bool true ''Block Russian destinations (geosite "category-ru", geoip "ru").''; blockPrivate = bool true "Block private and loopback addresses, so clients cannot reach this host's LAN or local services."; - zapretDirect = bool true "Send zapret hostlist sites direct, so this host's zapret unblocks them. Only for the default `via`."; + zapretDirect = bool true "Send zapret hostlist sites direct, so this host's zapret unblocks them. Only for the default `via`. With a direct listener or the XRay backend, only by IP: XRay matches names by what a client puts in its handshake, whatever address it connects to."; + + # Consumed in derived.nix (the addresses), rules/proxy-inbounds.nix and the inbounds' + # start script (the interface). + serverSource = { + ipv4 = mkOption { + type = types.nullOr (types.strMatching "([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}"); + default = null; + example = "10.78.0.0/24"; + description = '' + Range each inbound user gets an address from, for the connections they make to this + host itself (`serverAddress`, `serverAliases`, `serverPorts`). Otherwise those come + from this host's own address, and its services (mail, the web server, their rate + limits and bans) see every user as one. They see neither the users' real addresses. + The addresses sit on a dummy interface and reach nothing but this host. Pick a range + nothing here routes or trusts. Users are numbered by their `order`, then name, from + the range's second address: set `order` to keep each user's address as users come + and go. + ''; + }; + ipv6 = mkOption { + type = types.nullOr (types.strMatching "[0-9a-fA-F:]*::/[0-9]{1,3}"); + default = null; + example = "fd78:78:78::/64"; + description = '' + The same for IPv6: a prefix written with "::", such as a ULA /64. Needed as well when + `serverAliases` lists an IPv6 address, which is otherwise dialed from this host's own. + ''; + }; + interface = mkOption { + type = types.strMatching "[a-zA-Z0-9_-]{1,15}"; + default = "ps-self"; + description = "Dummy interface the `serverSource` addresses are put on."; + }; + }; + }; + + users = mkOption { + type = types.attrsOf (types.submodule t.userModule); + default = { }; + description = '' + Inbound users, by name, which listeners accept by naming them in their `users`. Each + listener takes the secret its protocol wants: `uuid`/`uuidFile` for vless and vmess, + `password`/`passwordFile` for the others, the keys for AmneziaWG. + ''; + example = literalExpression '' + { + phone = { + order = 1; + uuidFile = "/run/secrets/proxy-inbound-uuid"; + }; + laptop.order = 2; + } + ''; }; listeners = mkOption { type = types.attrsOf t.inboundType; default = { }; description = "Server listeners, by tag."; + # Each named user becomes the user, with their name: nothing past the options sees names. + apply = lib.mapAttrs ( + tag: listener: + listener + // { + users = map ( + name: + (config.services.proxy-suite.inbounds.users.${name} + or (throw "proxy-suite: inbounds listener '${tag}' names user '${name}', which inbounds.users does not define") + ) + // { + inherit name; + } + ) listener.users; + } + ); example = literalExpression '' { vless-reality = { type = "vless"; port = 443; - users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]; + users = [ "phone" ]; flow = "xtls-rprx-vision"; reality = { enable = true; @@ -134,7 +208,7 @@ in home = { type = "amneziawg"; port = 51820; - users = [ { name = "phone"; } { name = "laptop"; } ]; + users = [ "phone" "laptop" ]; amneziaWg.mode = "lan"; }; } diff --git a/modules/proxy-suite/options/types/inbounds.nix b/modules/proxy-suite/options/types/inbounds.nix index d0907b9..c154b62 100644 --- a/modules/proxy-suite/options/types/inbounds.nix +++ b/modules/proxy-suite/options/types/inbounds.nix @@ -5,13 +5,20 @@ let inherit (import ./amnezia-wg.nix { inherit lib; }) obfuscationType; inherit (import ../lib.nix { inherit lib; }) nullStr; - userType = types.submodule { + # One inbound user, in `inbounds.users` under their name (shown in share links, subscriptions + # and stats); listeners name the ones they accept. + userModule = { options = { - name = mkOption { - type = types.str; - default = ""; - description = "User name, shown in share links, subscriptions and stats."; - example = "phone"; + order = mkOption { + type = types.nullOr types.ints.positive; + default = null; + description = '' + 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. + ''; + example = 1; }; uuid = nullStr "UUID (vless, vmess). Ends up in the Nix store; prefer `uuidFile`." "b831381d-6324-4d53-ad4f-8cda48b30811"; uuidFile = nullStr "File with the UUID." "/run/secrets/proxy-inbound-uuid"; @@ -382,10 +389,15 @@ let }; users = mkOption { - type = types.listOf userType; + # Resolved to the users themselves, with their name, by the listeners option's apply + # (options/inbounds.nix): everything past the options reads full users. + type = types.listOf (types.strMatching "[^[:space:]]+"); default = [ ]; - description = "Accepted users."; - example = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ]; + description = "Accepted users, by their names in `inbounds.users`."; + example = [ + "phone" + "laptop" + ]; }; flow = mkOption { @@ -500,5 +512,5 @@ let ); in { - inherit inboundType; + inherit inboundType userModule; } diff --git a/modules/proxy-suite/options/whitelist-bypass.nix b/modules/proxy-suite/options/whitelist-bypass.nix index c4e0ae2..5bf6cd6 100644 --- a/modules/proxy-suite/options/whitelist-bypass.nix +++ b/modules/proxy-suite/options/whitelist-bypass.nix @@ -106,7 +106,7 @@ in type = types.package; default = proxySuiteUpstream.whitelist-bypass; defaultText = lib.literalMD "proxy-suite's `whitelist-bypass` (`pkgs/whitelist-bypass.nix`)"; - description = "whitelist-bypass package."; + description = "whitelist-bypass package. It must take the call link and the proxy password from WB_LINK and WB_UPSTREAM_PASS, as `pkgs/whitelist-bypass.nix` patches it to."; }; joiners = mkOption { diff --git a/modules/proxy-suite/rules/proxy-inbounds.nix b/modules/proxy-suite/rules/proxy-inbounds.nix index 86a5ac5..e0544f9 100644 --- a/modules/proxy-suite/rules/proxy-inbounds.nix +++ b/modules/proxy-suite/rules/proxy-inbounds.nix @@ -5,6 +5,8 @@ proxyInboundsCfg, proxyInbounds, proxyInboundsRouteOnion, + proxyInboundsResolveInSingBox, + proxyInboundsSelfSources, zapretDirectRules, }: @@ -74,15 +76,83 @@ let inherit ruleTag; ${field} = items; inboundTag = exceptionInboundTags; - port = lib.concatMapStringsSep "," toString serverAddressPorts; + port = serverPortList; outboundTag = "direct"; }; - serverAddressRule = - mkServerAddressRule "inbound-server-address-direct" "domain" ( - map (name: if isSuffix name then name else "full:${name}") serverNames + # 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 + # host's own address. Any client could reach any address past routing.via that way by + # naming this host (or a zapret site) in its handshake. So before a name rule sends + # anything direct, a connection to an IP it would match goes where it would have gone + # without the name rule: its listener's via. Under AsIs an ip condition matches only + # connections to an IP. Under IPOnDemand it resolves names as well, so there it only works + # after the IP rules, which a name resolving to this host matches first. + anyIp = [ + "0.0.0.0/0" + "::/0" + ]; + mkSniffGuard = + ruleTag: domains: inbounds: 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); + + serverNameDomains = map (name: if isSuffix name then name else "full:${name}") serverNames; + serverPortList = lib.concatMapStringsSep "," toString serverAddressPorts; + + # inbounds.routing.serverSource: each user's connections to this host leave from the + # user's own address (the "direct-self" outbounds, config-templates/proxy-inbounds.nix), + # ahead of the rules that dial them from this host's. A name is dialed over the family the + # user has an address in. + serverIps4 = builtins.filter (ip: !lib.hasInfix ":" ip) serverIps; + serverIps6 = builtins.filter (lib.hasInfix ":") serverIps; + mkSelfRule = + ruleTag: field: items: source: outboundTag: + lib.optional (items != [ ] && exceptionInboundTags != [ ]) { + type = "field"; + ruleTag = "${ruleTag}-${source.id}"; + ${field} = items; + user = [ source.email ]; + inboundTag = exceptionInboundTags; + port = serverPortList; + inherit outboundTag; + }; + selfIpRules = lib.concatMap ( + s: + lib.optionals (s.ipv4 != null) ( + mkSelfRule "inbound-server-address-self-ip4" "ip" serverIps4 s "direct-self4-${s.id}" ) - ++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps; + ++ lib.optionals (s.ipv6 != null) ( + mkSelfRule "inbound-server-address-self-ip6" "ip" serverIps6 s "direct-self6-${s.id}" + ) + ) proxyInboundsSelfSources; + selfNameRules = lib.concatMap ( + s: + mkSelfRule "inbound-server-address-self" "domain" serverNameDomains s ( + if s.ipv4 != null then "direct-self4-${s.id}" else "direct-self6-${s.id}" + ) + ) proxyInboundsSelfSources; + serverNameGuarded = proxyInboundsResolveInSingBox || serverIps != [ ]; + serverAddressRule = + selfIpRules + ++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps + ++ lib.optionals (serverNames != [ ] && serverNameGuarded && exceptionInboundTags != [ ]) ( + mkSniffGuard "inbound-server-address-sniffed" serverNameDomains (builtins.filter ( + ib: ib.via != "block" + ) proxyInbounds) { port = serverPortList; } + ) + ++ lib.optionals (serverNames != [ ] && serverNameGuarded) selfNameRules + ++ mkServerAddressRule "inbound-server-address-direct" "domain" serverNameDomains; blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [ { @@ -144,11 +214,18 @@ let outboundTag = "direct"; }; + zapretDomains = map (domain: "domain:${domain}") zapretDirectRules.domains; + # Under IPOnDemand the guard would take every zapret name too: the domain rule stays off. zapretRules = - mkZapretRule "inbound-zapret-direct-domain" "domain" ( - map (domain: "domain:${domain}") zapretDirectRules.domains + mkZapretRule "inbound-zapret-direct-ip" "ip" zapretDirectRules.ips + ++ lib.optionals (zapretDirectEnabled && zapretDomains != [ ] && proxyInboundsResolveInSingBox) ( + mkSniffGuard "inbound-zapret-sniffed" zapretDomains (builtins.filter ( + ib: builtins.elem ib.tag defaultInboundTags + ) proxyInbounds) { } ) - ++ mkZapretRule "inbound-zapret-direct-ip" "ip" zapretDirectRules.ips; + ++ lib.optionals proxyInboundsResolveInSingBox ( + mkZapretRule "inbound-zapret-direct-domain" "domain" zapretDomains + ); overrideRules = map (ib: { type = "field"; @@ -179,4 +256,6 @@ let in { inherit xrayInboundRules; + # 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 47ed858..ff30d42 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -185,6 +185,34 @@ let (mkAssertion (!(cfg.warp.enable && cfg.warp.asOutbound != null && cfg.warp.asAmneziaWg)) "proxy-suite: warp.asOutbound and warp.asAmneziaWg share one WARP key and would knock each other off; enable one" ) + # inbounds.routing.serverSource: a dummy interface, and an address per user in each range. + ( + let + src = cfg.inbounds.routing.serverSource; + highest = lib.foldl lib.max 0 (map (s: s.number) derived.proxyInboundsSelfSources); + v4 = builtins.match "([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)/([0-9]+)" src.ipv4; + v4Prefix = lib.toInt (lib.last v4); + v4Int = lib.foldl (acc: o: acc * 256 + lib.toInt o) 0 (lib.take 4 v4); + v4Size = lib.foldl (acc: _: acc * 2) 1 (lib.range 1 (32 - v4Prefix)); + in + mkAssertion + ( + src.ipv4 == null + || (v4Prefix >= 8 && v4Prefix <= 30 && lib.mod v4Int v4Size == 0 && highest + 2 <= v4Size) + ) + "proxy-suite: inbounds.routing.serverSource.ipv4 must be a network address (host bits zero), /8 to /30, with room for user number ${toString highest}" + ) + # A user's order is their serverSource number: two would share an address. + (uniqueValues true (builtins.filter (order: order != null) ( + lib.mapAttrsToList (_: user: user.order) cfg.inbounds.users + )) "proxy-suite: inbounds.users must each have a distinct order") + (mkAssertion ( + 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) + "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. (mkAssertion (cfg.userControl.group != derived.constants.serviceUser) "proxy-suite: userControl.group must not be ${derived.constants.serviceUser}, the group that can read backend configs" @@ -845,9 +873,6 @@ let ]; in lib.optionals (proxyInboundsEnabled && l.type == "amneziawg") [ - (mkAssertion (lib.all (user: user.name != "") - l.users - ) "${prefix}: AmneziaWG users each need a name, which their keys and address are kept under") (mkAssertion (builtins.stringLength awg.interfaceName <= 15) "${prefix}: amneziaWg.interfaceName '${awg.interfaceName}' is longer than the kernel's 15 characters" ) diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index ca27eca..1b86822 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -270,6 +270,32 @@ lib.mkMerge [ "proxy-suite: proxy.listener.address is ${proxyCfg.listener.address} without listener.auth:" + " anyone who reaches the port uses your outbounds; set listener.auth, or keep it off the" + " firewall's allowed ports" + ) + # rules/proxy-inbounds.nix guards the names of this host only where XRay leaves names + # unresolved, or where IP aliases catch a name that resolves here first. + ++ + lib.optional + ( + proxyInboundsEnabled + && !derived.proxyInboundsResolveInSingBox + # Only a listener whose traffic is not direct anyway loses anything by it. + && lib.any ( + ib: + !builtins.elem ib.via [ + "direct" + "block" + ] + ) derived.proxyInbounds + && (cfg.inbounds.serverAddress != null || cfg.inbounds.serverAliases != [ ]) + && lib.all (a: lib.hasPrefix "domain:" a || builtins.match "[0-9.]+|.*:.*" a == null) ( + lib.optional (cfg.inbounds.serverAddress != null) cfg.inbounds.serverAddress + ++ cfg.inbounds.serverAliases + ) + ) + ( + "proxy-suite: with a direct listener or the XRay backend, list this host's IPs in" + + " inbounds.serverAliases: without them a client can name this host in its TLS handshake" + + " while connecting to any other address, which XRay then dials direct, from this host" ); } diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index 682b319..e7422fc 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -25,6 +25,7 @@ let buildOutboundPy proxyInboundsFile proxyInboundsSpecFile + proxyInboundsSelfSources builders constants ; @@ -33,6 +34,22 @@ let subscriptionsFile = "${runtimeDir}/subscriptions.json"; subsCfg = proxyInboundsCfg.subscriptions; xray = "${proxyInboundsCfg.package}/bin/xray"; + + # inbounds.routing.serverSource: the users' own addresses toward this host, on a dummy + # interface. Reached through lo like any local address; nothing routes out from them. + 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 != [ ]) '' + ${selfInterfaceDown} + ${ip} link add ${selfInterface} type dummy + ${ip} link set ${selfInterface} up + ${lib.concatMapStrings ( + s: + 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} + ''; # Only listeners, and for AmneziaWG listeners transparent sockets (IP_TRANSPARENT). runXray = constants.runAsServiceUser pkgs ( [ "net_bind_service" ] ++ lib.optional (proxyInboundsAwg != [ ]) "net_admin" @@ -242,6 +259,7 @@ let ${writeLinksBlock} ${writeSubscriptionsBlock} + ${selfInterfaceUp} exec ${runXray} ${xray} run -c "$RUNTIME_DIR/config.json" ''; @@ -288,10 +306,16 @@ let chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp" mv -f "$tmp" "$file" ''; + stopInboundsInterface = + if proxyInboundsSelfSources == [ ] then + null + else + pkgs.writeShellScript "proxy-suite-inbounds" selfInterfaceDown; in { inherit startInbounds + stopInboundsInterface collectInboundStats linksFile subscriptionsFile diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index c08be12..fbf1f4e 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -168,7 +168,7 @@ let inherit (startScripts) startSocks startTun startPerAppTun; proxyInboundsScripts = import ./proxy-inbounds-scripts.nix { ctx = sctx; }; - inherit (proxyInboundsScripts) startInbounds collectInboundStats; + inherit (proxyInboundsScripts) startInbounds stopInboundsInterface collectInboundStats; proxyInboundsLinksFile = proxyInboundsScripts.linksFile; proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile; @@ -204,6 +204,7 @@ in startTun startPerAppTun startInbounds + stopInboundsInterface collectInboundStats ; inherit diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index fbd2cc3..7b10632 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -118,6 +118,8 @@ let ++ lib.optional torOnionEnabled "proxy-suite-tor.service"; wantedBy = [ "multi-user.target" ]; execStart = scripts.startInbounds; + # inbounds.routing.serverSource's dummy interface. + execStopPost = scripts.stopInboundsInterface; runtimeDirectory = serviceNames.inbounds; # The collector's file. stateDirectory = "proxy-suite"; diff --git a/modules/proxy-suite/tor.nix b/modules/proxy-suite/tor.nix index e10cd53..7b94a5c 100644 --- a/modules/proxy-suite/tor.nix +++ b/modules/proxy-suite/tor.nix @@ -27,10 +27,21 @@ let withProxyAuth = viaProxy && derived.localProxy.authEnabled; bridgesEnabled = t.bridges.lines != [ ] || t.bridges.file != null; - # Members of userControl.group may use the control socket for `proxy-ctl tor - # status|newnym`, so Tor runs with that group on a system install: Tor refuses a - # group-writable socket whose directory is owned by any group but its own. - controlGroup = privileged && derived.userControlAllows "services"; + # The control socket is Tor's own (and root's): with it, one can publish any loopback + # port as an onion service, point Tor at another upstream, or read the proxy password + # from its config. userControl's group asks for a new identity through + # proxy-suite-tor-newnym instead. + controlSocket = derived.constants.torControlSocket; + newnymScript = pkgs.writeShellScript "proxy-suite-tor-newnym" '' + set -euo pipefail + reply=$(printf 'AUTHENTICATE\r\nSIGNAL NEWNYM\r\nQUIT\r\n' \ + | ${pkgs.socat}/bin/socat -t 5 - UNIX-CONNECT:${lib.escapeShellArg controlSocket}) + # One "250 OK" each for AUTHENTICATE and SIGNAL. + if [ "$(${pkgs.gnugrep}/bin/grep -c '^250 OK' <<< "$reply")" -lt 2 ]; then + printf 'Tor refused: %s\n' "$reply" >&2 + exit 1 + fi + ''; # An onion service port per listener: its share port, forwarded to where XRay listens. onionTarget = @@ -68,7 +79,6 @@ let "TransPort 0" "NATDPort 0" "CookieAuthentication 0" - "ControlSocketsGroupWritable 1" ] ++ lib.optional t.clientOnly "ClientOnly 1" ++ (if t.asOutbound then [ "SocksPort 127.0.0.1:${toString t.socksPort}" ] else [ "SocksPort 0" ]) @@ -103,9 +113,7 @@ let umask 0077 torrc="$RUNTIME_DIRECTORY/torrc" - ${pkgs.coreutils}/bin/mkdir -p -m ${ - if controlGroup then "0750" else "0700" - } "$RUNTIME_DIRECTORY/control" + ${pkgs.coreutils}/bin/mkdir -p -m 0700 "$RUNTIME_DIRECTORY/control" { cat <<'TORRC' ${staticConfig} @@ -161,7 +169,19 @@ in RestartSec = 5; LimitNOFILE = 65536; } - // lib.optionalAttrs controlGroup { Group = cfg.userControl.group; } // lib.optionalAttrs onionKeyEnabled { ExecStartPre = onionKeyScript; }; }; + + # `proxy-ctl tor newnym` for userControl's group ("services" scope), which cannot open + # the control socket. Root. + services.proxy-suite.internal.services.proxy-suite-tor-newnym = lib.mkIf privileged { + description = "proxy-suite - new Tor circuits for new connections"; + after = [ "proxy-suite-tor.service" ]; + # Only a running Tor: this never starts one. + unitConfig.Requisite = [ "proxy-suite-tor.service" ]; + serviceConfig = { + Type = "oneshot"; + ExecStart = newnymScript; + }; + }; } diff --git a/modules/proxy-suite/whitelist-bypass.nix b/modules/proxy-suite/whitelist-bypass.nix index 2b490cf..f4cb4f8 100644 --- a/modules/proxy-suite/whitelist-bypass.nix +++ b/modules/proxy-suite/whitelist-bypass.nix @@ -12,17 +12,10 @@ let inherit (derived.constants) unprivilegedServiceConfig privileged serviceUser; inherit (derived.localProxy) auth; - # Every flag that takes the call, joiner and creator alike. - linkFlag = { - wbstream = "--room"; - dion = "--room"; - bitrix = "--room"; - telemost = "--tm-link"; - vk = "--vk-link"; - }; - joinerLinkFlag = linkFlag // { - bitrix = "--link"; - }; + # A file in the state directory, which the whitelistBypass scope's group writes to: a + # regular file only, never through a symlink, which could name the backend's config + # (the daemon reads it) and have its credentials on a command line. + readState = file: "${pkgs.coreutils}/bin/dd if=${file} iflag=nofollow,nonblock status=none"; passwordSource = if auth.passwordFile != null then @@ -59,6 +52,9 @@ let StateDirectory = "proxy-suite/whitelist-bypass"; StateDirectoryMode = stateMode; } + # The group writes the state directory: whatever a name there points at, the daemon + # writes nowhere else. + // lib.optionalAttrs privileged { ProtectSystem = "strict"; } // lib.optionalAttrs groupAccess { Group = stateGroup; } // serviceConfig; }; @@ -72,9 +68,10 @@ let set -euo pipefail join="$STATE_DIRECTORY/${j.tag}.join" ${lib.optionalString (j.linkFile != null) ''[ -e "$join" ] || join="$CREDENTIALS_DIRECTORY/link"''} - link=$(tr -d '[:space:]' < "$join") - exec ${w.package}/bin/headless-${j.platform}-joiner \ - ${joinerLinkFlag.${j.platform}} "$link" --socks-port ${toString j.port} + # The link from the environment (pkgs/whitelist-bypass.nix): argv is public. + WB_LINK=$(${readState ''"$join"''} | tr -d '[:space:]') + export WB_LINK + exec ${w.package}/bin/headless-${j.platform}-joiner --socks-port ${toString j.port} ''; LoadCredential = lib.optional (j.linkFile != null) "link:${j.linkFile}"; } @@ -91,6 +88,8 @@ let set -euo pipefail cookies="$STATE_DIRECTORY/${name}.cookies.json" links="$STATE_DIRECTORY/${name}.link" + # The creator opens it by name: not through a symlink the group left there. + if [ -L "$cookies" ]; then rm -f -- "$cookies"; fi ${lib.optionalString (c.cookiesFile != null) '' [ -e "$cookies" ] || install -m 600 "$CREDENTIALS_DIRECTORY/cookies" "$cookies" ''} @@ -99,9 +98,10 @@ let if c.linkFile != null then ''link=$(tr -d '[:space:]' < "$CREDENTIALS_DIRECTORY/link")'' else - ''link=$(tail -n 1 "$links" 2>/dev/null || true)'' + "link=$(${readState ''"$links"''} 2>/dev/null | tail -n 1 || true)" } - [ -z "$link" ] || args+=(${linkFlag.${c.platform}} "$link") + # From the environment (pkgs/whitelist-bypass.nix): argv is public. + export WB_LINK="$link" ${lib.optionalString viaProxy '' args+=(--upstream-socks ${derived.localProxy.hostPart}:${toString cfg.proxy.listener.port}) ''}${lib.optionalString withProxyAuth '' diff --git a/modules/proxy-suite/zapret2.nix b/modules/proxy-suite/zapret2.nix index e920a3c..ffbd8b7 100644 --- a/modules/proxy-suite/zapret2.nix +++ b/modules/proxy-suite/zapret2.nix @@ -101,7 +101,12 @@ let Type = "notify"; ExecReload = "${lib.getExe' pkgs.coreutils "kill"} -HUP $MAINPID"; Environment = runtimeEnv; + # Its own part of the state only: under the sandbox below, the rest stays read-only. + StateDirectoryMode = if userControlAllows "zapret" then "2775" else "0755"; } + # systemd gives the state directory the unit's group on every start: the group's, which + # edits the lists (as autoProxy's units do). + // lib.optionalAttrs (userControlAllows "zapret") { Group = cfg.userControl.group; } # nfqws2 runs as root and writes its lists in a directory the zapret scope's group # writes to as well. // constants.rootInSharedDirConfig; @@ -136,7 +141,7 @@ in wantedBy = [ "multi-user.target" ]; preStart = mkPreStart; runtimeDirectory = "proxy-suite-zapret"; - stateDirectory = "proxy-suite"; + stateDirectory = "proxy-suite/zapret2"; execStart = "${runtime.daemonScript}"; execStopPost = "${runtime.initScript} stop_fw"; extraServiceConfig = daemonConfig ( @@ -156,7 +161,7 @@ in conflicts = perAppConflicts ++ awgServiceNames; preStart = mkPreStart; runtimeDirectory = "proxy-suite-per-app-zapret"; - stateDirectory = "proxy-suite"; + stateDirectory = "proxy-suite/zapret2"; execStart = "${runtime.daemonScript}"; execStartPre = "${perAppZapretMarkUpScript}"; execStopPost = [ diff --git a/nix/checks/amnezia-wg-inbound-runtime.nix b/nix/checks/amnezia-wg-inbound-runtime.nix index 659fbf7..ec89f4d 100644 --- a/nix/checks/amnezia-wg-inbound-runtime.nix +++ b/nix/checks/amnezia-wg-inbound-runtime.nix @@ -24,7 +24,7 @@ let ); }; - users = names: map (name: { inherit name; }) names; + users = names: names; # Each client imports what the server hands out: the .conf, or the vpn:// link. client = @@ -81,6 +81,12 @@ pkgs.testers.runNixOSTest { inherit serverAddress; routing.via = "direct"; openFirewall = true; + users = pkgs.lib.genAttrs [ + "phone" + "laptop" + "tablet" + "watch" + ] (_: { }); listeners.home = { type = "amneziawg"; port = 51820; diff --git a/nix/checks/chaining-dns.nix b/nix/checks/chaining-dns.nix index 6377731..6c74e9e 100644 --- a/nix/checks/chaining-dns.nix +++ b/nix/checks/chaining-dns.nix @@ -120,16 +120,12 @@ in inbounds = { enable = true; serverAddress = "203.0.113.1"; + users.a.password = "b"; listeners.main = { type = "socks"; port = 1081; via = "exit"; - users = [ - { - name = "a"; - password = "b"; - } - ]; + users = [ "a" ]; }; }; }; @@ -276,16 +272,12 @@ in inbounds = { enable = true; serverAddress = "203.0.113.1"; + users.a.password = "b"; listeners.main = { type = "socks"; port = 1081; via = "exit"; - users = [ - { - name = "a"; - password = "b"; - } - ]; + users = [ "a" ]; }; }; } diff --git a/nix/checks/hosts.nix b/nix/checks/hosts.nix index 4b2d694..90ca2ab 100644 --- a/nix/checks/hosts.nix +++ b/nix/checks/hosts.nix @@ -123,10 +123,11 @@ let }; inbounds = { enable = true; + users.user.uuidFile = "/run/secrets/uuid"; listeners.vless = { type = "vless"; port = 8443; - users = [ { uuidFile = "/run/secrets/uuid"; } ]; + users = [ "user" ]; tls.certificateFile = "/c"; tls.keyFile = "/k"; }; diff --git a/nix/checks/proxy-inbounds-runtime.nix b/nix/checks/proxy-inbounds-runtime.nix index 7744705..6474873 100644 --- a/nix/checks/proxy-inbounds-runtime.nix +++ b/nix/checks/proxy-inbounds-runtime.nix @@ -48,21 +48,20 @@ pkgs.testers.runNixOSTest { inherit serverAddress; routing.via = "direct"; openFirewall = true; + users = { + tester.uuidFile = "/run/inbound-secrets/uuid"; + ss-user.passwordFile = "/run/inbound-secrets/password"; + }; listeners.vless-in = { type = "vless"; port = 8443; - users = [ - { - name = "tester"; - uuidFile = "/run/inbound-secrets/uuid"; - } - ]; + users = [ "tester" ]; }; listeners.ss-in = { type = "shadowsocks"; port = 8388; method = "2022-blake3-aes-128-gcm"; - users = [ { passwordFile = "/run/inbound-secrets/password"; } ]; + users = [ "ss-user" ]; }; }; }; diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index 8896115..b891dc7 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -11,10 +11,28 @@ let inherit (checkLib) ok; inherit (pkgs) lib; + # The users every fixture's listeners name, by what they hold. + usersModule = { + services.proxy-suite.inbounds.users = { + user.uuidFile = "/run/secrets/uuid"; + ws.uuidFile = "/run/secrets/ws"; + h3.uuidFile = "/run/secrets/h3"; + hy2.passwordFile = "/run/secrets/hy2"; + ss.passwordFile = "/run/secrets/ss"; + a.passwordFile = "/run/secrets/a"; + b.passwordFile = "/run/secrets/b"; + second = { }; + phone = { }; + laptop = { }; + far.address = "10.66.1.2"; + }; + }; + evalWithUsers = modules: evalProxySuite (modules ++ [ usersModule ]); + realityListener = { type = "vless"; port = 443; - users = [ { uuidFile = "/run/secrets/uuid"; } ]; + users = [ "user" ]; flow = "xtls-rprx-vision"; reality = { enable = true; @@ -27,7 +45,7 @@ let mkInbounds = inbounds: - evalProxySuite [ + evalWithUsers [ baseModule { services.proxy-suite.inbounds = { @@ -69,7 +87,7 @@ let blockedConfig = mkInboundsConfig blockedFixture; # Two listeners, two different servers. - pinnedFixture = evalProxySuite [ + pinnedFixture = evalWithUsers [ { system.stateVersion = "26.05"; services.proxy-suite = { @@ -141,6 +159,58 @@ let }; aliasedConfig = mkInboundsConfig aliasedFixture; + # Connections to this host from each user's own address: an order is the user's number, + # and users without one follow the highest, by name. + selfSourceInbounds = { + serverAddress = "vpn.example.com"; + serverAliases = [ + "203.0.113.10" + "2001:db8::10" + ]; + routing.serverSource = { + ipv4 = "10.78.0.0/24"; + ipv6 = "fd78:78:78::/64"; + }; + users = { + # One user, two secrets: each listener takes its protocol's. + bob = { + order = 1; + uuidFile = "/run/secrets/bob"; + passwordFile = "/run/secrets/bob"; + }; + alice = { + order = 5; + passwordFile = "/run/secrets/alice"; + }; + anon.uuidFile = "/run/secrets/anon"; + }; + listeners.vless-in = realityListener // { + users = [ + "bob" + "anon" + ]; + }; + listeners.hy-in = { + type = "hysteria2"; + port = 8443; + users = [ + "alice" + "bob" + ]; + tls = { + enable = true; + certificateFile = "/run/secrets/cert"; + keyFile = "/run/secrets/key"; + }; + }; + }; + selfSourceFixture = mkInbounds selfSourceInbounds; + selfSourceConfig = mkInboundsConfig selfSourceFixture; + selfSourceService = selfSourceFixture.config.systemd.services.proxy-suite-inbounds.serviceConfig; + badSelfSourceFixture = mkInbounds ( + lib.recursiveUpdate selfSourceInbounds { routing.serverSource.ipv4 = "10.78.0.5/24"; } + ); + unguardedFixture = mkInbounds { routing = { blockRu = false; @@ -155,7 +225,7 @@ let listeners.ss-in = { type = "shadowsocks"; port = 8388; - users = [ { passwordFile = "/run/secrets/ss"; } ]; + users = [ "ss" ]; }; # Loopback-bound: the port stays closed though the link advertises the public one. listeners.ws-in = { @@ -163,7 +233,7 @@ let port = 10002; sharePort = 443; address = "127.0.0.53"; - users = [ { uuidFile = "/run/secrets/ws"; } ]; + users = [ "ws" ]; transport = { type = "ws"; path = "/vpnjantit"; @@ -178,7 +248,7 @@ let listeners.h3-in = { type = "vless"; port = 8443; - users = [ { uuidFile = "/run/secrets/h3"; } ]; + users = [ "h3" ]; transport = { type = "xhttp"; path = "/h3"; @@ -194,7 +264,7 @@ let listeners.hy2-in = { type = "hysteria2"; port = 8444; - users = [ { passwordFile = "/run/secrets/hy2"; } ]; + users = [ "hy2" ]; tls = { certificateFile = "/run/acme/fullchain.pem"; keyFile = "/run/acme/key.pem"; @@ -209,7 +279,7 @@ let listeners.hy2-in = { type = "hysteria2"; port = 443; - users = [ { passwordFile = "/run/secrets/hy2"; } ]; + users = [ "hy2" ]; tls = { certificateFile = "/c"; keyFile = "/k"; @@ -227,7 +297,7 @@ let type = "vless"; port = 10002; address = "127.0.0.1"; - users = [ { uuidFile = "/run/secrets/ws"; } ]; + users = [ "ws" ]; transport = { type = "ws"; path = "/ws"; @@ -237,7 +307,7 @@ let front-in = { type = "vless"; port = 443; - users = [ { uuidFile = "/run/secrets/uuid"; } ]; + users = [ "user" ]; tls = { enable = true; certificateFile = "/run/acme/fullchain.pem"; @@ -277,8 +347,8 @@ let type = "amneziawg"; port = 51820; users = [ - { name = "phone"; } - { name = "laptop"; } + "phone" + "laptop" ]; }; awgFixture = mkInbounds { @@ -339,7 +409,7 @@ let fixture: (import ./read-generated.nix).readDerivation fixture.config.systemd.services."proxy-suite-inbound-stats".serviceConfig.ExecStart; - controlFixture = evalProxySuite [ + controlFixture = evalWithUsers [ baseModule { services.proxy-suite = { @@ -367,7 +437,7 @@ let mkRejects = proxySuiteConfig: fragment: let - fixture = evalProxySuite [ + fixture = evalWithUsers [ { system.stateVersion = "26.05"; services.proxy-suite = proxySuiteConfig; @@ -395,14 +465,8 @@ let ); ssUsers = [ - { - name = "a"; - passwordFile = "/run/secrets/a"; - } - { - name = "b"; - passwordFile = "/run/secrets/b"; - } + "a" + "b" ]; failing = [ @@ -477,9 +541,21 @@ let (mkRejectsListener ( realityListener // { port = 18533; } ) "collides with a port proxy-suite uses internally") + # An order is an address: two users cannot share one. + (mkRejects ( + baseProxy + // { + inbounds = { + enable = true; + users.a.order = 3; + users.b.order = 3; + listeners.bad = realityListener; + }; + } + ) "inbounds.users must each have a distinct order") # Every user is checked, not only the first. (mkRejectsListener ( - realityListener // { users = realityListener.users ++ [ { name = "second"; } ]; } + realityListener // { users = realityListener.users ++ [ "second" ]; } ) "users each need exactly one of uuid or uuidFile") (mkRejectsListener { type = "shadowsocks"; @@ -487,7 +563,10 @@ let } "needs exactly one of serverPassword or serverPasswordFile") (mkRejectsListener { type = "trojan"; - users = map (u: u // { name = "same"; }) ssUsers; + users = [ + "a" + "a" + ]; tls = { certificateFile = "/c"; keyFile = "/k"; @@ -576,7 +655,7 @@ let listeners.tls-in = { type = "vless"; port = 8443; - users = [ { uuidFile = "/run/secrets/uuid"; } ]; + users = [ "user" ]; tls.enable = true; }; }; @@ -603,7 +682,7 @@ let listeners.hy2-in = { type = "hysteria2"; port = 8444; - users = [ { passwordFile = "/run/secrets/hy2"; } ]; + users = [ "hy2" ]; transport.type = "ws"; tls = { certificateFile = "/c"; @@ -622,7 +701,7 @@ let listeners.hy2-in = { type = "hysteria2"; port = 8444; - users = [ { passwordFile = "/run/secrets/hy2"; } ]; + users = [ "hy2" ]; }; }; } @@ -637,7 +716,7 @@ let listeners.hy2-in = { type = "hysteria2"; port = 8444; - users = [ { passwordFile = "/run/secrets/hy2"; } ]; + users = [ "hy2" ]; acceptProxyProtocol = true; tls = { certificateFile = "/c"; @@ -668,7 +747,7 @@ let listeners.hy2-in = { type = "hysteria2"; port = 443; - users = [ { passwordFile = "/run/secrets/hy2"; } ]; + users = [ "hy2" ]; hysteria.portHopping = "30000-20000"; tls = { certificateFile = "/c"; @@ -734,16 +813,10 @@ let }; } ) "is longer than the kernel's 15 characters") - (mkRejectsListener (awgListener // { users = [ { } ]; }) "users each need a name") (mkRejectsListener ( awgListener // { - users = [ - { - name = "a"; - address = "10.66.1.2"; - } - ]; + users = [ "far" ]; } ) "must be a host address inside amneziaWg.subnet") (mkRejects ( @@ -802,17 +875,39 @@ let (ok ((ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ])) (ok ((ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ])) (ok (!builtins.elem "inbound-block-private" (ruleTags unguardedConfig))) - # serverAddress is exempt after blockPrivate, before the country blocks. + # serverAddress is exempt after blockPrivate, before the country blocks. Sniffing is + # routeOnly, so a connection to another IP naming this host in its handshake would match + # the name: the guard before it sends those the listener's way. ( assert - lib.take 4 (ruleTags namedConfig) == [ + lib.take 5 (ruleTags namedConfig) == [ "inbound-stats-api" "inbound-block-private" + "inbound-server-address-sniffed-proxy" "inbound-server-address-direct" "inbound-block-ru-domain" ]; true ) + ( + let + guard = ruleByTag aliasedConfig "inbound-server-address-sniffed-proxy"; + tags = ruleTags aliasedConfig; + at = tag: lib.lists.findFirstIndex (t: t == tag) null tags; + in + assert + guard.ip == [ + "0.0.0.0/0" + "::/0" + ]; + assert guard.outboundTag == "proxy"; + assert guard.domain == (ruleByTag aliasedConfig "inbound-server-address-direct").domain; + assert guard.port == (ruleByTag aliasedConfig "inbound-server-address-direct").port; + # This host's IPs first: a client that resolved the name itself still gets here. + assert at "inbound-server-address-direct-ip" < at "inbound-server-address-sniffed-proxy"; + assert at "inbound-server-address-sniffed-proxy" < at "inbound-server-address-direct"; + true + ) (ok ((ruleByTag namedConfig "inbound-server-address-direct").domain == [ "full:vpn.example.ru" ])) # Names that resolve private are refused where XRay dials them itself. ( @@ -853,6 +948,53 @@ let true ) # serverPorts join the listener's, ranges as they are. + # inbounds.routing.serverSource: bob 1 and alice 5 by their orders, anon after them (6); + # each family its outbound. + ( + let + out = tag: builtins.head (builtins.filter (ob: ob.tag == tag) selfSourceConfig.outbounds); + tags = ruleTags selfSourceConfig; + at = tag: lib.lists.findFirstIndex (t: t == tag) null tags; + startScript = (import ./read-generated.nix).readDerivation selfSourceService.ExecStart; + in + assert (out "direct-self4-1").sendThrough == "10.78.0.1"; + assert (out "direct-self6-5").sendThrough == "fd78:78:78::5"; + assert (out "direct-self4-6").sendThrough == "10.78.0.6"; + assert (out "direct-self4-1").settings.domainStrategy == "UseIPv4"; + # Only ever this host. + assert + (out "direct-self4-1").settings.finalRules == [ + { + action = "allow"; + ip = [ + "203.0.113.10" + "2001:db8::10" + ]; + } + { action = "block"; } + ]; + assert (ruleByTag selfSourceConfig "inbound-server-address-self-ip4-1").user == [ "bob" ]; + assert (ruleByTag selfSourceConfig "inbound-server-address-self-ip4-5").user == [ "alice" ]; + assert (ruleByTag selfSourceConfig "inbound-server-address-self-ip4-5").ip == [ "203.0.113.10" ]; + assert + (ruleByTag selfSourceConfig "inbound-server-address-self-ip6-5").outboundTag == "direct-self6-5"; + assert (ruleByTag selfSourceConfig "inbound-server-address-self-6").user == [ "anon" ]; + assert + (ruleByTag selfSourceConfig "inbound-server-address-self-6").domain == [ "full:vpn.example.com" ]; + # Users' own rules before the host's, and the names behind the sniffing guard. + assert at "inbound-server-address-self-ip4-1" < at "inbound-server-address-direct-ip"; + assert at "inbound-server-address-sniffed-proxy" < at "inbound-server-address-self-1"; + assert at "inbound-server-address-self-1" < at "inbound-server-address-direct"; + assert lib.hasInfix "link add ps-self type dummy" startScript; + assert lib.hasInfix "addr add 10.78.0.5/32 dev ps-self" startScript; + assert lib.hasInfix "-6 addr add fd78:78:78::6/128 dev ps-self nodad" startScript; + assert selfSourceService ? ExecStopPost; + assert !(relayFixture.config.systemd.services.proxy-suite-inbounds.serviceConfig ? ExecStopPost); + assert builtins.any ( + a: !a.assertion && lib.hasInfix "serverSource.ipv4 must be a network address" a.message + ) badSelfSourceFixture.config.assertions; + true + ) (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/tor.nix b/nix/checks/tor.nix index b13207e..8459a44 100644 --- a/nix/checks/tor.nix +++ b/nix/checks/tor.nix @@ -21,7 +21,7 @@ let listener = { type = "vless"; port = 10443; - users = [ { uuidFile = "/run/secrets/uuid"; } ]; + users = [ "user" ]; }; mkFixture = @@ -31,6 +31,7 @@ let system.stateVersion = "26.05"; services.proxy-suite = lib.recursiveUpdate { enable = true; + inbounds.users.user.uuidFile = "/run/secrets/uuid"; tor = { enable = true; asOutbound = true; @@ -121,6 +122,7 @@ let }; inbounds = { enable = true; + users.user.uuidFile = "/run/secrets/uuid"; serverAddress = "vpn.example.com"; routing.via = "direct"; listeners.plain = listener; @@ -135,6 +137,7 @@ let exitInbounds = { inbounds = { enable = true; + users.user.uuidFile = "/run/secrets/uuid"; serverAddress = "vpn.example.com"; routing.via = "direct"; listeners.plain = listener; @@ -196,111 +199,119 @@ let onionInbounds = (services onion).proxy-suite-inbounds; invalidAssertions = mkFailingAssertions mkBadProxySuiteFixture ( - map (case: { enable = true; } // case) [ - # Enabled but used for nothing. - { tor.enable = true; } - # An outbound without a backend. - { - tor = { + map + ( + case: + lib.recursiveUpdate { enable = true; - asOutbound = true; - }; - } - # "tor" is taken. - { - tor = { - enable = true; - asOutbound = true; - }; - proxy = { - enable = true; - outbounds = [ - { - tag = "tor"; - url = "http://proxy.example.com:8080"; - } - ]; - }; - } - # Snowflake ignores Socks5Proxy. - { - tor = { - enable = true; - asOutbound = true; - upstream = "proxy"; - bridges.lines = [ "snowflake 192.0.2.3:80 2B280B23E1107BB62ABFC40DDCC8824814F80A72" ]; - }; - proxy = { - enable = true; - outbounds = [ - { - tag = "vps"; - url = "http://vps.example.com:8080"; - } - ]; - }; - } - # Upstream through the proxy with Tor its only outbound: Tor through itself. - { - tor = { - enable = true; - asOutbound = true; - upstream = "proxy"; - }; - proxy.enable = true; - } - # The SOCKS port on the proxy's own. - { - tor = { - enable = true; - asOutbound = true; - socksPort = 1080; - }; - proxy = { - enable = true; - listener.port = 1080; - }; - } - # An onion service without inbounds, and one naming a listener that is not there. - { - tor = { - enable = true; - onionService.enable = true; - }; - } - { - tor = { - enable = true; - onionService = { + inbounds.users.user.uuidFile = "/run/secrets/uuid"; + } case + ) + [ + # Enabled but used for nothing. + { tor.enable = true; } + # An outbound without a backend. + { + tor = { enable = true; - listeners = [ "missing" ]; + asOutbound = true; }; - }; - inbounds = { - enable = true; - routing.via = "direct"; - listeners.plain = listener; - }; - } - # Two listeners on one onion port. - { - tor = { - enable = true; - onionService.enable = true; - }; - inbounds = { - enable = true; - routing.via = "direct"; - listeners.a = listener // { - sharePort = 443; + } + # "tor" is taken. + { + tor = { + enable = true; + asOutbound = true; }; - listeners.b = listener // { - port = 10444; - sharePort = 443; + proxy = { + enable = true; + outbounds = [ + { + tag = "tor"; + url = "http://proxy.example.com:8080"; + } + ]; }; - }; - } - ] + } + # Snowflake ignores Socks5Proxy. + { + tor = { + enable = true; + asOutbound = true; + upstream = "proxy"; + bridges.lines = [ "snowflake 192.0.2.3:80 2B280B23E1107BB62ABFC40DDCC8824814F80A72" ]; + }; + proxy = { + enable = true; + outbounds = [ + { + tag = "vps"; + url = "http://vps.example.com:8080"; + } + ]; + }; + } + # Upstream through the proxy with Tor its only outbound: Tor through itself. + { + tor = { + enable = true; + asOutbound = true; + upstream = "proxy"; + }; + proxy.enable = true; + } + # The SOCKS port on the proxy's own. + { + tor = { + enable = true; + asOutbound = true; + socksPort = 1080; + }; + proxy = { + enable = true; + listener.port = 1080; + }; + } + # An onion service without inbounds, and one naming a listener that is not there. + { + tor = { + enable = true; + onionService.enable = true; + }; + } + { + tor = { + enable = true; + onionService = { + enable = true; + listeners = [ "missing" ]; + }; + }; + inbounds = { + enable = true; + routing.via = "direct"; + listeners.plain = listener; + }; + } + # Two listeners on one onion port. + { + tor = { + enable = true; + onionService.enable = true; + }; + inbounds = { + enable = true; + routing.via = "direct"; + listeners.a = listener // { + sharePort = 443; + }; + listeners.b = listener // { + port = 10444; + sharePort = 443; + }; + }; + } + ] ); in { @@ -457,11 +468,16 @@ in && !(hasInfix "HiddenService" singBoxTorStart); true ) - # userControl's group can use the control socket: that is `proxy-ctl tor status|newnym`. + # The control socket is Tor's alone, with userControl or without: with it the group could + # publish any loopback port as an onion service. `proxy-ctl tor newnym` goes through a + # root unit, which polkit's "services" scope may start. ( assert - (services controlled).proxy-suite-tor.serviceConfig.Group == "proxy-suite" - && hasInfix "mkdir -p -m 0750" (torStartOf controlled) + (services controlled).proxy-suite-tor.serviceConfig.Group == "proxy-suite-daemon" + && hasInfix "mkdir -p -m 0700" (torStartOf controlled) + && !(hasInfix "ControlSocketsGroupWritable" (torStartOf controlled)) + && (services controlled) ? proxy-suite-tor-newnym + && hasInfix "\"proxy-suite-tor-newnym.service\"" (controlled.config.security.polkit.extraConfig) && singBoxTorUnit.serviceConfig.Group == "proxy-suite-daemon" && !(singBoxTorUnit.serviceConfig ? ExecStartPre) && diff --git a/nix/checks/zapret2.nix b/nix/checks/zapret2.nix index 2290d07..01c4723 100644 --- a/nix/checks/zapret2.nix +++ b/nix/checks/zapret2.nix @@ -66,7 +66,7 @@ in assert envValue zapret2Global globalService "HOSTLIST_BASE=" == "/var/lib/proxy-suite/zapret2"; assert zapret2Global.config.systemd.services.${globalService}.serviceConfig.StateDirectory - == "proxy-suite"; + == "proxy-suite/zapret2"; assert envValue zapret2PerApp perAppService "HOSTLIST_BASE=" == "/var/lib/proxy-suite/zapret2"; assert envValue zapret2PerApp perAppService "Z2K_STATE_DIR_OVERRIDE=" diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index f97e7c4..8888697 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -364,7 +364,8 @@ def _warp_unit(): def _tor_control(*commands): """Replies to commands on Tor's control socket, one list of lines per command. - The socket authenticates by who can open it: root and the userControl group. + The socket authenticates by who can open it: root, and Tor's own user. Not the + userControl group, which could publish any loopback port as an onion service with it. """ path = env("TOR_CONTROL_SOCKET", f"{runtime_dir()}/proxy-suite-tor/control/socket") replies = [] @@ -413,7 +414,11 @@ def cmd_tor(verb="status", *args): if verb == "newnym": if not svc_exists(unit): die("tor is not enabled in this configuration.") - _tor_control("SIGNAL NEWNYM") + if env("PRIVILEGED") == "1" and os.geteuid() != 0: + # The group's way in, polkit's "services" scope: a root unit that asks Tor. + must("start", "proxy-suite-tor-newnym.service") + else: + _tor_control("SIGNAL NEWNYM") print("New connections take new circuits (Tor allows this once every 10 seconds).") return if verb not in ("status", "on", "off", "toggle", "restart"): diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index 9c8ea9e..ad5d158 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -1301,6 +1301,16 @@ class TorTest(EnvTest): self.thread.join(5) self.assertEqual(self.received, ["AUTHENTICATE", "SIGNAL NEWNYM"]) + def test_newnym_as_the_group_goes_through_the_unit(self): + """On a system install only root opens the socket: the group starts a root unit.""" + os.environ["PRIVILEGED"] = "1" + started = [] + self.patch("systemctl", lambda *a, **kw: started.append(a) or (0, None)) + with mock.patch.object(ctl.os, "geteuid", return_value=1000): + ok(ctl.cmd_tor, "newnym") + self.assertIn(("start", "proxy-suite-tor-newnym.service"), started) + self.assertEqual(self.received, []) + def test_not_running(self): os.environ["TOR_CONTROL_SOCKET"] = "missing" status, _, err = run(ctl.cmd_tor, "newnym") diff --git a/pkgs/whitelist-bypass.nix b/pkgs/whitelist-bypass.nix index 0f90940..d202974 100644 --- a/pkgs/whitelist-bypass.nix +++ b/pkgs/whitelist-bypass.nix @@ -26,14 +26,23 @@ pkgs.buildGo126Module (finalAttrs: { "headless/dion-joiner" "headless/bitrix-joiner" ]; - # The local proxy's password from the environment, not argv: a creator runs for good, - # and every local user reads its command line. + # The call link (WB_LINK) and the local proxy's password (WB_UPSTREAM_PASS) from the + # environment, not argv: these run for good, and every local user reads a command line. postPatch = '' + envDefault() { + substituteInPlace "headless/$1/main.go" --replace-fail \ + "flag.String(\"$2\", \"\"," "flag.String(\"$2\", os.Getenv(\"$3\")," + } for p in vk telemost wbstream dion bitrix; do - substituteInPlace headless/$p/main.go --replace-fail \ - 'flag.String("upstream-pass", "",' \ - 'flag.String("upstream-pass", os.Getenv("WB_UPSTREAM_PASS"),' + envDefault $p upstream-pass WB_UPSTREAM_PASS done + for p in bitrix dion dion-joiner wbstream wbstream-joiner; do + envDefault $p room WB_LINK + done + envDefault bitrix-joiner link WB_LINK + envDefault telemost tm-link WB_LINK + envDefault telemost-joiner tm-link WB_LINK + envDefault vk vk-link WB_LINK ''; ldflags = [ "-s"