From ae8f65da2e5b752a33421157d4a01596f3f98dcc Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Wed, 23 Sep 2026 01:05:19 +0500 Subject: [PATCH] feat: tproxy lan gateway, killswitch; fix: zapret2 fixes, various other --- README.md | 7 +- deploy/installer.sh | 2 +- docs/options/inbounds.md | 28 +- docs/options/index.md | 10 + docs/options/killSwitch.md | 34 ++ docs/options/proxy.md | 235 ++++++++++++ docs/options/zapret.md | 3 +- modules/proxy-suite/amnezia-wg.nix | 41 ++- modules/proxy-suite/assembly.nix | 1 + .../config-templates/proxy-inbounds.nix | 27 +- .../proxy-suite/config-templates/sing-box.nix | 2 +- modules/proxy-suite/config.nix | 1 + modules/proxy-suite/core.nix | 11 + modules/proxy-suite/derived.nix | 66 +++- modules/proxy-suite/hosts/nixos.nix | 11 + modules/proxy-suite/inbound-stats-add.jq | 3 +- modules/proxy-suite/nftables.nix | 74 +++- modules/proxy-suite/options/default.nix | 1 + modules/proxy-suite/options/host.nix | 2 + modules/proxy-suite/options/kill-switch.nix | 11 + modules/proxy-suite/options/proxy-routing.nix | 52 +++ modules/proxy-suite/options/proxy-tproxy.nix | 11 + modules/proxy-suite/options/types.nix | 14 +- .../proxy-suite/options/types/inbounds.nix | 9 +- modules/proxy-suite/options/zapret2.nix | 3 +- modules/proxy-suite/rules.nix | 7 +- modules/proxy-suite/rules/sing-box.nix | 43 ++- modules/proxy-suite/rulesets.nix | 137 +++++++ modules/proxy-suite/service-assertions.nix | 89 ++++- modules/proxy-suite/service/context.nix | 2 + modules/proxy-suite/service/control.nix | 9 +- modules/proxy-suite/service/default.nix | 25 +- .../service/proxy-inbounds-scripts.nix | 18 +- .../proxy-suite/service/routing-scripts.nix | 24 ++ modules/proxy-suite/service/units.nix | 28 +- modules/proxy-suite/zapret2.nix | 45 ++- modules/proxy-suite/zapret2/runtime.nix | 25 +- modules/proxy-suite/zapret2/sources.nix | 19 +- nix/checks/_groups-tmp.nix | 342 ++++++++++++++++++ nix/checks/global-proxy-modes.nix | 89 +++++ nix/checks/global-proxy-modes/fixtures.nix | 61 ++++ nix/checks/lib.nix | 1 + nix/checks/module-suite.nix | 2 + nix/checks/proxy-inbounds-runtime.nix | 2 +- nix/checks/proxy-inbounds.nix | 60 ++- nix/checks/tor.nix | 3 +- nix/checks/zapret2.nix | 41 ++- pkgs/proxy-ctl/proxy_ctl.py | 99 ++++- pkgs/proxy-ctl/proxy_model.py | 1 + pkgs/proxy-ctl/test_proxy_ctl.py | 36 ++ scripts/amneziawg_config.py | 39 ++ scripts/proxy_inbound.py | 51 ++- scripts/test-amneziawg-config.py | 36 ++ scripts/test-build-inbound.py | 30 +- 54 files changed, 1880 insertions(+), 143 deletions(-) create mode 100644 docs/options/killSwitch.md create mode 100644 modules/proxy-suite/options/kill-switch.nix create mode 100644 modules/proxy-suite/rulesets.nix create mode 100644 nix/checks/_groups-tmp.nix diff --git a/README.md b/README.md index 8f54b83..33540c1 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Inspired by [Throne](https://github.com/throneproj/Throne) (formerly NekoRay), [ - Local SOCKS5/HTTP proxy on `127.0.0.1:1080`, backed by sing-box, XRay, or both - Global TProxy or TUN mode, on demand or at boot +- A kill switch for the global tunnels (TUN, TProxy, AmneziaWG): nothing leaves outside them while they restart or after they fail - Per-app routing: `proxy-ctl apps run -- ` through proxychains, a per-app TUN/TProxy, or zapret - Outbounds from URLs, raw JSON or subscriptions; manual or latency-based selection; per-outbound routing - vless (REALITY, TLS), vmess, trojan, shadowsocks, hysteria2, socks, http; TUIC, AnyTLS and NaïveProxy on sing-box, XHTTP/ECH on XRay @@ -26,7 +27,7 @@ Inspired by [Throne](https://github.com/throneproj/Throne) (formerly NekoRay), [ - Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel - Cloudflare WARP from a `wgcf` profile, as an outbound or an AWG VPN profile - Tor as an outbound, with `.onion` names routed to it automatically, bridges (obfs4, webtunnel, meek, snowflake), and an onion service in front of the server inbounds -- Server inbounds (XRay protocols and multi-user AmneziaWG) with share links, QR codes, per-user subscriptions and traffic stats +- Server inbounds (XRay protocols, hysteria2, and multi-user AmneziaWG) with share links, QR codes, per-user subscriptions and traffic stats - Proxy Suite GUI (a desktop app with a tray icon), the `proxy-ctl` CLI, and the `proxy-tui` terminal UI ## Setup @@ -158,6 +159,7 @@ Secrets and changes need root, or the userControl group. proxy subs add [tag] add a subscription at runtime; no tag: named after its host proxy subs rm remove a runtime subscription proxy subs link [--qr] its URL + proxy rulesets [list|update] routing rule sets: when each was fetched; update fetches them now proxy config [--raw] client config to import elsewhere; --raw: as running proxy tun [status|on|off] global TUN mode proxy tproxy [status|on|off] global TProxy mode @@ -182,6 +184,9 @@ Secrets and changes need root, or the userControl group. awg [list] AmneziaWG profiles and their state awg on | off [profile] | restart [profile] + killswitch [status|on|off] reject traffic outside the global tunnel; up with + TUN, TProxy or AWG, lifted only by off here or on them + ssh [status|on|off] SSH SOCKS5 tunnel warp [status|on|off] WARP tunnel behind the warp outbound tor [status|on|off] Tor, behind the tor outbound and the onion service diff --git a/deploy/installer.sh b/deploy/installer.sh index 161a012..f006447 100644 --- a/deploy/installer.sh +++ b/deploy/installer.sh @@ -95,7 +95,7 @@ done while true; do ask SSH_PORT "SSH port" "22" if [[ $SSH_PORT =~ ^[0-9]+$ ]] && ((SSH_PORT >= 1 && SSH_PORT <= 65535)) && - [[ ! " 80 443 2053 8443 18533 18534 18535 18536 " == *" $SSH_PORT "* ]]; then + [[ ! " 80 443 2053 8443 18533 18534 18535 " == *" $SSH_PORT "* ]]; then break fi reject "A free port from 1 to 65535 (80, 443, 2053 and 8443 are taken)." SSH_PORT diff --git a/docs/options/inbounds.md b/docs/options/inbounds.md index d40a1c8..1fac4fe 100644 --- a/docs/options/inbounds.md +++ b/docs/options/inbounds.md @@ -48,6 +48,8 @@ Part of the [proxy-suite options reference](./index.md). - [subnet](#services-proxy-suite-inbounds-listeners-name-amneziawg-subnet) - [subnet6](#services-proxy-suite-inbounds-listeners-name-amneziawg-subnet6) - [flow](#services-proxy-suite-inbounds-listeners-name-flow) + - hysteria + - [masquerade](#services-proxy-suite-inbounds-listeners-name-hysteria-masquerade) - [jsonFile](#services-proxy-suite-inbounds-listeners-name-jsonfile) - [method](#services-proxy-suite-inbounds-listeners-name-method) - [port](#services-proxy-suite-inbounds-listeners-name-port) @@ -770,6 +772,27 @@ null "xtls-rprx-vision" ``` + +## services\.proxy-suite\.inbounds\.listeners\.\\.hysteria\.masquerade + +Site that a hysteria2 listener serves, reverse-proxied, to anything that is not a client +(a browser, a prober)\. Null answers them with 404\. + +*Type:* +null or string + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"https://www.example.com" +``` + ## services\.proxy-suite\.inbounds\.listeners\.\\.jsonFile @@ -1292,10 +1315,11 @@ one of “raw”, “ws”, “grpc”, “httpupgrade”, “xhttp” Protocol\. Set exactly one of type, xrayJson, or jsonFile\. “amneziawg” is an AmneziaWG server on UDP port, with its own interface (see amneziaWg); its traffic is handed to XRay -and leaves like any other listener’s\. +and leaves like any other listener’s\. “hysteria2” is QUIC on UDP port: it needs tls (a +certificate) and takes passwords, and no transport, reality or flow\. *Type:* -null or one of “vless”, “vmess”, “trojan”, “shadowsocks”, “socks”, “http”, “amneziawg” +null or one of “vless”, “vmess”, “trojan”, “hysteria2”, “shadowsocks”, “socks”, “http”, “amneziawg” *Default:* diff --git a/docs/options/index.md b/docs/options/index.md index 034eaf3..6528c65 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -10,6 +10,7 @@ Update the module option docs there instead of editing these files by hand. - [geodata](./geodata.md) - [gui](./gui.md) - [inbounds](./inbounds.md) +- [killSwitch](./killSwitch.md) - [perAppRouting](./perAppRouting.md) - [proxy](./proxy.md) - [sshProxy](./sshProxy.md) @@ -72,6 +73,9 @@ services.proxy-suite = { group = "nginx"; }; }; + killSwitch = { + enable = false; + }; perAppRouting = { createDefaultProfiles = false; enable = false; @@ -159,6 +163,7 @@ services.proxy-suite = { geoips = [ ]; geosites = [ ]; ips = [ ]; + ruleSets = [ ]; }; default = "proxy"; direct = { @@ -166,6 +171,7 @@ services.proxy-suite = { geoips = [ ]; geosites = [ ]; ips = [ ]; + ruleSets = [ ]; }; directRu = true; proxy = { @@ -173,7 +179,10 @@ services.proxy-suite = { geoips = [ ]; geosites = [ ]; ips = [ ]; + ruleSets = [ ]; }; + ruleSetUpdateInterval = "1d"; + ruleSets = { }; rules = [ ]; }; selection = "first"; @@ -187,6 +196,7 @@ services.proxy-suite = { tproxy = { enable = false; fwmark = 1; + lanInterfaces = [ ]; localSubnets = [ "192.168.0.0/16" ]; diff --git a/docs/options/killSwitch.md b/docs/options/killSwitch.md new file mode 100644 index 0000000..06e4165 --- /dev/null +++ b/docs/options/killSwitch.md @@ -0,0 +1,34 @@ +# services.proxy-suite.killSwitch + +Part of the [proxy-suite options reference](./index.md). + +## Options + +- killSwitch + - [enable](#services-proxy-suite-killswitch-enable) + + +## services\.proxy-suite\.killSwitch\.enable + +Whether to enable a kill switch for the global tunnels (proxy\.tun, proxy\.tproxy and global AmneziaWG profiles): +once one starts, outgoing traffic that would leave outside it is rejected, also while it +restarts, after it crashes or after its handshake gives up\. LAN destinations, DHCP and NTP +stay open; tproxy\.lanInterfaces clients keep the LAN but lose the internet\. Only +` proxy-ctl killswitch off `, ` proxy off `, ` proxy tun off `, ` proxy tproxy off ` or ` awg off ` +lift it (proxy-suite-killswitch) +\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` diff --git a/docs/options/proxy.md b/docs/options/proxy.md index 3f74528..2bc46bd 100644 --- a/docs/options/proxy.md +++ b/docs/options/proxy.md @@ -51,6 +51,7 @@ Part of the [proxy-suite options reference](./index.md). - [geoips](#services-proxy-suite-proxy-outbounds-routing-geoips) - [geosites](#services-proxy-suite-proxy-outbounds-routing-geosites) - [ips](#services-proxy-suite-proxy-outbounds-routing-ips) + - [ruleSets](#services-proxy-suite-proxy-outbounds-routing-rulesets) - [singBoxJson](#services-proxy-suite-proxy-outbounds-singboxjson) - [tag](#services-proxy-suite-proxy-outbounds-tag) - [url](#services-proxy-suite-proxy-outbounds-url) @@ -62,18 +63,27 @@ Part of the [proxy-suite options reference](./index.md). - [geoips](#services-proxy-suite-proxy-routing-block-geoips) - [geosites](#services-proxy-suite-proxy-routing-block-geosites) - [ips](#services-proxy-suite-proxy-routing-block-ips) + - [ruleSets](#services-proxy-suite-proxy-routing-block-rulesets) - [default](#services-proxy-suite-proxy-routing-default) - direct - [domains](#services-proxy-suite-proxy-routing-direct-domains) - [geoips](#services-proxy-suite-proxy-routing-direct-geoips) - [geosites](#services-proxy-suite-proxy-routing-direct-geosites) - [ips](#services-proxy-suite-proxy-routing-direct-ips) + - [ruleSets](#services-proxy-suite-proxy-routing-direct-rulesets) - [directRu](#services-proxy-suite-proxy-routing-directru) - proxy - [domains](#services-proxy-suite-proxy-routing-proxy-domains) - [geoips](#services-proxy-suite-proxy-routing-proxy-geoips) - [geosites](#services-proxy-suite-proxy-routing-proxy-geosites) - [ips](#services-proxy-suite-proxy-routing-proxy-ips) + - [ruleSets](#services-proxy-suite-proxy-routing-proxy-rulesets) + - [ruleSetUpdateInterval](#services-proxy-suite-proxy-routing-rulesetupdateinterval) + - [ruleSets](#services-proxy-suite-proxy-routing-rulesets) + - `` + - [detour](#services-proxy-suite-proxy-routing-rulesets-name-detour) + - [format](#services-proxy-suite-proxy-routing-rulesets-name-format) + - [url](#services-proxy-suite-proxy-routing-rulesets-name-url) - [rules](#services-proxy-suite-proxy-routing-rules) - item - [domains](#services-proxy-suite-proxy-routing-rules-domains) @@ -81,6 +91,7 @@ Part of the [proxy-suite options reference](./index.md). - [geosites](#services-proxy-suite-proxy-routing-rules-geosites) - [ips](#services-proxy-suite-proxy-routing-rules-ips) - [outbound](#services-proxy-suite-proxy-routing-rules-outbound) + - [ruleSets](#services-proxy-suite-proxy-routing-rules-rulesets) - [selection](#services-proxy-suite-proxy-selection) - [selectionExclude](#services-proxy-suite-proxy-selectionexclude) - singBox @@ -96,6 +107,7 @@ Part of the [proxy-suite options reference](./index.md). - tproxy - [enable](#services-proxy-suite-proxy-tproxy-enable) - [fwmark](#services-proxy-suite-proxy-tproxy-fwmark) + - [lanInterfaces](#services-proxy-suite-proxy-tproxy-laninterfaces) - [localSubnets](#services-proxy-suite-proxy-tproxy-localsubnets) - [port](#services-proxy-suite-proxy-tproxy-port) - [proxyMark](#services-proxy-suite-proxy-tproxy-proxymark) @@ -859,6 +871,28 @@ list of string ] ``` + +## services\.proxy-suite\.proxy\.outbounds\.\*\.routing\.ruleSets + +Names from proxy\.routing\.ruleSets to match (sing-box and hybrid backends)\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "antifilter" +] +``` + ## services\.proxy-suite\.proxy\.outbounds\.\*\.singBoxJson @@ -1050,6 +1084,28 @@ list of string ] ``` + +## services\.proxy-suite\.proxy\.routing\.block\.ruleSets + +Names from ruleSets blocked\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "ads" +] +``` + ## services\.proxy-suite\.proxy\.routing\.default @@ -1158,6 +1214,28 @@ list of string ] ``` + +## services\.proxy-suite\.proxy\.routing\.direct\.ruleSets + +Names from ruleSets sent direct\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "ru-services" +] +``` + ## services\.proxy-suite\.proxy\.routing\.directRu @@ -1260,6 +1338,117 @@ list of string ] ``` + +## services\.proxy-suite\.proxy\.routing\.proxy\.ruleSets + +Names from ruleSets sent through the proxy\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "antifilter" +] +``` + + +## services\.proxy-suite\.proxy\.routing\.ruleSetUpdateInterval + +How often ruleSets are downloaded again (systemd time span)\. + +*Type:* +string + +*Default:* + +```nix +"1d" +``` + +*Example:* + +```nix +"6h" +``` + + +## services\.proxy-suite\.proxy\.routing\.ruleSets + +sing-box rule sets kept up to date at runtime, for the ruleSets of proxy, direct, block, +rules and an outbound’s routing\. They are fetched every ruleSetUpdateInterval and on +` proxy-ctl proxy rulesets update `, and sing-box picks up a new file without a restart; +until the first fetch one matches nothing\. Not for backend = “xray”\. + +*Type:* +attribute set of (submodule) + +*Default:* + +```nix +{ } +``` + +*Example:* + +```nix +{ + antifilter = { + url = "https://example.com/antifilter.srs"; + }; +} +``` + + +## services\.proxy-suite\.proxy\.routing\.ruleSets\.\\.detour + +Downloaded through the local proxy, or directly\. + +*Type:* +one of “proxy”, “direct” + +*Default:* + +```nix +"proxy" +``` + + +## services\.proxy-suite\.proxy\.routing\.ruleSets\.\\.format + +“binary” (\.srs) or “source” (JSON)\. Null goes by the URL: \.srs is binary\. + +*Type:* +null or one of “binary”, “source” + +*Default:* + +```nix +null +``` + + +## services\.proxy-suite\.proxy\.routing\.ruleSets\.\\.url + +Where the sing-box rule set is downloaded from\. + +*Type:* +string matching the pattern https?://\.+ + +*Example:* + +```nix +"https://example.com/antifilter.srs" +``` + ## services\.proxy-suite\.proxy\.routing\.rules @@ -1395,6 +1584,28 @@ string "vps-de" ``` + +## services\.proxy-suite\.proxy\.routing\.rules\.\*\.ruleSets + +Names from proxy\.routing\.ruleSets to match (sing-box and hybrid backends)\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "antifilter" +] +``` + ## services\.proxy-suite\.proxy\.selection @@ -1638,6 +1849,30 @@ signed integer 1 ``` + +## services\.proxy-suite\.proxy\.tproxy\.lanInterfaces + +Interfaces whose forwarded TCP and UDP is taken through the proxy too: devices on them +that use this host as their gateway\. Turns on IP forwarding for the rest (ping, the LAN +itself), which is routed as it is\. Needs the nftables firewall on NixOS\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "br0" +] +``` + ## services\.proxy-suite\.proxy\.tproxy\.localSubnets diff --git a/docs/options/zapret.md b/docs/options/zapret.md index 4fe13fb..95165e7 100644 --- a/docs/options/zapret.md +++ b/docs/options/zapret.md @@ -718,7 +718,8 @@ attribute set of string Some lines let TLS to certain hosting networks handshake and then cut it at 12-34 KB, which no strategy fixes\. z2k’s probe checks this line against ~110 known targets when its network changes and once a day, and for each cut-off network searches a whitelisted -name that nfqws2 then puts into a fake ClientHello: thousands of short TLS connections to +name that nfqws2 then puts into a fake ClientHello (strategySource “z2k” only; ahead of +the nfqws2-keenetic strategies it breaks them): thousands of short TLS connections to foreign hosting IPs per full run, sent directly and never touched by zapret2\. State and maps live in /var/lib/proxy-suite/zapret2/cutoff; ` proxy-ctl zapret cutoff ` shows them\. diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index d7ce2d3..b206f8a 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -11,6 +11,8 @@ let profiles = awgCfg.profiles; profileNames = builtins.attrNames profiles; globalProfileNames = builtins.attrNames derived.awgGlobalProfiles; + inherit (derived.constants) awgGlobalFwmark awgGlobalGroup; + killSwitchUnit = "proxy-suite-killswitch.service"; # Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick. tunnelOutbounds = derived.awgTunnelOutbounds; interfaceProfiles = lib.filterAttrs ( @@ -135,17 +137,31 @@ let ) " -I ${lib.escapeShellArg profile.interfaceName}"; # An outbound interface keeps the host's routes and resolver, and marks its packets so TUN and - # TProxy let them past. + # TProxy let them past. A global one under the kill switch marks them with a mark it knows. prepareCommand = profile: output: '' ${pkgs.python3}/bin/python3 ${configTool} \ --manifest ${lib.escapeShellArg (toString (manifestFor profile))} \ --output ${output}${ - lib.optionalString ( - profile.asOutbound == "interface" - ) " --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}" + if profile.asOutbound == "interface" then + " --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}" + else + lib.optionalString (derived.killSwitchEnabled && profile.asOutbound == null) " --fwmark ${toString awgGlobalFwmark} --resolve-endpoints" } ''; + # Under the kill switch, glibc would hand the Endpoint lookup to nscd or systemd-resolved, + # whose own queries the kill switch rejects. With both out of the way it asks resolved's + # upstreams itself, under the unit's group, and awg-quick gets the Endpoint as an address. + ownLookups = pkgs.writeShellScript "proxy-suite-awg" '' + mount=${pkgs.util-linux}/bin/mount + # Best effort: at worst the lookup goes the usual way. + if [ -S /run/nscd/socket ]; then $mount --bind /dev/null /run/nscd/socket || true; fi + if [ -s /run/systemd/resolve/resolv.conf ]; then + $mount --bind /run/systemd/resolve/resolv.conf /etc/resolv.conf || true + fi + exec "$@" + ''; + mkService = name: profile: let @@ -153,7 +169,7 @@ let configPath = runtimeConfig name profile; prepare = pkgs.writeShellScript "proxy-suite-awg" '' set -euo pipefail - ${prepareCommand profile (lib.escapeShellArg configPath)} + ${lib.optionalString (derived.killSwitchEnabled && !outbound) "${pkgs.util-linux}/bin/unshare --mount ${ownLookups} "}${prepareCommand profile (lib.escapeShellArg configPath)} ''; proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" '' set -euo pipefail @@ -247,7 +263,11 @@ let "proxy-suite-zapret.service" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; - wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; + wants = [ + "network-online.target" + ] + ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service" + ++ lib.optional derived.killSwitchEnabled killSwitchUnit; wantedBy = lib.optionals profile.autostart [ "multi-user.target" ]; conflicts = allProfileConflicts name ++ [ "proxy-suite-tun.service" @@ -291,6 +311,11 @@ let // lib.optionalAttrs (cfg.proxy.enable && !outbound) { ExecStopPost = proxyBypassDown; } + # The Endpoint lookup (ownLookups) gets past the kill switch by this group, so a + # profile that dropped can come back while the kill switch holds. + // lib.optionalAttrs (derived.killSwitchEnabled && !outbound) { + Group = awgGlobalGroup; + } # A failed handshake leaves no routes behind here, so try again later. // lib.optionalAttrs outbound { Restart = "on-failure"; @@ -451,6 +476,10 @@ in ] ++ lib.optional (builtins.any (ob: ob.kind == "userspace") tunnelOutbounds) awgCfg.wireproxyPackage; + services.proxy-suite.internal.groups = lib.optional ( + derived.killSwitchEnabled && globalProfileNames != [ ] + ) awgGlobalGroup; + services.proxy-suite.internal.kernelModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [ diff --git a/modules/proxy-suite/assembly.nix b/modules/proxy-suite/assembly.nix index a5b292d..06f8865 100644 --- a/modules/proxy-suite/assembly.nix +++ b/modules/proxy-suite/assembly.nix @@ -46,6 +46,7 @@ let perAppTproxyRulesFile perAppZapretRulesFile nftablesRulesFile + killSwitchRulesFile ip nft ; diff --git a/modules/proxy-suite/config-templates/proxy-inbounds.nix b/modules/proxy-suite/config-templates/proxy-inbounds.nix index 1f5c434..873d8c2 100644 --- a/modules/proxy-suite/config-templates/proxy-inbounds.nix +++ b/modules/proxy-suite/config-templates/proxy-inbounds.nix @@ -38,14 +38,24 @@ in (mkDnsServer "local" proxyCfg.dns.local) ]; - inbounds = [ ]; - # Counters per user, inbound and outbound for proxy-suite-inbound-stats, and who is - # connected right now, on loopback only. + # connected right now, from where. A socket rather than loopback, which any local + # user could ask: the start script's setgid directory gives it the group that may + # read the stats. The listeners are appended at start. + inbounds = [ + { + tag = "api-in"; + protocol = "dokodemo-door"; + listen = "${derived.constants.inboundStatsApiSocket},0660"; + settings = { + address = "127.0.0.1"; + network = "unix"; + }; + } + ]; stats = { }; api = { tag = "api"; - listen = "127.0.0.1:${toString derived.constants.inboundStatsApiPort}"; services = [ "StatsService" ]; }; policy = { @@ -95,6 +105,13 @@ in # IPIfNonMatch the network-only final rule matches names unresolved. domainStrategy = if proxyInboundsResolveInSingBox then "AsIs" else "IPOnDemand"; domainMatcher = "hybrid"; - rules = inboundRules.xrayInboundRules; + rules = [ + { + ruleTag = "inbound-stats-api"; + inboundTag = [ "api-in" ]; + outboundTag = "api"; + } + ] + ++ inboundRules.xrayInboundRules; }; } diff --git a/modules/proxy-suite/config-templates/sing-box.nix b/modules/proxy-suite/config-templates/sing-box.nix index f08e504..839abd0 100644 --- a/modules/proxy-suite/config-templates/sing-box.nix +++ b/modules/proxy-suite/config-templates/sing-box.nix @@ -219,7 +219,7 @@ let route = { default_domain_resolver = "local"; - rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets; + rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets ++ rules.remoteRuleSets; rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules; final = if (proxyCfg.routing.default == "proxy") then "proxy" else "direct"; } diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 57003c9..9026e50 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -58,6 +58,7 @@ let transport tls reality + hysteria xrayJson jsonFile ; diff --git a/modules/proxy-suite/core.nix b/modules/proxy-suite/core.nix index 0ed44e6..78dae66 100644 --- a/modules/proxy-suite/core.nix +++ b/modules/proxy-suite/core.nix @@ -138,6 +138,17 @@ in } )) + (lib.mkIf derived.ruleSetsEnabled ( + import ./rulesets.nix { + inherit + lib + pkgs + cfg + derived + ; + } + )) + (lib.mkIf (derived.proxyInboundsEnabled && derived.proxyInboundsAwg != [ ]) ( import ./amnezia-wg-inbounds.nix { inherit diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index c43133a..f6892fc 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -23,6 +23,43 @@ let perAppRoutingCfg = cfg.perAppRouting; globalTun = proxyCfg.tun; globalTproxy = proxyCfg.tproxy; + # Forwarding for what gateway clients send that TProxy does not take (ping, the LAN itself). + tproxyLanSysctl = + lib.optionalAttrs (proxyEnabled && globalTproxy.enable && globalTproxy.lanInterfaces != [ ]) + ( + { + "net.ipv4.ip_forward" = 1; + } + // lib.optionalAttrs proxyCfg.ipv6 { + "net.ipv6.conf.all.forwarding" = 1; + } + ); + # proxy.routing.ruleSets, with the format settled and the file sing-box reads. + ruleSets = lib.mapAttrsToList ( + name: rs: + let + format = + if rs.format != null then + rs.format + else if lib.hasSuffix ".srs" (lib.head (lib.splitString "?" rs.url)) then + "binary" + else + "source"; + in + rs + // { + inherit name format; + path = "${constants.ruleSetsDir}/${name}.${if format == "binary" then "srs" else "json"}"; + # Its domain rules only, for DNS rules: sing-box 1.14 refuses an IP-only rule set there, + # and a legacy address filter would send every other name to that rule's server first. + dnsPath = "${constants.ruleSetsDir}/${name}.dns.json"; + } + ) proxyCfg.routing.ruleSets; + ruleSetsEnabled = proxyEnabled && ruleSets != [ ]; + # Some global tunnel for it to guard. + killSwitchEnabled = + cfg.killSwitch.enable + && (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalProfiles != { }); perAppRoutingTun = cfg.perAppRouting.tun; perAppRoutingTproxy = cfg.perAppRouting.tproxy; zapretCfg = cfg.zapret; @@ -188,6 +225,7 @@ let proxyInboundUdpTypes = [ "amneziawg" + "hysteria2" "shadowsocks" "socks" ]; @@ -203,13 +241,16 @@ let ] ) ) proxyInbounds; - # h3-only xhttp listeners are UDP-only, leaving the TCP port to a web server. - proxyInboundIsH3Only = - l: l.type != null && l.transport.type == "xhttp" && l.tls.enable && l.tls.alpn == [ "h3" ]; + # QUIC listeners are UDP-only: hysteria2, and h3-only xhttp, which leaves the TCP port to a + # web server. + proxyInboundIsUdpOnly = + l: + l.type == "hysteria2" + || l.type != null && l.transport.type == "xhttp" && l.tls.enable && l.tls.alpn == [ "h3" ]; # What an onion service can carry: TCP to a listener with a known protocol. proxyInboundOnionCapable = ib: - ib.listener.type != null && ib.listener.type != "amneziawg" && !proxyInboundIsH3Only ib.listener; + ib.listener.type != null && ib.listener.type != "amneziawg" && !proxyInboundIsUdpOnly ib.listener; torOnionEnabled = torCfg.enable && torCfg.onionService.enable && proxyInboundsEnabled; torOnionInbounds = if !torOnionEnabled then @@ -221,7 +262,7 @@ let proxyInboundFirewallPorts = lib.unique ( map (ib: ib.listener.port) ( builtins.filter ( - ib: !proxyInboundIsH3Only ib.listener && ib.listener.type != "amneziawg" + ib: !proxyInboundIsUdpOnly ib.listener && ib.listener.type != "amneziawg" ) proxyInboundsPublic ) ); @@ -232,7 +273,7 @@ let ib: ib.listener.type == null || builtins.elem ib.listener.type proxyInboundUdpTypes - || proxyInboundIsH3Only ib.listener + || proxyInboundIsUdpOnly ib.listener ) proxyInboundsPublic ) ); @@ -357,14 +398,21 @@ let # Written by every backend start script; proxy-ctl reads the socks copy. outboundInventoryFile = "${runtimeDir}/proxy-suite-socks/outbounds.json"; - inboundStatsApiPort = 18536; + inboundStatsApiSocket = "${runtimeDir}/proxy-suite-inbounds/api/stats.sock"; # Mark and table sending the AmneziaWG listeners' diverted packets to the local stack, # clear of proxy.tproxy's and perAppRouting's (asserted). awgInboundFwmark = 20; awgInboundRouteTable = 103; awgInboundRulePriority = 8990; + # A global AmneziaWG profile's own packets carry this mark (awg-quick's default table, + # pinned so the kill switch knows it), and its unit runs with this group, whose lookups + # (an Endpoint's name) get past the kill switch. + awgGlobalFwmark = 51820; + awgGlobalGroup = "proxy-suite-awg"; # sing-box's fake IP caches, one per TUN config; the start script hands it to the backend. fakeIpCacheDir = "${stateDir}/fakeip"; + # Downloaded proxy.routing.ruleSets, one file each, written by the service user. + ruleSetsDir = "${stateDir}/rulesets"; # Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches. outboundTestPort = 18537; inboundStatsFile = "${stateDir}/inbound-stats.json"; @@ -436,6 +484,10 @@ in perAppRoutingCfg globalTun globalTproxy + tproxyLanSysctl + killSwitchEnabled + ruleSets + ruleSetsEnabled perAppRoutingTun perAppRoutingTproxy zapretCfg diff --git a/modules/proxy-suite/hosts/nixos.nix b/modules/proxy-suite/hosts/nixos.nix index 76c96ce..19ba437 100644 --- a/modules/proxy-suite/hosts/nixos.nix +++ b/modules/proxy-suite/hosts/nixos.nix @@ -49,11 +49,22 @@ in allowedTCPPorts = forward internal.firewall.allowedTCPPorts; allowedUDPPorts = forward internal.firewall.allowedUDPPorts; extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules; + extraInputRules = forward internal.firewall.extraInputRules; trustedInterfaces = forward internal.firewall.trustedInterfaces; }; boot.extraModulePackages = forward internal.kernelModulePackages; boot.kernel.sysctl = lib.mapAttrs (_: lib.mkDefault) cfg.internal.sysctl; + + assertions = [ + { + assertion = + cfg.internal.firewall.extraInputRules == "" + || !config.networking.firewall.enable + || config.networking.nftables.enable; + message = "proxy-suite: proxy.tproxy.lanInterfaces needs the nftables firewall (networking.nftables.enable); the iptables one drops the gateway clients' diverted traffic"; + } + ]; } ] )) diff --git a/modules/proxy-suite/inbound-stats-add.jq b/modules/proxy-suite/inbound-stats-add.jq index b188405..2b74e0d 100644 --- a/modules/proxy-suite/inbound-stats-add.jq +++ b/modules/proxy-suite/inbound-stats-add.jq @@ -14,7 +14,8 @@ # interface). The newest handshake counts as seen, and .awgPeers keeps each user's latest. reduce ($q.stat // [])[] as $s (.; ($s.name | split(">>>")) as $n - | if ($n | length) == 4 and ($n[0] | IN("user", "inbound", "outbound")) and $n[2] == "traffic" then + | if ($n | length) == 4 and ($n[0] | IN("user", "inbound", "outbound")) and $n[2] == "traffic" + and ([$n[0], $n[1]] | IN(["inbound", "api-in"], ["outbound", "api"]) | not) then .days[$day][$n[0]][$n[1]][if $n[3] == "uplink" then "up" else "down" end] += (($s.value // 0) | tonumber) else . end) | reduce ($online.users // [])[] as $u (.; diff --git a/modules/proxy-suite/nftables.nix b/modules/proxy-suite/nftables.nix index d387a54..d333587 100644 --- a/modules/proxy-suite/nftables.nix +++ b/modules/proxy-suite/nftables.nix @@ -6,7 +6,8 @@ }: let - inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser; + inherit (import ./derived.nix { inherit lib cfg; }) constants awgGlobalProfiles; + inherit (constants) serviceUser; proxyCfg = cfg.proxy; globalTproxy = proxyCfg.tproxy; perAppTun = cfg.perAppRouting.tun; @@ -67,6 +68,12 @@ let ''; tproxyLocalSubnetLines = mkLocalSubnetLines globalTproxy.localSubnets; + + lanInterfaceSet = "{ ${lib.concatMapStringsSep ", " (i: ''"${i}"'') globalTproxy.lanInterfaces} }"; + # Devices using this host as their gateway, past the destinations nobody diverts. + tproxyLanLines = lib.optionalString (globalTproxy.lanInterfaces != [ ]) ( + mkTproxyLines "iifname ${lanInterfaceSet} " " meta mark set ${toString globalTproxy.fwmark}" + ); perAppTproxyLocalSubnetLines = mkLocalSubnetLines perAppTproxy.localSubnets; # Without ipv6, IPv6 packets are left alone, as if the table were still `ip`. @@ -89,11 +96,12 @@ let # are served here, not taken by the tproxy socket. A resolver this host # runs for the LAN is one of them. fib daddr type local return + ${tproxyLocalSubnetLines} + ${tproxyLanLines} # Packets re-entering via loopback after output marking should not # be skipped just because the host has an RFC1918 source address. iifname != "lo" ip saddr $RESERVED_IP return iifname != "lo" ip6 saddr $RESERVED_IP6 return - ${tproxyLocalSubnetLines} ${mkTproxyLines "" " meta mark set ${toString globalTproxy.fwmark}"} } chain output { @@ -140,6 +148,67 @@ let } ''; + # Everything proxy-suite sends itself, or has already taken into the proxy, gets past; the + # rest is what TUN, TProxy or a global AmneziaWG profile would have taken, had it been up. + sshProxyUser = cfg.sshProxy.serviceUser; + killSwitchMarks = [ + globalTproxy.fwmark + globalTproxy.proxyMark + ] + ++ lib.optional perAppTun.enable perAppTun.fwmark + ++ lib.optional perAppTproxy.enable perAppTproxy.fwmark + ++ lib.optional tgWsProxyBypassEnabled tgWsProxyCfg.fwmark + ++ lib.optional (awgGlobalProfiles != { }) constants.awgGlobalFwmark; + awgGlobalInterfaces = lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles; + globalTunEnabled = proxyCfg.enable && proxyCfg.tun.enable; + killSwitchAllowLines = '' + ip daddr $RESERVED_IP accept + ip6 daddr $RESERVED_IP6 accept + ${lib.concatMapStrings (cidr: '' + ${ipFamily cidr} daddr ${cidr} accept + '') globalTproxy.localSubnets} + ct direction reply accept + ''; + killSwitchRulesFile = pkgs.writeText "proxy-suite-routing" '' + ${reservedIpBlock} + table inet proxy_suite_killswitch { + chain output { + type filter hook output priority filter; policy accept; + oifname "lo" accept + meta skuid "${serviceUser}" accept + ${lib.optionalString globalTunEnabled '' + oifname "${proxyCfg.tun.interface}" accept + # sing-box's auto_redirect hands DNS to the TUN by rewriting it to the TUN's peer, + # while the route still points at the uplink. + ip daddr ${proxyCfg.tun.address} accept + ${lib.optionalString proxyCfg.ipv6 "ip6 daddr ${constants.globalTunIPv6Address} accept"} + ''} + ${lib.optionalString (awgGlobalProfiles != { }) '' + oifname { ${lib.concatMapStringsSep ", " (i: ''"${i}"'') awgGlobalInterfaces} } accept + meta skgid "${constants.awgGlobalGroup}" accept + ''} + ${lib.optionalString ( + cfg.sshProxy.enable && sshProxyUser != null && sshProxyUser != serviceUser + ) ''meta skuid "${sshProxyUser}" accept''} + meta mark { ${lib.concatMapStringsSep ", " toString (lib.unique killSwitchMarks)} } accept + # A lookup the proxy did not take would name every site to the LAN resolver. + meta l4proto { tcp, udp } th dport 53 reject with icmpx admin-prohibited + ${killSwitchAllowLines} + # DHCP keeps the uplink, NTP the clock that TLS depends on. + udp dport { 67, 68, 123 } accept + reject with icmpx admin-prohibited + } + ${lib.optionalString (globalTproxy.lanInterfaces != [ ]) '' + # Gateway clients: what TProxy does not divert is forwarded, to the LAN only. + chain forward { + type filter hook forward priority filter; policy accept; + ${killSwitchAllowLines} + iifname ${lanInterfaceSet} reject with icmpx admin-prohibited + } + ''} + } + ''; + perAppZapretRulesFile = pkgs.writeText "proxy-suite-routing" '' table inet proxy_suite_per_app_zapret_mark { chain prerouting { @@ -192,6 +261,7 @@ in inherit reservedIpBlock nftablesRulesFile + killSwitchRulesFile perAppTproxyRulesFile perAppZapretRulesFile perAppTunChainFile diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index ccca645..405a6ea 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -21,6 +21,7 @@ ./gui.nix ./tui.nix ./user-control.nix + ./kill-switch.nix ./host.nix ]; diff --git a/modules/proxy-suite/options/host.nix b/modules/proxy-suite/options/host.nix index 201c664..b6ba41f 100644 --- a/modules/proxy-suite/options/host.nix +++ b/modules/proxy-suite/options/host.nix @@ -68,6 +68,8 @@ in allowedTCPPorts = internalOption (types.listOf types.port) [ ]; allowedUDPPorts = internalOption (types.listOf types.port) [ ]; extraReversePathFilterRules = internalOption types.lines ""; + # nftables firewall only: iptables has no such hook. + extraInputRules = internalOption types.lines ""; trustedInterfaces = internalOption (types.listOf types.str) [ ]; }; # Kernel parameters the services also set when they start. diff --git a/modules/proxy-suite/options/kill-switch.nix b/modules/proxy-suite/options/kill-switch.nix new file mode 100644 index 0000000..76e6801 --- /dev/null +++ b/modules/proxy-suite/options/kill-switch.nix @@ -0,0 +1,11 @@ +{ lib, ... }: +{ + options.services.proxy-suite.killSwitch.enable = lib.mkEnableOption '' + a kill switch for the global tunnels (proxy.tun, proxy.tproxy and global AmneziaWG profiles): + once one starts, outgoing traffic that would leave outside it is rejected, also while it + restarts, after it crashes or after its handshake gives up. LAN destinations, DHCP and NTP + stay open; tproxy.lanInterfaces clients keep the LAN but lose the internet. Only + `proxy-ctl killswitch off`, `proxy off`, `proxy tun off`, `proxy tproxy off` or `awg off` + lift it (proxy-suite-killswitch) + ''; +} diff --git a/modules/proxy-suite/options/proxy-routing.nix b/modules/proxy-suite/options/proxy-routing.nix index 392afa1..72282d6 100644 --- a/modules/proxy-suite/options/proxy-routing.nix +++ b/modules/proxy-suite/options/proxy-routing.nix @@ -28,6 +28,7 @@ in ips = list "IP CIDRs sent through the proxy." [ "1.1.1.0/24" ]; geosites = list "Geosite names sent through the proxy." [ "netflix" ]; geoips = list "Geoip names sent through the proxy." [ "us" ]; + ruleSets = list "Names from ruleSets sent through the proxy." [ "antifilter" ]; }; direct = { @@ -39,6 +40,7 @@ in ips = list "IP CIDRs sent direct." [ "10.10.0.0/16" ]; geosites = list "Geosite names sent direct." [ "category-ru" ]; geoips = list "Geoip names sent direct." [ "ru" ]; + ruleSets = list "Names from ruleSets sent direct." [ "ru-services" ]; }; block = { @@ -46,6 +48,7 @@ in ips = list "IP CIDRs blocked." [ "203.0.113.0/24" ]; geosites = list "Geosite names blocked." [ "category-ads-all" ]; geoips = list "Geoip names blocked." [ "cn" ]; + ruleSets = list "Names from ruleSets blocked." [ "ads" ]; }; rules = mkOption { @@ -63,5 +66,54 @@ in } ]; }; + + ruleSets = mkOption { + type = types.attrsOf ( + types.submodule { + options = { + url = mkOption { + type = types.strMatching "https?://.+"; + description = "Where the sing-box rule set is downloaded from."; + example = "https://example.com/antifilter.srs"; + }; + format = mkOption { + type = types.nullOr ( + types.enum [ + "binary" + "source" + ] + ); + default = null; + description = ''"binary" (.srs) or "source" (JSON). Null goes by the URL: .srs is binary.''; + }; + detour = mkOption { + type = types.enum [ + "proxy" + "direct" + ]; + default = "proxy"; + description = "Downloaded through the local proxy, or directly."; + }; + }; + } + ); + default = { }; + description = '' + sing-box rule sets kept up to date at runtime, for the ruleSets of proxy, direct, block, + rules and an outbound's routing. They are fetched every ruleSetUpdateInterval and on + `proxy-ctl proxy rulesets update`, and sing-box picks up a new file without a restart; + until the first fetch one matches nothing. Not for backend = "xray". + ''; + example = { + antifilter.url = "https://example.com/antifilter.srs"; + }; + }; + + ruleSetUpdateInterval = mkOption { + type = types.str; + default = "1d"; + description = "How often ruleSets are downloaded again (systemd time span)."; + example = "6h"; + }; }; } diff --git a/modules/proxy-suite/options/proxy-tproxy.nix b/modules/proxy-suite/options/proxy-tproxy.nix index 68b1370..2b4592c 100644 --- a/modules/proxy-suite/options/proxy-tproxy.nix +++ b/modules/proxy-suite/options/proxy-tproxy.nix @@ -41,5 +41,16 @@ in "fd00::/8" ]; }; + + lanInterfaces = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + Interfaces whose forwarded TCP and UDP is taken through the proxy too: devices on them + that use this host as their gateway. Turns on IP forwarding for the rest (ping, the LAN + itself), which is routed as it is. Needs the nftables firewall on NixOS. + ''; + example = [ "br0" ]; + }; }; } diff --git a/modules/proxy-suite/options/types.nix b/modules/proxy-suite/options/types.nix index 4936582..c05805a 100644 --- a/modules/proxy-suite/options/types.nix +++ b/modules/proxy-suite/options/types.nix @@ -10,6 +10,12 @@ let geosites = list "Geosite names to match (see geodata)." [ "netflix" ]; geoips = list "Geoip names to match (see geodata; the defaults are country codes only)." [ "us" ]; }; + # The client's routing also matches downloaded rule sets, which XRay cannot read. + clientRoutingFields = routingFields // { + ruleSets = list "Names from proxy.routing.ruleSets to match (sing-box and hybrid backends)." [ + "antifilter" + ]; + }; routingRuleType = types.submodule { options = { @@ -19,7 +25,7 @@ let example = "vps-de"; }; } - // routingFields; + // clientRoutingFields; }; dnsUpstreamType = types.submodule { @@ -78,10 +84,14 @@ in dnsUpstreamType perAppRoutingProfileType routingFields + clientRoutingFields routingRuleType ; } -// import ./types/outbounds.nix { inherit lib routingFields; } +// import ./types/outbounds.nix { + inherit lib; + routingFields = clientRoutingFields; +} // import ./types/zapret.nix { inherit lib; } // import ./types/inbounds.nix { inherit lib; } // import ./types/amnezia-wg.nix { inherit lib; } diff --git a/modules/proxy-suite/options/types/inbounds.nix b/modules/proxy-suite/options/types/inbounds.nix index f4c778c..bd92e80 100644 --- a/modules/proxy-suite/options/types/inbounds.nix +++ b/modules/proxy-suite/options/types/inbounds.nix @@ -254,6 +254,7 @@ let "vless" "vmess" "trojan" + "hysteria2" "shadowsocks" "socks" "http" @@ -264,7 +265,8 @@ let description = '' Protocol. Set exactly one of type, xrayJson, or jsonFile. "amneziawg" is an AmneziaWG server on UDP port, with its own interface (see amneziaWg); its traffic is handed to XRay - and leaves like any other listener's. + and leaves like any other listener's. "hysteria2" is QUIC on UDP port: it needs tls (a + certificate) and takes passwords, and no transport, reality or flow. ''; example = "vless"; }; @@ -345,6 +347,11 @@ let jsonFile = nullStr "Runtime path to a raw XRay inbound (no share link); tag is overridden and port, if left out, filled in." "/run/secrets/proxy-inbound-vless.json"; + hysteria.masquerade = nullStr '' + Site that a hysteria2 listener serves, reverse-proxied, to anything that is not a client + (a browser, a prober). Null answers them with 404. + '' "https://www.example.com"; + amneziaWg = mkOption { type = mkAmneziaWgType name; default = { }; diff --git a/modules/proxy-suite/options/zapret2.nix b/modules/proxy-suite/options/zapret2.nix index 3666bc3..3f0f2f8 100644 --- a/modules/proxy-suite/options/zapret2.nix +++ b/modules/proxy-suite/options/zapret2.nix @@ -125,7 +125,8 @@ in Some lines let TLS to certain hosting networks handshake and then cut it at 12-34 KB, which no strategy fixes. z2k's probe checks this line against ~110 known targets when its network changes and once a day, and for each cut-off network searches a whitelisted - name that nfqws2 then puts into a fake ClientHello: thousands of short TLS connections to + name that nfqws2 then puts into a fake ClientHello (strategySource "z2k" only; ahead of + the nfqws2-keenetic strategies it breaks them): thousands of short TLS connections to foreign hosting IPs per full run, sent directly and never touched by zapret2. State and maps live in /var/lib/proxy-suite/zapret2/cutoff; `proxy-ctl zapret cutoff` shows them. ''; diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index 27fa628..f63f1c5 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -47,7 +47,8 @@ let ob: let ro = ob.routing; - hasAny = ro.domains != [ ] || ro.ips != [ ] || ro.geosites != [ ] || ro.geoips != [ ]; + hasAny = + ro.domains != [ ] || ro.ips != [ ] || ro.geosites != [ ] || ro.geoips != [ ] || ro.ruleSets != [ ]; in lib.optional hasAny { outbound = resolveTag ob.tag; @@ -56,6 +57,7 @@ let ips geosites geoips + ruleSets ; } ) proxyCfg.outbounds; @@ -78,10 +80,12 @@ let onionOutbound ; inherit (cfg) geodata; + inherit (derived) ruleSets; }; inherit (singBoxRules) geositeRuleSets geoIPRuleSets + remoteRuleSets singBoxRoutingRules singBoxRouteModeRules singBoxDnsRules @@ -111,6 +115,7 @@ in zapretDirectRules geositeRuleSets geoIPRuleSets + remoteRuleSets singBoxRoutingRules singBoxRouteModeRules singBoxDnsRules diff --git a/modules/proxy-suite/rules/sing-box.nix b/modules/proxy-suite/rules/sing-box.nix index d0c4c9b..48a4b27 100644 --- a/modules/proxy-suite/rules/sing-box.nix +++ b/modules/proxy-suite/rules/sing-box.nix @@ -8,6 +8,7 @@ customRuleCategory, onionOutbound, geodata, + ruleSets, }: let @@ -28,6 +29,7 @@ let (mkIPRule rule.outbound rule.ips) (mkRulesetRule rule.outbound (map (s: "geosite-${s}") rule.geosites)) (mkRulesetRule rule.outbound (map (s: "geoip-${s}") rule.geoips)) + (mkRulesetRule rule.outbound (map remoteTag rule.ruleSets)) ]; allGeositeNames = lib.unique ( @@ -51,6 +53,24 @@ let geositeRuleSets = map (mkRuleSet "geosite" geodata.singBox.geosite) allGeositeNames; geoIPRuleSets = map (mkRuleSet "geoip" geodata.singBox.geoip) allGeoIPNames; + # Downloaded at runtime; sing-box reloads a local rule set when its file changes. + # DNS rules read each one's domain-only copy (see derived.ruleSets). + remoteTag = name: "ruleset-${name}"; + remoteDnsTag = name: "ruleset-${name}-dns"; + remoteRuleSets = lib.concatMap (rs: [ + { + tag = remoteTag rs.name; + type = "local"; + inherit (rs) format path; + } + { + tag = remoteDnsTag rs.name; + type = "local"; + format = "source"; + path = rs.dnsPath; + } + ]) ruleSets; + commonRules = [ { network = [ @@ -82,6 +102,7 @@ let (mkIPRule "direct" direct.ips) (mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites)) (mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips)) + (mkRulesetRule "direct" (map remoteTag r.direct.ruleSets)) ]; tgWsProxyRelayDirectRules = @@ -105,11 +126,13 @@ let (mkIPRule "block" r.block.ips) (mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites)) (mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips)) + (mkRulesetRule "block" (map remoteTag r.block.ruleSets)) ]; proxyGeoRules = lib.flatten [ (mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites)) (mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips)) + (mkRulesetRule "proxy" (map remoteTag r.proxy.ruleSets)) ]; singBoxRoutingRules = @@ -125,13 +148,16 @@ let # the ISP's resolver never sees it and cannot spoof the answer; a direct one is looked up # locally. In the routing's order; block entries resolve however the final says. mkDnsRules = - server: domains: geosites: + server: domains: geosites: names: + let + tags = map (s: "geosite-${s}") geosites ++ map remoteDnsTag names; + in lib.optional (domains != [ ]) { domain_suffix = domains; inherit server; } - ++ lib.optional (geosites != [ ]) { - rule_set = map (s: "geosite-${s}") geosites; + ++ lib.optional (tags != [ ]) { + rule_set = tags; inherit server; }; dnsServerFor = category: if category == "direct" then "local" else "remote"; @@ -139,12 +165,14 @@ let lib.concatMap ( rule: lib.optionals (customRuleCategory rule.outbound != "block") ( - mkDnsRules (dnsServerFor (customRuleCategory rule.outbound)) rule.domains rule.geosites + mkDnsRules (dnsServerFor (customRuleCategory rule.outbound)) rule.domains rule.geosites ( + rule.ruleSets or [ ] + ) ) ) customRules - ++ mkDnsRules "remote" r.proxy.domains [ ] - ++ mkDnsRules "local" direct.domains direct.geosites - ++ mkDnsRules "remote" [ ] r.proxy.geosites; + ++ mkDnsRules "remote" r.proxy.domains [ ] [ ] + ++ mkDnsRules "local" direct.domains direct.geosites r.direct.ruleSets + ++ mkDnsRules "remote" [ ] r.proxy.geosites r.proxy.ruleSets; singBoxRouteModeRules = { common = commonRules; @@ -160,6 +188,7 @@ in inherit geositeRuleSets geoIPRuleSets + remoteRuleSets singBoxRoutingRules singBoxRouteModeRules singBoxDnsRules diff --git a/modules/proxy-suite/rulesets.nix b/modules/proxy-suite/rulesets.nix new file mode 100644 index 0000000..5f75741 --- /dev/null +++ b/modules/proxy-suite/rulesets.nix @@ -0,0 +1,137 @@ +# proxy.routing.ruleSets: downloaded by the service user into the state directory, where +# sing-box reads them as local rule sets and reloads each one when its file changes. +{ + lib, + pkgs, + cfg, + derived, +}: + +let + inherit (derived) ruleSets localProxy; + inherit (derived.constants) ruleSetsDir unprivilegedServiceConfig serviceUser; + inherit (cfg.host) privileged; + singBox = "${cfg.proxy.singBox.package}/bin/sing-box"; + curl = "${pkgs.curl}/bin/curl"; + + inherit (localProxy) auth; + passwordSource = + if auth.passwordFile != null then + auth.passwordFile + else if auth.password != null then + pkgs.writeText "proxy-suite-rulesets" auth.password + else + null; + withProxyAuth = lib.any (rs: rs.detour == "proxy") ruleSets && localProxy.authEnabled; + + # What sing-box reads until the first download: a rule set that matches nothing. + emptySource = pkgs.writeText "proxy-suite-rulesets.json" ( + builtins.toJSON { + version = 3; + rules = [ ]; + } + ); + emptyBinary = pkgs.runCommand "proxy-suite-rulesets.srs" { } '' + ${singBox} rule-set compile --output "$out" ${emptySource} + ''; + + fetchScript = pkgs.writeShellScript "proxy-suite-rulesets" '' + set -uo pipefail + proxy=(--proxy socks5h://${localProxy.hostPart}:${toString cfg.proxy.listener.port}) + ${lib.optionalString withProxyAuth '' + proxy+=(--proxy-user ${lib.escapeShellArg auth.username}:"$(< "$CREDENTIALS_DIRECTORY/proxy-password")") + ''} + failed=0 + + # A download replaces the file only once sing-box has read it back, so a bad one never + # reaches the backend; a failed one keeps what was there. Its domain rules go to the copy + # DNS rules read. + fetch() { + local name=$1 url=$2 path=$3 dns=$4 format=$5 detour=$6 tmp dnsTmp + local args=(--fail --silent --show-error --location --max-time 120 --max-filesize 64M) + [ "$detour" = proxy ] && args+=("''${proxy[@]}") + tmp=$(${pkgs.coreutils}/bin/mktemp "$path.XXXXXX") || { failed=1; return; } + dnsTmp=$(${pkgs.coreutils}/bin/mktemp "$dns.XXXXXX") || { rm -f "$tmp"; failed=1; return; } + if ${curl} "''${args[@]}" --output "$tmp" "$url" && valid "$tmp" "$format" && + domains "$tmp" "$format" > "$dnsTmp" && valid "$dnsTmp" source; then + chmod 0644 "$tmp" "$dnsTmp" + mv -f "$dnsTmp" "$dns" + mv -f "$tmp" "$path" + echo "rule set $name: updated" + else + rm -f "$tmp" "$dnsTmp" + echo "rule set $name: not updated from $url; keeping the one it has" >&2 + failed=1 + fi + } + valid() { + if [ "$2" = binary ]; then + ${singBox} rule-set decompile --output /dev/null "$1" 2>/dev/null + else + ${singBox} rule-set compile --output /dev/null "$1" 2>/dev/null + fi + } + domains() { + if [ "$2" = binary ]; then + ${singBox} rule-set decompile --output /dev/stdout "$1" + else + cat "$1" + fi | ${pkgs.jq}/bin/jq '.rules = [(.rules // [])[] + | select((.type // "default") == "default" + and (has("domain") or has("domain_suffix") or has("domain_keyword") or has("domain_regex"))) + | del(.ip_cidr, .ip_is_private)]' + } + + ${lib.concatMapStrings (rs: '' + fetch ${ + lib.escapeShellArgs [ + rs.name + rs.url + rs.path + rs.dnsPath + rs.format + rs.detour + ] + } + '') ruleSets} + exit "$failed" + ''; +in +{ + services.proxy-suite.internal = { + # sing-box refuses to start on a missing rule set: an empty one stands in until the first + # download, and is only copied where no file is yet. + tmpfiles = [ + "d ${ruleSetsDir} 0755 ${if privileged then "${serviceUser} ${serviceUser}" else "- -"} -" + ] + ++ lib.concatMap (rs: [ + "C ${rs.path} - - - - ${if rs.format == "binary" then emptyBinary else emptySource}" + "C ${rs.dnsPath} - - - - ${emptySource}" + ]) ruleSets; + + services.proxy-suite-rulesets = { + description = "proxy-suite - download routing rule sets"; + after = [ + "network-online.target" + "proxy-suite-socks.service" + ]; + wants = [ "network-online.target" ]; + serviceConfig = unprivilegedServiceConfig [ ] // { + Type = "oneshot"; + ExecStart = fetchScript; + StateDirectory = "proxy-suite/rulesets"; + StateDirectoryMode = "0755"; + LoadCredential = lib.optional withProxyAuth "proxy-password:${passwordSource}"; + }; + }; + + timers.proxy-suite-rulesets = { + description = "Periodic proxy-suite rule set download"; + wantedBy = [ "timers.target" ]; + timerConfig = { + OnActiveSec = "1m"; + OnUnitActiveSec = cfg.proxy.routing.ruleSetUpdateInterval; + }; + }; + }; +} diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index e015529..d92f1fd 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -68,10 +68,7 @@ let # the autoProxy prober's range must stay clear of. reservedLoopbackPorts = builtins.attrValues constants.xrayDnsBridgePorts - ++ [ - constants.inboundStatsApiPort - constants.outboundTestPort - ] + ++ [ constants.outboundTestPort ] ++ lib.optionals derived.warpOutboundEnabled [ derived.warpCfg.tunnelPort derived.warpCfg.directPort @@ -116,6 +113,7 @@ let rootlessAssertions = [ (rootlessForbids (proxyEnabled && globalTun.enable) "proxy.tun") (rootlessForbids (proxyEnabled && globalTproxy.enable) "proxy.tproxy") + (rootlessForbids cfg.killSwitch.enable "killSwitch") (rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTun.enable) "perAppRouting.tun") (rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTproxy.enable) "perAppRouting.tproxy") (rootlessForbids perAppZapretCfg.enable "perAppRouting.zapret") @@ -144,6 +142,18 @@ let "proxy-suite: ${item.name} = ${toString item.port} is a privileged port, which services on a ${hostKind} host cannot bind; pick one from 1024 up" ) rootlessPorts; + unknownRuleSets = lib.unique ( + builtins.filter (name: !proxyCfg.routing.ruleSets ? ${name}) ( + lib.concatMap (category: proxyCfg.routing.${category}.ruleSets) [ + "proxy" + "direct" + "block" + ] + ++ lib.concatMap (rule: rule.ruleSets) proxyCfg.routing.rules + ++ lib.concatMap (ob: ob.routing.ruleSets) proxyCfg.outbounds + ) + ); + featureAssertions = [ # Declaring no outbound at all is legal: they can be added at runtime with # `proxy-ctl proxy outbounds add`. Only a warning here; the backend still @@ -212,6 +222,12 @@ let (mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ]) "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}" ) + (mkAssertion (!proxyEnabled || unknownRuleSets == [ ]) + "proxy-suite: routing refers to rule set(s) proxy.routing.ruleSets does not declare: ${lib.concatStringsSep ", " unknownRuleSets}" + ) + (mkAssertion (!(pureXrayEnabled && proxyCfg.routing.ruleSets != { })) + "proxy-suite: proxy.routing.ruleSets are sing-box rule sets, which proxy.backend = \"xray\" cannot read; use \"sing-box\" or \"hybrid\"" + ) (mkAssertion ( !(pureXrayEnabled && proxyCfg.selection == "selector") ) "proxy-suite: proxy.selection = \"selector\" requires proxy.backend = \"sing-box\" or \"hybrid\"") @@ -244,6 +260,36 @@ let (requireEnabled (proxyCfg.autostart == "tproxy") globalTproxy.enable ''proxy-suite: proxy.autostart = "tproxy" requires proxy.tproxy.enable = true'' ) + (requireEnabled ( + globalTproxy.lanInterfaces != [ ] + ) globalTproxy.enable "proxy-suite: proxy.tproxy.lanInterfaces requires proxy.tproxy.enable = true") + (requireEnabled cfg.killSwitch.enable derived.killSwitchEnabled + "proxy-suite: killSwitch.enable needs a global tunnel to guard: proxy.tun, proxy.tproxy or a global amneziaWg profile" + ) + (mkAssertion + ( + !derived.killSwitchEnabled + || derived.awgGlobalProfiles == { } + || !builtins.elem constants.awgGlobalFwmark ( + [ + globalTproxy.fwmark + globalTproxy.proxyMark + globalTproxy.routeTable + constants.tunAutoRouteTableIndex + ] + ++ lib.optionals perAppRoutingTun.enable [ + perAppRoutingTun.fwmark + perAppRoutingTun.routeTable + ] + ++ lib.optionals perAppRoutingTproxy.enable [ + perAppRoutingTproxy.fwmark + perAppRoutingTproxy.routeTable + ] + ++ lib.optional tgWsProxyCfg.enable tgWsProxyCfg.fwmark + ) + ) + "proxy-suite: global AmneziaWG profiles mark and route with ${toString constants.awgGlobalFwmark}, which a proxy.tproxy, perAppRouting or tgWsProxy mark or table also uses" + ) ]; # Each case reads " requires = true", with option paths as labels. @@ -406,12 +452,11 @@ let ( !proxyInboundsEnabled || !lib.any (port: builtins.elem port derived.proxyInboundPorts) ( - [ derived.constants.inboundStatsApiPort ] - ++ map (listener: listener.internalPort) derived.proxyInboundsAwg + map (listener: listener.internalPort) derived.proxyInboundsAwg ++ builtins.attrValues derived.constants.xrayDnsBridgePorts ) ) - "proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the inbounds' stats API on ${toString derived.constants.inboundStatsApiPort}, the AmneziaWG listeners' loopback inbounds from 18700, or 18533-18535)" + "proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, or 18533-18535)" ) # The prober opens one loopback listener per exit from probeBasePort; the WARP # and AmneziaWG tunnels open two each from their own bases. They all bind @@ -441,11 +486,12 @@ let ]; needsPassword = builtins.elem l.type [ "trojan" + "hysteria2" "shadowsocks" "socks" "http" ]; - tlsTerminated = l.tls.enable || l.type == "trojan"; + tlsTerminated = l.tls.enable || l.type == "trojan" || l.type == "hysteria2"; multiUserShadowsocks = l.type == "shadowsocks" && builtins.length l.users > 1; eachUser = condition: fields: message: @@ -544,12 +590,24 @@ let (mkAssertion ( !proxyInboundsEnabled || l.flow == null || (l.type == "vless" && l.transport.type == "raw") ) "${prefix}: flow is only valid on a vless listener with transport.type = \"raw\"") + (mkAssertion + ( + !proxyInboundsEnabled + || l.tls.alpn == null + || !builtins.elem "h3" l.tls.alpn + || l.type == "hysteria2" + || (l.transport.type == "xhttp" && l.tls.enable && !l.reality.enable) + ) + "${prefix}: tls.alpn \"h3\" is served only by hysteria2, and by the xhttp transport with tls.enable (not REALITY)" + ) + # hysteria2 is its own QUIC transport, under a certificate of its own. + (mkAssertion + (!proxyInboundsEnabled || l.type != "hysteria2" || (!l.reality.enable && l.transport.type == "raw")) + "${prefix}: hysteria2 takes no reality or transport; it needs tls.certificateFile and tls.keyFile" + ) (mkAssertion ( - !proxyInboundsEnabled - || l.tls.alpn == null - || !builtins.elem "h3" l.tls.alpn - || (l.transport.type == "xhttp" && l.tls.enable && !l.reality.enable) - ) "${prefix}: tls.alpn \"h3\" is served only by the xhttp transport with tls.enable (not REALITY)") + !proxyInboundsEnabled || l.hysteria.masquerade == null || l.type == "hysteria2" + ) "${prefix}: hysteria.masquerade is for hysteria2 listeners only") ] ) proxyInbounds; @@ -891,10 +949,7 @@ let || (proxyInboundsEnabled && builtins.elem torCfg.socksPort derived.proxyInboundPorts) || builtins.elem torCfg.socksPort ( builtins.attrValues constants.xrayDnsBridgePorts - ++ [ - constants.inboundStatsApiPort - constants.outboundTestPort - ] + ++ [ constants.outboundTestPort ] ) ) ) diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index b35bc59..aeb546d 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -14,6 +14,7 @@ perAppTproxyRulesFile, perAppZapretRulesFile, nftablesRulesFile, + killSwitchRulesFile, ip, nft, }: @@ -96,6 +97,7 @@ let perAppTproxyRulesFile perAppZapretRulesFile nftablesRulesFile + killSwitchRulesFile ip nft ; diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 59bffa3..3937471 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -21,6 +21,8 @@ let proxyInboundsCfg proxyInboundsEnabled amneziaWgProfileNamesFile + ruleSets + pkgs ; inherit (ctx.scripts) subscriptionTagsFile @@ -54,6 +56,11 @@ in SELECTION = selectionMode; SUB_TAGS_FILE = toString subscriptionTagsFile; SUB_CACHE_DIR = subscriptionCacheDir; + RULE_SETS_FILE = toString ( + pkgs.writeText "proxy-suite-control" ( + builtins.toJSON (map (rs: { inherit (rs) name path; }) ruleSets) + ) + ); PER_APP_ROUTING_ENABLED = flag perAppRoutingCfg.enable; PER_APP_ROUTING_PROXYCHAINS_ENABLED = flag perAppRoutingCfg.proxychains.enable; PER_APP_ROUTING_TUN_ENABLED = flag perAppRoutingTun.enable; @@ -69,7 +76,7 @@ in INBOUNDS_LINKS_FILE = proxyInboundsLinksFile; INBOUNDS_STATS_FILE = constants.inboundStatsFile; INBOUNDS_XRAY = proxyInboundsXray; - INBOUNDS_API = "127.0.0.1:${toString constants.inboundStatsApiPort}"; + INBOUNDS_API = "unix://${constants.inboundStatsApiSocket}"; INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile; INBOUNDS_SUB_BASE_URL = if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl; diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index b3ab810..2dfcb2f 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -26,6 +26,7 @@ let pureXrayEnabled globalTun globalTproxy + tproxyLanSysctl perAppRoutingTun perAppRoutingTproxy userControlCfg @@ -98,10 +99,26 @@ lib.mkMerge [ ) true; # Inbound listeners are reached from outside, so their ports have to be open. - firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) { - allowedTCPPorts = proxyInboundFirewallPorts; - allowedUDPPorts = proxyInboundFirewallUdpPorts; - }; + firewall = lib.mkMerge [ + (lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) { + allowedTCPPorts = proxyInboundFirewallPorts; + allowedUDPPorts = proxyInboundFirewallUdpPorts; + }) + # 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 != { }) ( + let + rules = lib.concatMapStrings (interface: '' + iifname "${interface}" meta mark ${toString globalTproxy.fwmark} accept + '') globalTproxy.lanInterfaces; + in + { + extraInputRules = rules; + extraReversePathFilterRules = rules; + } + )) + ]; + sysctl = tproxyLanSysctl; groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) [ userControlCfg.group diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index d35bc42..82bbedd 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -173,7 +173,7 @@ let --argjson auth_enabled ${if needsLocalProxyAuth then "true" else "false"} \ --arg user ${if needsLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \ --arg password ${if needsLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \ - '.inbounds = $ibs + '.inbounds += $ibs | .outbounds = $obs + .outbounds | if $auth_enabled then (.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users) @@ -220,6 +220,20 @@ let } mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json" + # The stats API's socket takes this setgid directory's group: XRay cannot chown it. + API_DIR=$(dirname ${lib.escapeShellArg constants.inboundStatsApiSocket}) + rm -rf "$API_DIR" + ${ + if !constants.privileged then + ''mkdir -m 0700 "$API_DIR"'' + else if userControlAllows "stats" then + '' + install -d -m 2750 -o ${constants.serviceUser} -g ${lib.escapeShellArg userControlCfg.group} "$API_DIR" || + install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"'' + else + ''install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"'' + } + ${writeLinksBlock} ${writeSubscriptionsBlock} @@ -231,7 +245,7 @@ let collectInboundStats = pkgs.writeShellScript "proxy-suite-inbounds" '' set -euo pipefail file=${lib.escapeShellArg constants.inboundStatsFile} - api=--server=127.0.0.1:${toString constants.inboundStatsApiPort} + api=--server=unix://${constants.inboundStatsApiSocket} # A timer run and a stop can overlap: each reads and resets part, and both rewrite the file. exec 9> "$file.lock" ${pkgs.util-linux}/bin/flock 9 diff --git a/modules/proxy-suite/service/routing-scripts.nix b/modules/proxy-suite/service/routing-scripts.nix index eb90726..dd496b2 100644 --- a/modules/proxy-suite/service/routing-scripts.nix +++ b/modules/proxy-suite/service/routing-scripts.nix @@ -8,9 +8,11 @@ let ip nft nftablesRulesFile + killSwitchRulesFile constants globalTun globalTproxy + tproxyLanSysctl perAppRoutingTun proxyCfg ; @@ -62,8 +64,24 @@ let family = "inet"; table = xrayTunReplyTable; }; + deleteKillSwitchTable = builders.mkNftDeleteTable { + inherit nft; + family = "inet"; + table = "proxy_suite_killswitch"; + }; in { + killSwitchUpScript = pkgs.writeShellScript "proxy-suite-routing" '' + set -euo pipefail + ${deleteKillSwitchTable} + ${nft} -f ${killSwitchRulesFile} + ''; + + killSwitchDownScript = pkgs.writeShellScript "proxy-suite-routing" '' + set +e + ${deleteKillSwitchTable} + ''; + xrayTunUpScript = pkgs.writeShellScript "proxy-suite-routing" '' set -euo pipefail @@ -139,6 +157,12 @@ in }} ${nft} -f ${nftablesRulesFile} + # Set on NixOS already; system-manager hosts only get them here. + ${lib.concatStrings ( + lib.mapAttrsToList (name: value: '' + ${pkgs.procps}/bin/sysctl -q -w ${name}=${toString value} + '') tproxyLanSysctl + )} ${builders.mkTproxyRoutingUp { inherit ip; inherit ipv6; diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index bc25053..9f43e52 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -11,6 +11,8 @@ let pureXrayEnabled globalTun globalTproxy + killSwitchEnabled + awgGlobalProfiles perAppRoutingTun perAppRoutingTproxy perAppZapretEnabled @@ -37,6 +39,8 @@ let xrayTunUpScript tproxyUpScript tproxyDownScript + killSwitchUpScript + killSwitchDownScript tunCleanupScript ; @@ -44,6 +48,7 @@ let socks = "proxy-suite-socks"; tproxy = "proxy-suite-tproxy"; tun = "proxy-suite-tun"; + killSwitch = "proxy-suite-killswitch"; perAppTun = "proxy-suite-per-app-tun"; perAppTproxy = "proxy-suite-per-app-tproxy"; perAppZapret = "proxy-suite-per-app-zapret"; @@ -132,6 +137,23 @@ let extraServiceConfig.RemainAfterExit = false; }; } + # Pulled in by every global tunnel and left up when it stops or crashes: only + # proxy-ctl's off verbs take it down. After them, so a first start still fetches + # subscriptions and resolves endpoints directly. + { + enable = killSwitchEnabled; + name = serviceNames.killSwitch; + value = mkOneshotService { + description = "proxy-suite kill switch - reject traffic outside the global tunnel"; + after = [ + "${serviceNames.socks}.service" + "${serviceNames.tun}.service" + ] + ++ map (name: "proxy-suite-awg-${name}.service") (builtins.attrNames awgGlobalProfiles); + execStart = killSwitchUpScript; + execStop = killSwitchDownScript; + }; + } { enable = proxyEnabled && globalTproxy.enable; name = serviceNames.tproxy; @@ -143,6 +165,7 @@ let ]; wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ]; requires = [ "${serviceNames.socks}.service" ]; + wants = lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service"; conflicts = [ "${serviceNames.tun}.service" "${serviceNames.perAppTproxy}.service" @@ -157,7 +180,10 @@ let value = mkRestartingService { description = "${backendDescription} TUN proxy client"; after = [ "network-online.target" ]; - wants = [ "network-online.target" ]; + wants = [ + "network-online.target" + ] + ++ lib.optional killSwitchEnabled "${serviceNames.killSwitch}.service"; wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ]; conflicts = [ "${serviceNames.tproxy}.service" ]; execStartPre = tunCleanupScript; diff --git a/modules/proxy-suite/zapret2.nix b/modules/proxy-suite/zapret2.nix index fb69818..2a9f28e 100644 --- a/modules/proxy-suite/zapret2.nix +++ b/modules/proxy-suite/zapret2.nix @@ -11,7 +11,7 @@ let builders = import ./service/builders.nix { inherit lib pkgs; }; - inherit (builders) mkOneshotService; + inherit (builders) mkRestartingService; zapretCfg = cfg.zapret; perAppZapretCfg = cfg.perAppRouting.zapret; @@ -87,8 +87,16 @@ let if userControlAllows "zapret" then "2775 -g ${lib.escapeShellArg cfg.userControl.group}" else "0755" } ${runtime.stateDir} ${runtime.circularStateDir} touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile} + ${runtime.initScript} start_fw ''; + # nfqws2 runs supervised; the firewall comes and goes around it. + daemonConfig = runtimeEnv: { + Type = "notify"; + ExecReload = "${lib.getExe' pkgs.coreutils "kill"} -HUP $MAINPID"; + Environment = runtimeEnv; + }; + cutoff = import ./zapret2/cutoff.nix { inherit lib @@ -110,7 +118,7 @@ in services.proxy-suite.internal.services.proxy-suite-zapret = lib.mkIf zapretCfg.enable - (mkOneshotService { + (mkRestartingService { description = "zapret2 DPI bypass"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; @@ -119,20 +127,19 @@ in preStart = mkPreStart; runtimeDirectory = "proxy-suite-zapret"; stateDirectory = "proxy-suite"; - execStart = "${runtime.initScript} start"; - execStop = "${runtime.initScript} stop"; - extraServiceConfig = { - ExecReload = "${runtime.initScript} restart"; - Environment = runtime.mkEnv { + execStart = "${runtime.daemonScript}"; + execStopPost = "${runtime.initScript} stop_fw"; + extraServiceConfig = daemonConfig ( + runtime.mkEnv { runtime = globalRuntime; pidDir = "/run/proxy-suite-zapret"; - }; - }; + } + ); }); services.proxy-suite.internal.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable - (mkOneshotService { + (mkRestartingService { description = "proxy-suite per-app-routing zapret2 backend"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; @@ -140,13 +147,17 @@ in preStart = mkPreStart; runtimeDirectory = "proxy-suite-per-app-zapret"; stateDirectory = "proxy-suite"; - execStart = "${runtime.initScript} start"; - execStop = "${runtime.initScript} stop"; + execStart = "${runtime.daemonScript}"; execStartPre = "${perAppZapretMarkUpScript}"; - execStopPost = "${perAppZapretMarkDownScript}"; - extraServiceConfig.Environment = runtime.mkEnv { - runtime = perAppRuntime; - pidDir = "/run/proxy-suite-per-app-zapret"; - }; + execStopPost = [ + "${runtime.initScript} stop_fw" + "${perAppZapretMarkDownScript}" + ]; + extraServiceConfig = daemonConfig ( + runtime.mkEnv { + runtime = perAppRuntime; + pidDir = "/run/proxy-suite-per-app-zapret"; + } + ); }); } diff --git a/modules/proxy-suite/zapret2/runtime.nix b/modules/proxy-suite/zapret2/runtime.nix index a559917..d1ae66c 100644 --- a/modules/proxy-suite/zapret2/runtime.nix +++ b/modules/proxy-suite/zapret2/runtime.nix @@ -106,13 +106,11 @@ let end ''; - # The state layer wraps circular, so it loads after the source's Lua. z2k-tcp16 - # does nothing until the cutoff probe has written its maps. + # The state layer wraps circular, so it loads after the source's Lua. optPrefix = lib.concatStringsSep " " ( map (file: "--lua-init=@${file}") ( source.luaInit ++ [ - "${zapret2Sources.z2k}/files/lua/z2k-tcp16.lua" failStamp "${zapret2Sources.z2k}/files/lua/z2k-state-persist.lua" ] @@ -318,13 +316,26 @@ let "Z2K_STATE_DIR_OVERRIDE=${circularStateDir}" "Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE=${pidDir}" ] - # The cutoff probe's maps, read by z2k-tcp16.lua; pin.txt forces one name for the line. - ++ lib.optionals zapret2Cfg.cutoff.enable [ + # The cutoff probe's maps, read by z2k's tcp16 name step; pin.txt forces one name for the line. + ++ lib.optionals (zapret2Cfg.cutoff.enable && isZ2k) [ "Z2K_TCP16_ASN=${constants.zapret2CutoffDir}/asn.txt" "Z2K_TCP16_SNI=${constants.zapret2CutoffDir}/sni.txt" "Z2K_SNI_PIN=${constants.zapret2CutoffDir}/pin.txt" "Z2K_TCP16_NETS=${zapret2Sources.z2k}/files/lists/tcp16_nets.txt" ]; + initScript = "${zapretBase}/init.d/sysv/zapret2"; + + # nfqws2 as the unit's main process, with the command line the init script would + # build. The init script backgrounds it with stdout on /dev/null in a oneshot + # unit: when it dies, the unit stays active and the queue's bypass flag lets + # every packet through untouched, with nothing in the log. + daemonScript = pkgs.writeShellScript "proxy-suite-zapret2" '' + . "$ZAPRET_BASE/init.d/sysv/functions" + opt="--qnum=$QNUM $NFQWS2_OPT" + filter_apply_hostlist_target opt + set -f + exec "$NFQWS2" $NFQWS2_OPT_BASE $opt + ''; in { inherit @@ -337,7 +348,7 @@ in mkCustomScript mkRuntime mkEnv + initScript + daemonScript ; - - initScript = "${zapretBase}/init.d/sysv/zapret2"; } diff --git a/modules/proxy-suite/zapret2/sources.nix b/modules/proxy-suite/zapret2/sources.nix index c2f4328..97ff5f7 100644 --- a/modules/proxy-suite/zapret2/sources.nix +++ b/modules/proxy-suite/zapret2/sources.nix @@ -45,17 +45,6 @@ let ) ); lists = "--hostlist=${src}/etc/nfqws2/lists/user.list --hostlist-exclude=${src}/etc/nfqws2/lists/exclude.list"; - # z2k's 16 KB cutoff name, as its generator places it: ahead of circular, with - # no strategy tag, so every strategy carries it. - withSniPick = - profile: - let - parts = splitString " --lua-desync=circular:" profile; - in - if builtins.length parts != 2 then - throw "proxy-suite: expected one circular in the nfqws2-keenetic TCP profile" - else - "${builtins.head parts} --lua-desync=z2k_sni_pick:payload=tls_client_hello:dir=out:blob=z2k_ch:nld=2 --lua-desync=fake:payload=tls_client_hello:dir=out:blob=z2k_ch:optional:repeats=8:tcp_ts=-1000 --lua-desync=circular:${builtins.elemAt parts 1}"; in { # Its init script's order. QUIC reads the learned list but never adds to it: @@ -71,7 +60,9 @@ let (args "NFQWS_ARGS_UDP") ) "${args "NFQWS_ARGS_QUIC"} ${lists}" - "${withSniPick (args "NFQWS_ARGS")} ${lists}" + # No 16 KB cutoff name step: its fake ClientHello ahead of these strategies + # broke every host on a line where the strategies alone work. + "${args "NFQWS_ARGS"} ${lists}" ]; blobArgs = map (replaceStrings [ "@/opt/etc/nfqws2/" ] [ "@${src}/etc/nfqws2/" ]) ( filter (hasPrefix "--blob=") (words (quoted "NFQWS_BASE_ARGS")) @@ -91,10 +82,14 @@ let ports = name: between "config_official.sh" "\n${name}=\"" "\"" generator; in { + # Its S99zapret2 order. z2k-range-rand resolves the ranges its strategies + # write (repeats=6-10); without it nfqws2 sends each fake once. luaInit = map (name: "${src}/files/lua/${name}.lua") [ "z2k-alert" "z2k-quic-silence" + "z2k-tcp16" "z2k-fooling-ext" + "z2k-range-rand" "z2k-modern-core" ]; ports = { diff --git a/nix/checks/_groups-tmp.nix b/nix/checks/_groups-tmp.nix new file mode 100644 index 0000000..c45f9bf --- /dev/null +++ b/nix/checks/_groups-tmp.nix @@ -0,0 +1,342 @@ +{ + pkgs, + checkLib, +}: + +let + inherit (checkLib) + ok + mkRouting + evalProxySuite + mkRoutingRules + mkRouteModeRules + mkTProxyConfig + mkTunConfig + mkPerAppTunConfig + mkInboundsConfig + mkInboundsSpec + mkTProxyNftRules + mkNftRules + mkPerAppZapretNftRules + mkPerAppUserRules + hasDirectDomain + hasDirectIP + hasRuleSet + dnsHasRuleSet + dnsServerByTag + mkZapretBaseFor + mkZapretBase + packagePathMatches + shellValueByPrefix + baseModule + mkBadFixture + mkBadFixtureRaw + mkBadProxySuiteFixture + mkFailingAssertions + rejects + rejectsProxySuite + mkProxyCtlDerived + ; + + minimal = evalProxySuite [ baseModule ]; + checkConstants = + (import ../../modules/proxy-suite/derived.nix { + lib = pkgs.lib; + cfg = minimal.config.services.proxy-suite; + }).constants; + _minimalProxyCtl = mkProxyCtlDerived minimal; + minimalProxyCtlWrapper = _minimalProxyCtl.wrapper; + minimalProxyCtlScript = _minimalProxyCtl.script; + minimalSocksService = minimal.config.systemd.services."proxy-suite-socks"; + + coreProxyChecks = import ./core-proxy.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + minimal + mkRoutingRules + mkTProxyConfig + hasRuleSet + dnsHasRuleSet + dnsServerByTag + ; + }; + inherit (coreProxyChecks) ruDefaultConfig; + + routeModeChecks = import ./route-mode.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + mkRouteModeRules + shellValueByPrefix + minimalProxyCtlWrapper + minimalProxyCtlScript + ; + }; + + subscriptionChecks = import ./subscriptions.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + mkBadFixtureRaw + mkFailingAssertions + mkProxyCtlDerived + minimal + ; + }; + + guiChecks = import ./gui.nix { + inherit + evalProxySuite + baseModule + packagePathMatches + ; + }; + + localProxyAuthChecks = import ./local-proxy-auth.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + mkProxyCtlDerived + shellValueByPrefix + mkBadFixture + mkFailingAssertions + ruDefaultConfig + ; + }; + + sshProxyChecks = import ./ssh-proxy.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + mkBadProxySuiteFixture + mkFailingAssertions + mkRoutingRules + ; + }; + + warpChecks = import ./warp.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + mkBadProxySuiteFixture + mkFailingAssertions + ; + }; + + torChecks = import ./tor.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + mkBadProxySuiteFixture + mkFailingAssertions + mkRouting + mkTunConfig + mkTProxyConfig + mkInboundsSpec + mkInboundsConfig + mkProxyCtlDerived + ; + }; + + proxyInboundsChecks = import ./proxy-inbounds.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + mkInboundsConfig + mkInboundsSpec + ; + }; + + perAppRoutingChecks = import ./per-app-routing.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + mkProxyCtlDerived + mkPerAppUserRules + mkPerAppZapretNftRules + mkPerAppTunConfig + dnsServerByTag + mkZapretBase + mkZapretBaseFor + mkBadFixture + mkFailingAssertions + rejects + minimalProxyCtlScript + ; + }; + + outboundValidationChecks = import ./outbound-validation.nix { + inherit mkBadProxySuiteFixture mkFailingAssertions; + }; + chainingDnsChecks = import ./chaining-dns.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + mkTunConfig + mkTProxyConfig + mkBadProxySuiteFixture + mkFailingAssertions + ; + }; + + amneziaWgChecks = import ./amnezia-wg.nix { + inherit checkLib; + inherit + rejectsProxySuite + pkgs + evalProxySuite + mkBadProxySuiteFixture + mkFailingAssertions + mkProxyCtlDerived + ; + }; + + amneziaWgOutboundChecks = import ./amnezia-wg-outbound.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + mkBadProxySuiteFixture + mkFailingAssertions + mkProxyCtlDerived + mkTProxyConfig + dnsServerByTag + ; + }; + + globalProxyModeChecks = import ./global-proxy-modes.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + mkBadFixture + mkFailingAssertions + mkTunConfig + mkTProxyConfig + mkTProxyNftRules + mkNftRules + dnsServerByTag + checkConstants + ; + }; + + zapretChecks = import ./zapret.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + mkRoutingRules + mkZapretBase + mkBadFixture + mkFailingAssertions + hasDirectDomain + hasDirectIP + ; + }; + + zapret2Checks = import ./zapret2.nix { + inherit + pkgs + evalProxySuite + baseModule + mkProxyCtlDerived + mkBadFixture + mkFailingAssertions + ; + }; + + tgWsProxyChecks = import ./tg-ws-proxy.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + baseModule + mkRoutingRules + mkTProxyNftRules + mkBadFixture + mkFailingAssertions + hasDirectIP + minimal + minimalSocksService + ; + zapretSyncService = zapretChecks.syncService; + }; + + serverModuleChecks = import ./server-module.nix { + inherit checkLib pkgs mkInboundsSpec; + inherit (checkLib) system nixpkgs proxySuiteModule; + }; + + xrayBackendChecks = import ./xray-backends.nix { + inherit checkLib; + inherit + pkgs + evalProxySuite + mkTProxyConfig + mkTunConfig + mkPerAppTunConfig + shellValueByPrefix + mkBadProxySuiteFixture + mkFailingAssertions + dnsServerByTag + checkConstants + ; + }; + + validated = builtins.all (x: x) ( + [ + (ok (minimal.config.services.proxy-suite.proxy.listener.address == "127.0.0.1")) + ] + ++ coreProxyChecks.assertions + ++ localProxyAuthChecks.assertions + ++ sshProxyChecks.assertions + ++ warpChecks.assertions + ++ torChecks.assertions + ++ proxyInboundsChecks.assertions + ++ tgWsProxyChecks.assertions + ++ xrayBackendChecks.assertions + ++ outboundValidationChecks.assertions + ++ chainingDnsChecks.assertions + ++ amneziaWgChecks.assertions + ++ amneziaWgOutboundChecks.assertions + ++ zapretChecks.assertions + ++ zapret2Checks.assertions + ++ globalProxyModeChecks.assertions + ++ guiChecks.assertions + ++ subscriptionChecks.assertions + ++ routeModeChecks.assertions + ++ perAppRoutingChecks.assertions + ++ serverModuleChecks.assertions + ); +in +{ + _groups = { inherit coreProxyChecks localProxyAuthChecks sshProxyChecks warpChecks torChecks proxyInboundsChecks tgWsProxyChecks xrayBackendChecks outboundValidationChecks chainingDnsChecks amneziaWgChecks amneziaWgOutboundChecks zapretChecks zapret2Checks globalProxyModeChecks guiChecks subscriptionChecks routeModeChecks perAppRoutingChecks serverModuleChecks ; minimalOk = { assertions = [ (ok (minimal.config.services.proxy-suite.proxy.listener.address == "127.0.0.1")) ]; }; }; + proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok"); + amneziawg-secret-manifest = amneziaWgChecks.manifest; + xray-jq-filter-runtime = xrayBackendChecks.runtime; + tor-guard-runtime = torChecks.runtime; + per-app-zapret-runtime = perAppRoutingChecks.runtime; + zapret-hostlist-rules = zapretChecks.rules; + zapret2-config = zapret2Checks.runtime; + proxy-suite-gui-build = _minimalProxyCtl.proxyCtl.gui; +} diff --git a/nix/checks/global-proxy-modes.nix b/nix/checks/global-proxy-modes.nix index 271c985..0b78453 100644 --- a/nix/checks/global-proxy-modes.nix +++ b/nix/checks/global-proxy-modes.nix @@ -8,6 +8,7 @@ mkTunConfig, mkTProxyConfig, mkTProxyNftRules, + mkNftRules, dnsServerByTag, checkConstants, }: @@ -23,6 +24,7 @@ let mkTunConfig mkTProxyConfig mkTProxyNftRules + mkNftRules ; }; @@ -34,6 +36,14 @@ let tproxyManualStopScript tproxyManualConfig tproxyManualNftRules + tproxyLanFixture + tproxyLanNftRules + tproxyLanStartScript + killSwitchFixture + killSwitchNftRules + awgKillSwitchFixture + awgKillSwitchNftRules + awgKillSwitchPrepare tproxyIPv4OnlyStartScript tproxyIPv4OnlyConfig tproxyIPv4OnlyNftRules @@ -70,6 +80,85 @@ in assert pkgs.lib.hasInfix "set +e" tproxyManualStopScript; true ) + # Gateway clients: diverted past the LAN destinations, let through the host firewall by + # mark only, with forwarding for the rest. + ( + let + cfg = tproxyLanFixture.config; + rules = tproxyLanNftRules; + at = + needle: + pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix needle) null (pkgs.lib.splitString "\n" rules); + in + assert pkgs.lib.hasInfix + ''iifname { "br0" } meta l4proto { tcp, udp } tproxy ip to 127.0.0.1:1085 meta mark set 1'' + rules; + assert pkgs.lib.hasInfix ''iifname { "br0" } meta l4proto { tcp, udp } tproxy ip6'' rules; + assert at "ip daddr 192.168.0.0/16 tcp dport != 53 return" < at ''iifname { "br0" }''; + assert at ''iifname { "br0" }'' < at "ip saddr $RESERVED_IP return"; + assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 accept'' + cfg.networking.firewall.extraInputRules; + assert pkgs.lib.hasInfix ''iifname "br0" meta mark 1 accept'' + cfg.networking.firewall.extraReversePathFilterRules; + assert !builtins.elem "br0" cfg.networking.firewall.trustedInterfaces; + assert cfg.boot.kernel.sysctl."net.ipv4.ip_forward" == 1; + assert pkgs.lib.hasInfix "sysctl -q -w net.ipv4.ip_forward=1" tproxyLanStartScript; + assert !(pkgs.lib.hasInfix "iifname {" tproxyManualNftRules); + assert !(pkgs.lib.hasInfix "sysctl" tproxyManualStartScript); + true + ) + # The kill switch: pulled in by both modes, but not stopped with them; it lets the proxy's + # own traffic and its DNS hand-off past, and cuts gateway clients off from the internet. + ( + let + units = killSwitchFixture.config.systemd.services; + ks = units."proxy-suite-killswitch"; + rules = killSwitchNftRules; + before = + a: b: + pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix a) null (pkgs.lib.splitString "\n" rules) + < pkgs.lib.lists.findFirstIndex (pkgs.lib.hasInfix b) null (pkgs.lib.splitString "\n" rules); + in + assert builtins.elem "proxy-suite-killswitch.service" units."proxy-suite-tun".wants; + assert builtins.elem "proxy-suite-killswitch.service" units."proxy-suite-tproxy".wants; + assert !(units."proxy-suite-tun" ? bindsTo) || units."proxy-suite-tun".bindsTo == [ ]; + assert !(ks ? partOf) || ks.partOf == [ ]; + assert builtins.elem "proxy-suite-tun.service" ks.after; + assert ks.wantedBy == [ ]; + assert pkgs.lib.hasInfix ''meta skuid "proxy-suite-daemon" accept'' rules; + assert pkgs.lib.hasInfix "meta mark { 1, 2 } accept" rules; + assert pkgs.lib.hasInfix ''oifname "singtun0" accept'' rules; + assert before "ip daddr 172.19.0.1/30 accept" "th dport 53 reject"; + assert before "th dport 53 reject" "ip daddr $RESERVED_IP accept"; + assert pkgs.lib.hasInfix ''iifname { "br0" } reject'' rules; + assert !(tproxyManualFixture.config.systemd.services ? "proxy-suite-killswitch"); + true + ) + # A global AmneziaWG profile under the kill switch: a mark the rules know, its interface, + # and a group for awg-quick's own lookups. Stopping the profile no longer lifts it. + ( + let + cfg = awgKillSwitchFixture.config; + units = cfg.systemd.services; + home = units.proxy-suite-awg-home; + rules = awgKillSwitchNftRules; + in + assert builtins.elem "proxy-suite-killswitch.service" home.wants; + assert builtins.elem "proxy-suite-awg-home.service" units.proxy-suite-killswitch.after; + assert !builtins.elem "proxy-suite-killswitch.service" (home.conflicts or [ ]); + assert (units.proxy-suite-killswitch.conflicts or [ ]) == [ ]; + assert home.serviceConfig.Group == "proxy-suite-awg"; + assert cfg.users.groups ? proxy-suite-awg; + assert pkgs.lib.hasInfix "--fwmark 51820" awgKillSwitchPrepare; + assert pkgs.lib.hasInfix ''meta skgid "proxy-suite-awg" accept'' rules; + assert pkgs.lib.hasInfix + ''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}" } accept'' + rules; + assert pkgs.lib.hasInfix "meta mark { 1, 2, 51820 } accept" rules; + assert !(pkgs.lib.hasInfix "skgid" killSwitchNftRules); + assert !(units.proxy-suite-awg-home-watchdog.serviceConfig ? Group); + true + ) # IPv6 goes through the same port on ::1; without it IPv6 is left alone. ( let diff --git a/nix/checks/global-proxy-modes/fixtures.nix b/nix/checks/global-proxy-modes/fixtures.nix index c62bcf5..7249a3f 100644 --- a/nix/checks/global-proxy-modes/fixtures.nix +++ b/nix/checks/global-proxy-modes/fixtures.nix @@ -6,6 +6,7 @@ mkTunConfig, mkTProxyConfig, mkTProxyNftRules, + mkNftRules, }: let @@ -45,6 +46,55 @@ let tproxyManualConfig = mkTProxyConfig tproxyManualFixture; tproxyManualNftRules = mkTProxyNftRules tproxyManualFixture; + tproxyLanFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.tproxy = { + enable = true; + lanInterfaces = [ "br0" ]; + }; + } + ]; + tproxyLanNftRules = mkTProxyNftRules tproxyLanFixture; + tproxyLanStartScript = + generated.readDerivation + tproxyLanFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig.ExecStart; + + killSwitchFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.killSwitch.enable = true; + services.proxy-suite.proxy = { + tun.enable = true; + tproxy = { + enable = true; + lanInterfaces = [ "br0" ]; + }; + }; + } + ]; + killSwitchNftRules = mkNftRules killSwitchFixture "killSwitchRulesFile"; + + # A global AmneziaWG profile alone, no proxy. + awgKillSwitchFixture = evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + killSwitch.enable = true; + amneziaWg = { + enable = true; + kernelModulePackage = null; + profiles.home.configFile = "/run/secrets/awg.conf"; + }; + }; + } + ]; + awgKillSwitchNftRules = mkNftRules awgKillSwitchFixture "killSwitchRulesFile"; + awgKillSwitchPrepare = generated.readDerivation ( + builtins.head awgKillSwitchFixture.config.systemd.services.proxy-suite-awg-home.serviceConfig.ExecStartPre + ); + tproxyIPv4OnlyFixture = evalProxySuite [ baseModule { @@ -135,6 +185,9 @@ let }; } ] + # The kill switch guards a global mode, and a gateway needs TProxy. + [ { services.proxy-suite.killSwitch.enable = true; } ] + [ { services.proxy-suite.proxy.tproxy.lanInterfaces = [ "br0" ]; } ] ]; tunDefaultConfig = mkTunConfig tunManualFixture; @@ -150,6 +203,14 @@ in tproxyManualStopScript tproxyManualConfig tproxyManualNftRules + tproxyLanFixture + tproxyLanNftRules + tproxyLanStartScript + killSwitchFixture + killSwitchNftRules + awgKillSwitchFixture + awgKillSwitchNftRules + awgKillSwitchPrepare tproxyIPv4OnlyStartScript tproxyIPv4OnlyConfig tproxyIPv4OnlyNftRules diff --git a/nix/checks/lib.nix b/nix/checks/lib.nix index f5ce4a1..ffa2186 100644 --- a/nix/checks/lib.nix +++ b/nix/checks/lib.nix @@ -245,6 +245,7 @@ in mkInboundsConfig mkInboundsSpec mkTProxyNftRules + mkNftRules mkPerAppZapretNftRules mkPerAppUserRules ok diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index e11f4cf..301149a 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -16,6 +16,7 @@ let mkInboundsConfig mkInboundsSpec mkTProxyNftRules + mkNftRules mkPerAppZapretNftRules mkPerAppUserRules hasDirectDomain @@ -232,6 +233,7 @@ let mkTunConfig mkTProxyConfig mkTProxyNftRules + mkNftRules dnsServerByTag checkConstants ; diff --git a/nix/checks/proxy-inbounds-runtime.nix b/nix/checks/proxy-inbounds-runtime.nix index d773231..9e0b581 100644 --- a/nix/checks/proxy-inbounds-runtime.nix +++ b/nix/checks/proxy-inbounds-runtime.nix @@ -125,7 +125,7 @@ pkgs.testers.runNixOSTest { with subtest("safety rules are present and ordered first"): cfg = "/run/proxy-suite-inbounds/config.json" - server.succeed(f"test $(jq -r '.routing.rules[0].ruleTag' {cfg}) = inbound-block-private") + server.succeed(f"test $(jq -r '.routing.rules[1].ruleTag' {cfg}) = inbound-block-private") server.succeed(f"jq -e '.routing.rules[] | select(.ruleTag == \"inbound-block-ru-domain\")' {cfg}") server.succeed(f"test $(jq -r '.routing.rules[-1].outboundTag' {cfg}) = direct") diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index 919b1d6..6893187 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -171,6 +171,17 @@ let alpn = [ "h3" ]; }; }; + # hysteria2 is QUIC: UDP only. + listeners.hy2-in = { + type = "hysteria2"; + port = 8444; + users = [ { passwordFile = "/run/secrets/hy2"; } ]; + tls = { + certificateFile = "/run/acme/fullchain.pem"; + keyFile = "/run/acme/key.pem"; + }; + hysteria.masquerade = "https://www.example.com"; + }; }; firewallSpec = mkInboundsSpec firewallFixture; wsListener = lib.head (builtins.filter (l: l.tag == "ws-in") firewallSpec.listeners); @@ -314,7 +325,7 @@ let failing = [ (mkRejectsListener ( - realityListener // { port = 18536; } + realityListener // { port = 18533; } ) "collides with a port proxy-suite uses internally") # Every user is checked, not only the first. (mkRejectsListener ( @@ -434,6 +445,39 @@ let } ) "flow is only valid on a vless listener") + (mkRejects ( + baseProxy + // { + inbounds = { + enable = true; + listeners.hy2-in = { + type = "hysteria2"; + port = 8444; + users = [ { passwordFile = "/run/secrets/hy2"; } ]; + transport.type = "ws"; + tls = { + certificateFile = "/c"; + keyFile = "/k"; + }; + }; + }; + } + ) "hysteria2 takes no reality or transport") + + (mkRejects ( + baseProxy + // { + inbounds = { + enable = true; + listeners.hy2-in = { + type = "hysteria2"; + port = 8444; + users = [ { passwordFile = "/run/secrets/hy2"; } ]; + }; + }; + } + ) "needs both tls.certificateFile and tls.keyFile") + (mkRejects ( baseProxy // { @@ -516,8 +560,8 @@ let ]; assertions = [ - # Listeners are rendered at start time. - (ok (relayConfig.inbounds == [ ])) + # Listeners are rendered at start time; only the stats API's is fixed. + (ok (map (ib: ib.tag) relayConfig.inbounds == [ "api-in" ])) # AsIs when relayed through sing-box; IPOnDemand when XRay dials (see the template). (ok (relayConfig.routing.domainStrategy == "AsIs")) @@ -547,7 +591,7 @@ let (ok ((ruleByTag exitConfig "inbound-final").outboundTag == "direct")) # Safety rules come first. - (ok (builtins.head (ruleTags relayConfig) == "inbound-block-private")) + (ok (lib.take 2 (ruleTags relayConfig) == [ "inbound-stats-api" "inbound-block-private" ])) (ok ((ruleByTag relayConfig "inbound-block-private").outboundTag == "block")) (ok ((ruleByTag relayConfig "inbound-block-ru-domain").domain == [ "geosite:category-ru" ])) (ok ((ruleByTag relayConfig "inbound-block-ru-ip").ip == [ "geoip:ru" ])) @@ -555,7 +599,8 @@ let # serverAddress is exempt after blockPrivate, before the country blocks. ( assert - lib.take 3 (ruleTags namedConfig) == [ + lib.take 4 (ruleTags namedConfig) == [ + "inbound-stats-api" "inbound-block-private" "inbound-server-address-direct" "inbound-block-ru-domain" @@ -642,10 +687,15 @@ let lib.sort lib.lessThan firewallFixture.config.networking.firewall.allowedUDPPorts == [ 8388 8443 + 8444 ]; true ) (ok (wsListener.port == 10002 && wsListener.sharePort == 443)) + (ok ( + (lib.head (builtins.filter (l: l.tag == "hy2-in") firewallSpec.listeners)).hysteria.masquerade + == "https://www.example.com" + )) (ok (noFirewallFixture.config.networking.firewall.allowedTCPPorts == [ ])) # The unit exists, and only waits on the client stack when it relays. diff --git a/nix/checks/tor.nix b/nix/checks/tor.nix index a6e53cc..fffb88e 100644 --- a/nix/checks/tor.nix +++ b/nix/checks/tor.nix @@ -146,7 +146,8 @@ let }; exitNode = mkFixture "sing-box" exitInbounds; exitNodeConfig = mkInboundsConfig exitNode; - exitNodeRules = exitNodeConfig.routing.rules; + # Past the stats API's own rule, which matches only its inbound. + exitNodeRules = builtins.tail exitNodeConfig.routing.rules; exitNodeNoOnion = mkInboundsConfig ( mkFixture "sing-box" (exitInbounds // { tor.routeOnion = false; }) ); diff --git a/nix/checks/zapret2.nix b/nix/checks/zapret2.nix index d815529..d852c9f 100644 --- a/nix/checks/zapret2.nix +++ b/nix/checks/zapret2.nix @@ -43,6 +43,7 @@ let tunedRuntime = runtimeDir zapret2Tuned globalService; noAutoRuntime = runtimeDir zapret2NoAuto globalService; z2kRuntime = runtimeDir zapret2Z2k globalService; + daemonStart = zapret2Global.config.systemd.services.${globalService}.serviceConfig.ExecStart; cutoffProbe = zapret2Global.config.systemd.services.proxy-suite-zapret2-cutoff.serviceConfig.ExecStart; socksStart = fixture: fixture.config.systemd.services.proxy-suite-socks.serviceConfig.ExecStart; @@ -81,14 +82,32 @@ in true ) - # The cutoff probe comes with zapret2, on a timer, and nfqws2 reads its maps. + # nfqws2 is the unit's supervised main process: if it dies, systemd sees it and + # restarts it, instead of a oneshot staying active while the queue bypasses it. + ( + let + sc = zapret2PerApp.config.systemd.services.${perAppService}.serviceConfig; + gc = zapret2Global.config.systemd.services.${globalService}.serviceConfig; + in + assert gc.Type == "notify" && sc.Type == "notify"; + assert gc.Restart == "on-failure" && sc.Restart == "on-failure"; + assert lib.hasSuffix "stop_fw" gc.ExecStopPost; + assert builtins.length sc.ExecStopPost == 2; + true + ) + + # The cutoff probe comes with zapret2, on a timer; z2k's nfqws2 reads its maps. ( assert zapret2Global.config.systemd.timers ? proxy-suite-zapret2-cutoff; assert !(zapretDiscordYoutubeGlobal.config.systemd.services ? proxy-suite-zapret2-cutoff); assert (proxyCtlEnv zapret2Global).ZAPRET_CUTOFF_ENABLED == "1"; assert - envValue zapret2Global globalService "Z2K_TCP16_ASN=" + envValue zapret2Z2k globalService "Z2K_TCP16_ASN=" == "/var/lib/proxy-suite/zapret2/cutoff/asn.txt"; + assert + !(builtins.any (lib.hasPrefix "Z2K_TCP16_ASN=") + zapret2Global.config.systemd.services.${globalService}.serviceConfig.Environment + ); true ) @@ -175,11 +194,16 @@ in test "$(grep -oF -- '' "${z2kRuntime}/config" | wc -l)" = 1 grep -qF -- '/lists/whitelist.txt --hostlist-exclude=/var/lib/proxy-suite/zapret2/zapret-hosts-user-exclude.txt' "${z2kRuntime}/config" + # z2k's Lua in its own order: ranges (repeats=6-10) resolve before its strategies fire. + grep -qE -- 'z2k-fooling-ext\.lua --lua-init=@[^ ]+/z2k-range-rand\.lua --lua-init=@[^ ]+/z2k-modern-core\.lua' "${z2kRuntime}/config" + # --- 16 KB cutoff --------------------------------------------------- - # The whitelisted-name step runs ahead of rotation, in both sources. - grep -qF -- '/files/lua/z2k-tcp16.lua' "${globalRuntime}/config" - grep -qF -- 'blob=z2k_ch:optional:repeats=8:tcp_ts=-1000 --lua-desync=circular:fails=2:time=300' "${globalRuntime}/config" + # The whitelisted-name step runs ahead of rotation, in z2k only: ahead of the + # nfqws2-keenetic strategies it broke hosts they reach on their own. + grep -qF -- '/files/lua/z2k-tcp16.lua' "${z2kRuntime}/config" grep -qF -- 'blob=z2k_ch:optional:repeats=8:tcp_ts=-1000 --lua-desync=circular:fails=3:time=60:key=rkn_tcp' "${z2kRuntime}/config" + if grep -qF -- 'z2k_sni_pick' "${globalRuntime}/config"; then exit 1; fi + if grep -qF -- 'z2k-tcp16.lua' "${globalRuntime}/config"; then exit 1; fi # zapret2 leaves the probe's own connections alone, in every chain. test "$(grep -c 'ct mark and 0x2000000 != 0 return' "${globalRuntime}/init.d/sysv/custom.d/50-proxy-suite-custom.sh")" = 4 @@ -253,6 +277,13 @@ in grep -qx -- '--hostlist-auto-fail-threshold=3' global.args grep -qx -- '--hostlist-auto-fail-time=300' global.args + # The supervised launcher execs nfqws2 with the command line the init script builds. + printf '#!/bin/sh\nprintf "%%s\\n" "$@"\n' >fake-nfqws2 + chmod +x fake-nfqws2 + ZAPRET_RW=${globalRuntime} NFQWS2="$PWD/fake-nfqws2" ${daemonStart} >daemon.args + head -n1 daemon.args | grep -qx -- '--user=root' + tail -n +6 daemon.args | diff - global.args + dry_run ${z2kRuntime} z2k.args test "$(grep -cx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" z2k.args)" = 1 diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index a9fae2f..d5613ed 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -25,6 +25,7 @@ ALL_SERVICES = [ "proxy-suite-socks", "proxy-suite-tproxy", "proxy-suite-tun", + "proxy-suite-killswitch", "proxy-suite-inbounds", "proxy-suite-ssh-proxy", "proxy-suite-warp", @@ -80,6 +81,7 @@ Secrets and changes need root, or the userControl group. proxy subs add [tag] add a subscription at runtime; no tag: named after its host proxy subs rm remove a runtime subscription proxy subs link [--qr] its URL + proxy rulesets [list|update] routing rule sets: when each was fetched; update fetches them now proxy config [--raw] client config to import elsewhere; --raw: as running proxy tun [status|on|off] global TUN mode proxy tproxy [status|on|off] global TProxy mode @@ -104,6 +106,9 @@ Secrets and changes need root, or the userControl group. awg [list] AmneziaWG profiles and their state awg on | off [profile] | restart [profile] + killswitch [status|on|off] reject traffic outside the global tunnel; up with + TUN, TProxy or AWG, lifted only by off here or on them + ssh [status|on|off] SSH SOCKS5 tunnel warp [status|on|off] WARP tunnel behind the warp outbound tor [status|on|off] Tor, behind the tor outbound and the onion service @@ -464,6 +469,7 @@ COMPLETE = { "proxy": "local proxy backend", "zapret": "DPI bypass", "awg": "AmneziaWG profiles", + "killswitch": "reject traffic outside the global tunnel", "ssh": "SSH SOCKS5 tunnel", "warp": "WARP tunnel behind the warp outbound", "tor": "Tor, behind the tor outbound and the onion service", @@ -484,6 +490,7 @@ COMPLETE = { "unpin": "let the configured selection pick again", "mode": "show or override the routing mode", "subs": "subscription caches", + "rulesets": "routing rule sets", "tun": "global TUN mode", "tproxy": "global TProxy mode", "auto": "what autoProxy routed", @@ -533,6 +540,7 @@ COMPLETE = { "link": "its URL", } }, + "proxy rulesets": {"words": {"list": "when each rule set was fetched", "update": "fetch the rule sets now"}}, "proxy subs link": {"args": lambda: _names(_sub_tags() + _runtime_tags("subscription")), "flags": {"--qr": "print a QR code"}}, "proxy subs rm": {"args": lambda: _names(_runtime_tags("subscription"))}, "proxy tun": {"words": TOGGLE}, @@ -588,6 +596,7 @@ COMPLETE = { "awg restart": {"args": lambda: _names(_awg_profiles())}, "ssh": {"words": TOGGLE}, "warp": {"words": TOGGLE}, + "killswitch": {"words": TOGGLE}, "tor": {"words": {**TOGGLE, "newnym": "new circuits for new connections"}}, "tg": {"words": TOGGLE}, "apps": {"words": {"list": "per-app routing profiles", "run": "run a command through a profile"}}, @@ -692,9 +701,11 @@ SNAPSHOT_UNITS = { "proxy": "proxy-suite-socks", "tproxy": "proxy-suite-tproxy", "tun": "proxy-suite-tun", + "killswitch": "proxy-suite-killswitch", "zapret": "proxy-suite-zapret", } SUBSCRIPTION_UPDATE = "proxy-suite-subscription-update" +KILL_SWITCH = "proxy-suite-killswitch" BUSY_STATES = ("activating", "deactivating", "reloading") @@ -831,6 +842,8 @@ def _status_autoproxy(): if env("AUTOPROXY_ENABLED") != "1": return "" state = os.path.join(_autoproxy_dir(), "state.json") + if _autoproxy_unreadable(_autoproxy_dir()): + return "state not readable" if not readable(state): return "" try: @@ -906,7 +919,7 @@ def cmd_proxy(verb="status", *args): elif verb == "off": if not svc_exists("proxy-suite-socks"): die("proxy is not enabled in this configuration.") - for svc in ("proxy-suite-tproxy", "proxy-suite-tun"): + for svc in ("proxy-suite-tproxy", "proxy-suite-tun", KILL_SWITCH): if svc_exists(svc): systemctl("stop", svc) must("stop", "proxy-suite-socks") @@ -922,16 +935,19 @@ def cmd_proxy(verb="status", *args): cmd_route_mode(*args) elif verb == "subs": cmd_subscription(*args) - elif verb == "tun": - _toggle("proxy-suite-tun", "proxy tun", *args) - elif verb == "tproxy": - _toggle("proxy-suite-tproxy", "proxy tproxy", *args) + elif verb == "rulesets": + cmd_rulesets(*args) + elif verb in ("tun", "tproxy"): + _toggle(f"proxy-suite-{verb}", f"proxy {verb}", *args) + # A mode stopped on purpose lifts the kill switch; one that fails leaves it up. + if args[:1] == ("off",) and svc_exists(KILL_SWITCH): + systemctl("stop", KILL_SWITCH) elif verb == "auto": cmd_proxy_auto(*args) elif verb in ("probe", "learn", "forget", "relearn", "queue", "learned"): cmd_proxy_auto(verb, *args) else: - usage("proxy [status|on|off|outbounds|pin|unpin|mode|subs|tun|tproxy|auto|config]") + usage("proxy [status|on|off|outbounds|pin|unpin|mode|subs|rulesets|tun|tproxy|auto|config]") def cmd_outbounds(verb="list", *args): @@ -1732,6 +1748,39 @@ def cmd_subscription(verb="list", *args): usage("proxy subs [list|update|add [tag] |rm |link ]") +RULE_SETS_UNIT = "proxy-suite-rulesets" + + +def cmd_rulesets(verb="list", *_): + rule_sets = read_json_or(env("RULE_SETS_FILE"), []) + if verb == "update": + if not rule_sets or not svc_exists(RULE_SETS_UNIT): + die("No proxy.routing.ruleSets in this configuration.") + # A oneshot: this returns once every rule set was tried. + status, _ = systemctl("start", RULE_SETS_UNIT) + print("Rule sets updated." if status == 0 else f"Some rule sets were not updated: {journal_hint(RULE_SETS_UNIT, 20)}") + sys.exit(status) + elif verb == "list": + if not rule_sets: + print("No rule sets configured.") + return + print(f" {'NAME':<24} {'LAST UPDATED':<22} SIZE") + for rs in rule_sets: + try: + stat = os.stat(rs["path"]) + except OSError: + print(f" {rs['name']:<24} {'(missing)':<22} -") + continue + updated = datetime.datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M:%S") + print(f" {rs['name']:<24} {updated:<22} {stat.st_size}") + next_run = _timer_next_run(f"{RULE_SETS_UNIT}.timer") + if next_run: + print() + print(f"Next update: {datetime.datetime.fromtimestamp(next_run):%H:%M:%S}, {_in_time(next_run)}") + else: + usage("proxy rulesets [list|update]") + + # --- proxy auto: reachability probe ------------------------------------------- # # Fetches a URL through one exit after another (direct first) and finds one @@ -2648,7 +2697,9 @@ def cmd_where(domain="", *_): config_path = _runtime_file("config.json") geosite_dir = "" - if readable(config_path): + if os.path.exists(config_path) and not readable(config_path): + _where_row("sing-box", f"routing is not readable - {ask_group()}") + elif readable(config_path): try: config = read_json(config_path) except (OSError, ValueError): @@ -2683,7 +2734,7 @@ def cmd_where(domain="", *_): _where_row("inbounds", f"{shown} - {why}") if env("AUTOPROXY_ENABLED") == "1": - if not readable(os.path.join(_autoproxy_dir(), "state.json")): + if _autoproxy_unreadable(_autoproxy_dir()): _where_row("autoProxy", f"state is not readable - {ask_group()}") else: domains = _autoproxy_state(_autoproxy_dir()).get("domains") @@ -2750,12 +2801,13 @@ def cmd_awg(verb="list", *args): must("start", _awg_service(args[0])) elif verb in ("off", "restart"): targets = list(args[:1]) or _active_awg_profiles() - if not targets: - if verb == "off": - return + if not targets and verb == "restart": die("No AmneziaWG profile is active.") for profile in targets: must("stop" if verb == "off" else "restart", _awg_service(profile)) + # Also after a profile that already failed: off is how its kill switch is lifted. + if verb == "off" and svc_exists(KILL_SWITCH): + systemctl("stop", KILL_SWITCH) else: usage("awg [list] | on | off [profile] | restart [profile]") @@ -3028,9 +3080,20 @@ AWG_ONLINE_SECONDS = 180 def _inbound_presence(): - """user -> (state, addresses): "online", "seen