From 5f29f30790909f16873f4abb4918aa622f04cf66 Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Wed, 23 Sep 2026 11:31:01 +0500 Subject: [PATCH] feat: warp endpoint; fix: hardening --- docs/options/amneziaWg.md | 21 ++ docs/options/index.md | 3 +- docs/options/proxy.md | 11 +- docs/options/warp.md | 24 ++ flake.nix | 3 + modules/proxy-suite/amnezia-wg.nix | 11 +- modules/proxy-suite/options/lib.nix | 9 + modules/proxy-suite/options/proxy-dns.nix | 18 +- .../proxy-suite/options/types/amnezia-wg.nix | 2 + modules/proxy-suite/options/warp.nix | 8 + modules/proxy-suite/service-assertions.nix | 3 +- modules/proxy-suite/tor.nix | 4 +- modules/proxy-suite/warp.nix | 3 +- modules/proxy-suite/wg-tunnel.nix | 16 +- modules/proxy-suite/zapret2/runtime.nix | 4 +- nix/checks/_groups-tmp.nix | 342 ------------------ nix/checks/core-proxy/routing-dns.nix | 2 +- nix/checks/per-app-routing-zapret.nix | 4 +- nix/checks/proxy-inbounds.nix | 7 +- nix/checks/repo.nix | 31 ++ nix/checks/warp.nix | 42 ++- nix/checks/zapret2.nix | 12 +- pkgs/proxy-ctl/proxy_ctl.py | 5 +- pkgs/proxy-ctl/proxy_tui.py | 2 +- pkgs/proxy-ctl/test_proxy_tui.py | 8 +- ruff.toml | 3 + scripts/amneziawg_config.py | 10 + scripts/patch-zapret-config.py | 2 +- scripts/test-amneziawg-config.py | 20 + scripts/test-fetch-subscription.py | 2 - scripts/test-warp-outbound.py | 8 + scripts/warp_outbound.py | 7 +- 32 files changed, 266 insertions(+), 381 deletions(-) delete mode 100644 nix/checks/_groups-tmp.nix create mode 100644 ruff.toml diff --git a/docs/options/amneziaWg.md b/docs/options/amneziaWg.md index abe8319..052b7e2 100644 --- a/docs/options/amneziaWg.md +++ b/docs/options/amneziaWg.md @@ -13,6 +13,7 @@ Part of the [proxy-suite options reference](./index.md). - [asOutbound](#services-proxy-suite-amneziawg-profiles-name-asoutbound) - [autostart](#services-proxy-suite-amneziawg-profiles-name-autostart) - [configFile](#services-proxy-suite-amneziawg-profiles-name-configfile) + - [endpoint](#services-proxy-suite-amneziawg-profiles-name-endpoint) - [interfaceName](#services-proxy-suite-amneziawg-profiles-name-interfacename) - [settings](#services-proxy-suite-amneziawg-profiles-name-settings) - [addresses](#services-proxy-suite-amneziawg-profiles-name-settings-addresses) @@ -189,6 +190,26 @@ null or string null ``` + +## services\.proxy-suite\.amneziaWg\.profiles\.\\.endpoint + +host:port (IPv6 in brackets) that replaces the first peer’s Endpoint when the profile is prepared\. + +*Type:* +null or string matching the pattern (\\\[\[0-9A-Fa-f:\.]+]|\[^]:\[]+):\[0-9]+ + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"162.159.192.1:500" +``` + ## services\.proxy-suite\.amneziaWg\.profiles\.\\.interfaceName diff --git a/docs/options/index.md b/docs/options/index.md index 6528c65..3a33574 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -132,7 +132,7 @@ services.proxy-suite = { local = { address = "1.1.1.1"; port = 53; - type = "udp"; + type = "tcp"; }; remote = { address = "1.1.1.1"; @@ -301,6 +301,7 @@ services.proxy-suite = { asOutbound = null; configFile = null; enable = false; + endpoint = null; generatorUrl = null; }; zapret = { diff --git a/docs/options/proxy.md b/docs/options/proxy.md index 2bc46bd..9ce2c64 100644 --- a/docs/options/proxy.md +++ b/docs/options/proxy.md @@ -389,7 +389,9 @@ string ## services\.proxy-suite\.proxy\.dns\.local -Resolver for direct traffic and the default domain resolver\. Goes through the proxy in global TUN mode\. +Resolver for direct traffic and the default domain resolver\. Goes through the proxy in +global TUN mode\. TCP by default: plain UDP queries to well-known resolvers are often +answered by the ISP’s DPI instead, which breaks blocked names routed direct to zapret\. *Type:* submodule @@ -400,7 +402,7 @@ submodule { address = "1.1.1.1"; port = 53; - type = "udp"; + type = "tcp"; } ``` @@ -408,8 +410,9 @@ submodule ```nix { - address = "9.9.9.9"; - type = "tcp"; + address = "1.1.1.1"; + port = 853; + type = "tls"; } ``` diff --git a/docs/options/warp.md b/docs/options/warp.md index 5be6bc9..1d0fc73 100644 --- a/docs/options/warp.md +++ b/docs/options/warp.md @@ -9,6 +9,7 @@ Part of the [proxy-suite options reference](./index.md). - [asAmneziaWg](#services-proxy-suite-warp-asamneziawg) - [asOutbound](#services-proxy-suite-warp-asoutbound) - [configFile](#services-proxy-suite-warp-configfile) + - [endpoint](#services-proxy-suite-warp-endpoint) - [generatorUrl](#services-proxy-suite-warp-generatorurl) @@ -95,6 +96,29 @@ null "/run/secrets/wgcf-profile.conf" ``` + +## services\.proxy-suite\.warp\.endpoint + +host:port that replaces the profile’s Endpoint (IPv6 in brackets), for when the default +engage\.cloudflareclient\.com:2408 is blocked: another Cloudflare address, another port WARP +answers on (500, 1701, 4500, …), or a relay\. Applied in every mode when the tunnel or +AmneziaWG profile starts; the profile file itself is left as is\. + +*Type:* +null or string matching the pattern (\\\[\[0-9A-Fa-f:\.]+]|\[^]:\[]+):\[0-9]+ + +*Default:* + +```nix +null +``` + +*Example:* + +```nix +"162.159.192.1:500" +``` + ## services\.proxy-suite\.warp\.generatorUrl diff --git a/flake.nix b/flake.nix index 9aee9a5..9cb4e7d 100644 --- a/flake.nix +++ b/flake.nix @@ -93,6 +93,9 @@ mkProxySuiteTray = throw "mkProxySuiteTray was replaced by Proxy Suite GUI: set services.proxy-suite.gui.enable"; }; + # `nix fmt`; the nix-format check holds the tree to it. + formatter = forAll (system: (pkgsFor system).nixfmt-tree); + packages = forAll ( system: let diff --git a/modules/proxy-suite/amnezia-wg.nix b/modules/proxy-suite/amnezia-wg.nix index b206f8a..fb0c07a 100644 --- a/modules/proxy-suite/amnezia-wg.nix +++ b/modules/proxy-suite/amnezia-wg.nix @@ -80,6 +80,7 @@ let allowConfigHooks = profile.allowConfigHooks; vpnContainer = profile.vpnContainer; } + // lib.optionalAttrs (profile.endpoint != null) { inherit (profile) endpoint; } // source profile ) ); @@ -145,7 +146,9 @@ let 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" + lib.optionalString ( + derived.killSwitchEnabled && profile.asOutbound == null + ) " --fwmark ${toString awgGlobalFwmark} --resolve-endpoints" } ''; @@ -169,7 +172,11 @@ let configPath = runtimeConfig name profile; prepare = pkgs.writeShellScript "proxy-suite-awg" '' set -euo pipefail - ${lib.optionalString (derived.killSwitchEnabled && !outbound) "${pkgs.util-linux}/bin/unshare --mount ${ownLookups} "}${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 diff --git a/modules/proxy-suite/options/lib.nix b/modules/proxy-suite/options/lib.nix index eeb5bef..407e2d3 100644 --- a/modules/proxy-suite/options/lib.nix +++ b/modules/proxy-suite/options/lib.nix @@ -18,6 +18,15 @@ in default = null; inherit description example; }; + # A WireGuard peer's host:port, IPv6 in brackets. + endpoint = + description: + mkOption { + type = types.nullOr (types.strMatching "(\\[[0-9A-Fa-f:.]+]|[^]:[]+):[0-9]+"); + default = null; + example = "162.159.192.1:500"; + inherit description; + }; bool = default: description: mkOption { diff --git a/modules/proxy-suite/options/proxy-dns.nix b/modules/proxy-suite/options/proxy-dns.nix index 1af2fea..6660a86 100644 --- a/modules/proxy-suite/options/proxy-dns.nix +++ b/modules/proxy-suite/options/proxy-dns.nix @@ -13,11 +13,21 @@ in options.services.proxy-suite.proxy.dns = { local = mkOption { type = t.dnsUpstreamType; - default = cloudflare; - description = "Resolver for direct traffic and the default domain resolver. Goes through the proxy in global TUN mode."; - example = { + # TCP: DPI boxes answer plain UDP queries to well-known resolvers themselves, with + # NXDOMAIN or a stub address for blocked names, so direct traffic (zapret's + # included) dials nothing. Not tls, which pure XRay lacks. + default = cloudflare // { type = "tcp"; - address = "9.9.9.9"; + }; + description = '' + Resolver for direct traffic and the default domain resolver. Goes through the proxy in + global TUN mode. TCP by default: plain UDP queries to well-known resolvers are often + answered by the ISP's DPI instead, which breaks blocked names routed direct to zapret. + ''; + example = { + type = "tls"; + address = "1.1.1.1"; + port = 853; }; }; diff --git a/modules/proxy-suite/options/types/amnezia-wg.nix b/modules/proxy-suite/options/types/amnezia-wg.nix index 9d84b24..ac38060 100644 --- a/modules/proxy-suite/options/types/amnezia-wg.nix +++ b/modules/proxy-suite/options/types/amnezia-wg.nix @@ -3,6 +3,7 @@ let inherit (lib) mkOption types; + inherit (import ../lib.nix { inherit lib; }) endpoint; optionalString = types.nullOr types.str; optionalUnsigned = types.nullOr types.ints.unsigned; rangeValue = types.oneOf [ @@ -206,6 +207,7 @@ let Either way the tunnel itself reaches the peer over the uplink, past TUN and TProxy. ''; }; + endpoint = endpoint "host:port (IPv6 in brackets) that replaces the first peer's Endpoint when the profile is prepared."; allowConfigHooks = mkOption { type = types.bool; default = false; diff --git a/modules/proxy-suite/options/warp.nix b/modules/proxy-suite/options/warp.nix index ec389ef..a491daf 100644 --- a/modules/proxy-suite/options/warp.nix +++ b/modules/proxy-suite/options/warp.nix @@ -2,6 +2,7 @@ let inherit (lib) mkEnableOption mkOption types; + inherit (import ./lib.nix { inherit lib; }) endpoint; in { options.services.proxy-suite.warp = { @@ -35,6 +36,13 @@ in example = "https://valokda-amnezia.vercel.app/api/warp?mode=awg2"; }; + endpoint = endpoint '' + host:port that replaces the profile's Endpoint (IPv6 in brackets), for when the default + engage.cloudflareclient.com:2408 is blocked: another Cloudflare address, another port WARP + answers on (500, 1701, 4500, ...), or a relay. Applied in every mode when the tunnel or + AmneziaWG profile starts; the profile file itself is left as is. + ''; + asOutbound = mkOption { type = types.nullOr ( types.enum [ diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index d92f1fd..5df884e 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -948,8 +948,7 @@ let (proxyEnabled && proxyCfg.listener.port == torCfg.socksPort) || (proxyInboundsEnabled && builtins.elem torCfg.socksPort derived.proxyInboundPorts) || builtins.elem torCfg.socksPort ( - builtins.attrValues constants.xrayDnsBridgePorts - ++ [ constants.outboundTestPort ] + builtins.attrValues constants.xrayDnsBridgePorts ++ [ constants.outboundTestPort ] ) ) ) diff --git a/modules/proxy-suite/tor.nix b/modules/proxy-suite/tor.nix index dd6e523..e10cd53 100644 --- a/modules/proxy-suite/tor.nix +++ b/modules/proxy-suite/tor.nix @@ -103,7 +103,9 @@ let umask 0077 torrc="$RUNTIME_DIRECTORY/torrc" - ${pkgs.coreutils}/bin/mkdir -p -m ${if controlGroup then "0750" else "0700"} "$RUNTIME_DIRECTORY/control" + ${pkgs.coreutils}/bin/mkdir -p -m ${ + if controlGroup then "0750" else "0700" + } "$RUNTIME_DIRECTORY/control" { cat <<'TORRC' ${staticConfig} diff --git a/modules/proxy-suite/warp.nix b/modules/proxy-suite/warp.nix index d5f7363..b23751b 100644 --- a/modules/proxy-suite/warp.nix +++ b/modules/proxy-suite/warp.nix @@ -94,6 +94,7 @@ in services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) { warp = { configFile = w.profilePath; + inherit (w) endpoint; asOutbound = lib.mkIf viaAmneziaWg w.asOutbound; }; }; @@ -111,7 +112,7 @@ in until [ -s "$profile" ]; do sleep 5; done fi ''; - inherit (w) tunnelPort directPort; + inherit (w) tunnelPort directPort endpoint; }; }) diff --git a/modules/proxy-suite/wg-tunnel.nix b/modules/proxy-suite/wg-tunnel.nix index 3985885..dd99eac 100644 --- a/modules/proxy-suite/wg-tunnel.nix +++ b/modules/proxy-suite/wg-tunnel.nix @@ -86,10 +86,13 @@ let tag, tunnelPort, directPort, + endpoint, }: { convert = '' - endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag}${markArg "--routing-mark"} < "$profile") + endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag}${markArg "--routing-mark"}${ + lib.optionalString (endpoint != null) " --endpoint ${lib.escapeShellArg endpoint}" + } < "$profile") (umask 027 && ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{ log: {level: "warn"}, dns: {servers: [ @@ -130,7 +133,8 @@ let }; # `profile` is a shell snippet, run as root on a privileged host, that sets $profile to - # the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort. + # the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort, + # and `endpoint`, a host:port in place of the profile's Endpoint. mkTunnel = { description, @@ -139,11 +143,17 @@ let profile, tunnelPort, directPort ? null, + endpoint ? null, engine ? "singBox", }: let chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) { - inherit tag tunnelPort directPort; + inherit + tag + tunnelPort + directPort + endpoint + ; }; tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" '' set -euo pipefail diff --git a/modules/proxy-suite/zapret2/runtime.nix b/modules/proxy-suite/zapret2/runtime.nix index d1ae66c..3815140 100644 --- a/modules/proxy-suite/zapret2/runtime.nix +++ b/modules/proxy-suite/zapret2/runtime.nix @@ -67,11 +67,13 @@ let zapret2Cfg.excludeDomains != [ ] ) "--hostlist-exclude-domains=${lib.concatStringsSep "," zapret2Cfg.excludeDomains}"; + # lib.trim drops string context: without it the source's list paths are no build input, + # so lazy trees never materialize them and the closure omits them. renderProfile = profile: lib.replaceStrings hostlistMarkers (map ( marker: marker + withSpaces staticListArgs - ) hostlistMarkers) (lib.trim profile); + ) hostlistMarkers) (lib.addContextFrom profile (lib.trim profile)); z2kGenerated = sources.z2k.mkProfiles { hostlistSuffix = withSpaces staticListArgs; diff --git a/nix/checks/_groups-tmp.nix b/nix/checks/_groups-tmp.nix deleted file mode 100644 index c45f9bf..0000000 --- a/nix/checks/_groups-tmp.nix +++ /dev/null @@ -1,342 +0,0 @@ -{ - 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/core-proxy/routing-dns.nix b/nix/checks/core-proxy/routing-dns.nix index b49f106..83e35c7 100644 --- a/nix/checks/core-proxy/routing-dns.nix +++ b/nix/checks/core-proxy/routing-dns.nix @@ -32,7 +32,7 @@ in localDns = dnsServerByTag ruDefaultConfig "local"; remoteDns = dnsServerByTag ruDefaultConfig "remote"; in - assert localDns.type == "udp"; + assert localDns.type == "tcp"; assert localDns.server == "1.1.1.1"; assert localDns.server_port == 53; assert !(localDns ? detour); diff --git a/nix/checks/per-app-routing-zapret.nix b/nix/checks/per-app-routing-zapret.nix index 2339b34..ae4d530 100644 --- a/nix/checks/per-app-routing-zapret.nix +++ b/nix/checks/per-app-routing-zapret.nix @@ -189,10 +189,10 @@ in perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "proxy-suite-per-app-zapret"; assert perAppRoutingZapretWithoutGlobalFixture.config.systemd.services - ? "proxy-suite-per-app-zapret-user@"; + ? "proxy-suite-per-app-zapret-user@"; assert perAppRoutingZapretWithoutGlobalFixture.config.systemd.user.services - ? "proxy-suite-per-app-zapret-anchor"; + ? "proxy-suite-per-app-zapret-anchor"; assert !(perAppRoutingZapretWithoutGlobalFixture.config.systemd.services ? "proxy-suite-zapret"); assert builtins.length perAppRoutingZapretWithoutGlobalProfiles == 2; assert builtins.any ( diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index 6893187..b3f93cb 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -591,7 +591,12 @@ let (ok ((ruleByTag exitConfig "inbound-final").outboundTag == "direct")) # Safety rules come first. - (ok (lib.take 2 (ruleTags relayConfig) == [ "inbound-stats-api" "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" ])) diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index e0ddb2c..8fe56d5 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -57,6 +57,37 @@ in touch "$out" ''; + # The tree as `nix fmt` leaves it. + nix-format = + pkgs.runCommand "proxy-suite-nix-format-check" { nativeBuildInputs = [ pkgs.nixfmt ]; } + '' + cd ${ + pkgs.lib.fileset.toSource { + root = ../..; + fileset = pkgs.lib.fileset.fileFilter (file: file.hasExt "nix") ../..; + } + } + find . -name '*.nix' -print0 | xargs -0 nixfmt --check + touch "$out" + ''; + + # Pyflakes and bugbear over every script and front end, as ruff.toml configures them. + python-lint = + pkgs.runCommand "proxy-suite-python-lint-check" { nativeBuildInputs = [ pkgs.ruff ]; } + '' + cd ${ + pkgs.lib.fileset.toSource { + root = ../..; + fileset = pkgs.lib.fileset.unions [ + ../../ruff.toml + (pkgs.lib.fileset.fileFilter (file: file.hasExt "py") ../..) + ]; + } + } + ruff check --no-cache . + touch "$out" + ''; + proxy-ctl-subscription-list = pkgs.runCommand "proxy-suite-proxy-ctl-subscription-list-check" { diff --git a/nix/checks/warp.nix b/nix/checks/warp.nix index 3a3dc7b..22d5f4c 100644 --- a/nix/checks/warp.nix +++ b/nix/checks/warp.nix @@ -67,6 +67,10 @@ let fixture: generated.readDerivation fixture.config.systemd.services."proxy-suite-warp".serviceConfig.ExecStart; autoRegister = registerOf auto; + endpointed = mkFixture "sing-box" { + asOutbound = "singBox"; + endpoint = "[2606:4700:d0::a29f:c001]:500"; + }; generatorRegister = registerOf generator; amneziaWg = mkProxySuite { @@ -79,7 +83,29 @@ let }; }; + amneziaWgEndpoint = mkProxySuite { + enable = true; + amneziaWg.enable = true; + warp = { + enable = true; + configFile = profile; + asAmneziaWg = true; + endpoint = "162.159.192.1:500"; + }; + }; + invalidAssertions = mkFailingAssertions mkBadProxySuiteFixture [ + # An IPv6 endpoint without brackets. + { + enable = true; + warp = { + enable = true; + configFile = profile; + asOutbound = "singBox"; + endpoint = "2606:4700:d0::a29f:c001:500"; + }; + proxy.enable = true; + } # Enabled but used for nothing. { enable = true; @@ -182,7 +208,7 @@ in # The resolver comes from proxy.dns.local; sing-box's "local" server fails behind resolved. ( assert - hasInfix ''{"server":"1.1.1.1","server_port":53,"tag":"local","type":"udp"}'' singBoxTunnel + hasInfix ''{"server":"1.1.1.1","server_port":53,"tag":"local","type":"tcp"}'' singBoxTunnel && !(hasInfix ''type: "local"'' singBoxTunnel); true ) @@ -242,6 +268,20 @@ in assert !(amneziaWg.config.systemd.services ? "proxy-suite-warp-tunnel"); true ) + # endpoint replaces the profile's Endpoint at conversion; the sing-box tunnel gets it quoted. + ( + assert + hasInfix "--endpoint '[2606:4700:d0::a29f:c001]:500' < \"$profile\"" (tunnelOf endpointed) + && !(hasInfix "--endpoint" singBoxTunnel); + true + ) + ( + assert + amneziaWgEndpoint.config.services.proxy-suite.amneziaWg.profiles.warp.endpoint + == "162.159.192.1:500" + && amneziaWg.config.services.proxy-suite.amneziaWg.profiles.warp.endpoint == null; + true + ) ] ++ invalidAssertions; } diff --git a/nix/checks/zapret2.nix b/nix/checks/zapret2.nix index d852c9f..b0b166a 100644 --- a/nix/checks/zapret2.nix +++ b/nix/checks/zapret2.nix @@ -102,8 +102,7 @@ in assert !(zapretDiscordYoutubeGlobal.config.systemd.services ? proxy-suite-zapret2-cutoff); assert (proxyCtlEnv zapret2Global).ZAPRET_CUTOFF_ENABLED == "1"; assert - envValue zapret2Z2k globalService "Z2K_TCP16_ASN=" - == "/var/lib/proxy-suite/zapret2/cutoff/asn.txt"; + 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 @@ -242,6 +241,15 @@ in test "$(grep -c 'mark and 0x10000000 != 0 return' "$hook")" = 4 grep -q 'nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and 0x10000000 != 0 return' "$hook" + # --- store paths ------------------------------------------------------ + # Every path a config names is a build input. One that lost its string context + # is missing from the closure, and from this sandbox under lazy trees. + for config in ${globalRuntime}/config ${perAppRuntime}/config ${z2kRuntime}/config; do + for path in $(grep -oE '/nix/store/[a-z0-9]{32}-[^ :"/]+' "$config" | sort -u); do + test -e "$path" || { echo "$config names $path, which is not in the sandbox" >&2; exit 1; } + done + done + # --- the command line nfqws2 receives --- # Expand with zapret2's list.sh and let nfqws2 validate the result, # Lua included; the strategy state layer gets a writable directory. diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index d5613ed..9eeeed6 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -690,7 +690,7 @@ def _unit_states(units): return {} _, out = systemctl("show", "--property=Id,LoadState,ActiveState", "--", *units, capture=True, quiet=True) states = {} - for unit, block in zip(units, out.strip().split("\n\n")): + for unit, block in zip(units, out.strip().split("\n\n"), strict=False): props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line) if props.get("LoadState") not in (None, "not-found"): states[unit] = props.get("ActiveState", "unknown") @@ -1605,7 +1605,6 @@ def cmd_outbound_disable(tag="", *_): if os.path.exists(marker) and tag in _outbound_disabled(): print(f"Already disabled: {tag}") return - pinned = _s(inventory.get("pinned") or "") excluded = set(inventory.get("excluded") or []) # With none left to pick the proxy would not start, pinned or not: an unpin falls back to selection. if [t for t in _outbound_tags() if t not in excluded] == [tag]: @@ -2104,7 +2103,7 @@ def cmd_proxy_probe(*args): "exit": w["exit"] or None, "direct": w["direct"], "proxy": w["via"], - "exits": [dict(zip(("tag", "path", "result", "judgement"), row), block=_probe_field(row[2], 5)) for row in w["rows"]], + "exits": [dict(zip(("tag", "path", "result", "judgement"), row, strict=False), block=_probe_field(row[2], 5)) for row in w["rows"]], } print(json.dumps(out, separators=(",", ":"), ensure_ascii=False)) return diff --git a/pkgs/proxy-ctl/proxy_tui.py b/pkgs/proxy-ctl/proxy_tui.py index 275fb2a..848a36e 100644 --- a/pkgs/proxy-ctl/proxy_tui.py +++ b/pkgs/proxy-ctl/proxy_tui.py @@ -13,7 +13,7 @@ import tempfile import traceback from rich.text import Text -from textual import events, work +from textual import work from textual.app import App, ComposeResult from textual.binding import Binding from textual.containers import Container, Vertical diff --git a/pkgs/proxy-ctl/test_proxy_tui.py b/pkgs/proxy-ctl/test_proxy_tui.py index 1defae8..5680ff3 100644 --- a/pkgs/proxy-ctl/test_proxy_tui.py +++ b/pkgs/proxy-ctl/test_proxy_tui.py @@ -9,6 +9,8 @@ import tempfile import unittest from unittest import mock +from textual import events + import proxy_ctl as ctl import proxy_model as model import proxy_tui as tui @@ -129,11 +131,11 @@ class TuiTest(unittest.TestCase): await self.settle(app, pilot) app.main.query_one("#tabs", tui.TabbedContent).active = "outbounds" await self.settle(app, pilot) - app.post_message(tui.events.Paste("vless://u@de.test:443#DE")) + app.post_message(events.Paste("vless://u@de.test:443#DE")) await pilot.pause() self.assertEqual(self.ran.pop(), ["proxy", "outbounds", "add", "vless://u@de.test:443#DE"]) # Whatever else was in the clipboard runs nothing, and the bar says why. - app.post_message(tui.events.Paste("ftp://a.test/x")) + app.post_message(events.Paste("ftp://a.test/x")) await pilot.pause() self.assertEqual(self.ran, []) self.assertIn("ftp:// link", str(app.main.query_one("#feedback").content)) @@ -162,7 +164,7 @@ class TuiTest(unittest.TestCase): self.assertEqual(app.focused.id, "services-table") # The terminal losing focus leaves the TUI as it is. - app.post_message(tui.events.AppBlur()) + app.post_message(events.AppBlur()) await pilot.pause() self.assertEqual((app.app_focus, app.focused.id), (True, "services-table")) diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..df831e5 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,3 @@ +# The python-lint check (nix/checks/repo.nix): real errors only, no style. +[lint] +select = ["F", "E9", "B"] diff --git a/scripts/amneziawg_config.py b/scripts/amneziawg_config.py index 45bdd5e..f785ce3 100644 --- a/scripts/amneziawg_config.py +++ b/scripts/amneziawg_config.py @@ -390,6 +390,14 @@ def resolve_endpoints(config: str) -> str: return ENDPOINT_LINE.sub(resolve, config) +def override_endpoint(config: str, endpoint: str) -> str: + """The first peer's Endpoint replaced by endpoint (host:port, IPv6 in brackets).""" + config, count = ENDPOINT_LINE.subn(lambda match: f"{match.group(1)}{endpoint}", config, count=1) + if not count: + raise ConfigError("configuration has no Endpoint to override") + return config + + # Read once by wireproxy: repeated lines are joined into one list. WIREPROXY_LIST_KEYS = {"address", "dns", "allowedips"} # wg-quick's, which wireproxy has no use for. @@ -722,6 +730,8 @@ def prepare(manifest: dict[str, Any]) -> str: else: raise ConfigError(f"unsupported manifest kind '{kind}'") config = _apply_awg3_mtu_default(config) + if manifest.get("endpoint") is not None: + config = override_endpoint(config, str(manifest["endpoint"])) validate_config(config, bool(manifest.get("allowConfigHooks", False))) return config diff --git a/scripts/patch-zapret-config.py b/scripts/patch-zapret-config.py index 76d4397..09fb2d3 100644 --- a/scripts/patch-zapret-config.py +++ b/scripts/patch-zapret-config.py @@ -346,4 +346,4 @@ if __name__ == "__main__": raise SystemExit(main()) except ValueError as exc: print(f"error: {exc}", file=sys.stderr) - raise SystemExit(1) + raise SystemExit(1) from None diff --git a/scripts/test-amneziawg-config.py b/scripts/test-amneziawg-config.py index ea521e9..8a696aa 100644 --- a/scripts/test-amneziawg-config.py +++ b/scripts/test-amneziawg-config.py @@ -474,6 +474,26 @@ class AmneziaWgConfigTests(unittest.TestCase): "[Peer]\nEndpoint = [2001:db8::7]:51820\n[Peer]\nEndpoint = 192.0.2.1:1\nendpoint = [2001:db8::1]:2\n[Peer]\nEndpoint = gone.invalid:3\n", ) + def test_endpoint_override(self): + # Only the first peer's Endpoint; a config without one cannot be overridden. + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "warp.conf" + source.write_text( + BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1") + + "\n[Peer]\nPublicKey = other\nAllowedIPs = 10.0.0.0/8\nEndpoint = second.example:1\n" + ) + config = prepare({"kind": "configFile", "path": str(source), "endpoint": "[2001:db8::1]:500"}) + self.assertEqual( + amneziawg_config.section_values(config, "peer", "endpoint"), + ["[2001:db8::1]:500", "second.example:1"], + ) + rendered = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700", 2) + self.assertIn("[2001:db8::1]:500", amneziawg_config.section_values(rendered, "peer", "endpoint")) + self.assertIn("Endpoint = [2001:db8::1]:500", amneziawg_config.as_outbound(config, 2)) + source.write_text("[Interface]\nPrivateKey = private\nAddress = 10.8.0.2/32\n[Peer]\nPublicKey = public\nAllowedIPs = 0.0.0.0/0\n") + with self.assertRaises(ConfigError): + prepare({"kind": "configFile", "path": str(source), "endpoint": "192.0.2.1:500"}) + def test_global_render_pins_the_fwmark(self): # The kill switch knows the tunnel's own packets by it; one set in the file is replaced. with tempfile.TemporaryDirectory() as directory: diff --git a/scripts/test-fetch-subscription.py b/scripts/test-fetch-subscription.py index 8af0ded..3748499 100644 --- a/scripts/test-fetch-subscription.py +++ b/scripts/test-fetch-subscription.py @@ -92,8 +92,6 @@ class FetchSubscriptionTests(unittest.TestCase): obs = run_fetcher(payload, tag_prefix="sub") tag = obs[0]["tag"] # Tag must contain only safe characters - import re - self.assertRegex(tag, r"^[a-zA-Z0-9_/\-]+$") def test_non_latin_remark_kept_in_tag(self): diff --git a/scripts/test-warp-outbound.py b/scripts/test-warp-outbound.py index 8023ddd..ee6c421 100644 --- a/scripts/test-warp-outbound.py +++ b/scripts/test-warp-outbound.py @@ -33,6 +33,14 @@ class WarpOutboundTest(unittest.TestCase): self.assertEqual((ob["peers"][0]["address"], ob["peers"][0]["port"]), ("2606:4700:d0::a29f:c001", 500)) self.assertNotIn("routing_mark", ob) + def test_endpoint_override(self): + peer = build(WGCF, "warp", None, "162.159.192.1:500")["peers"][0] + self.assertEqual((peer["address"], peer["port"]), ("162.159.192.1", 500)) + peer = build(WGCF, "warp", None, "[2606:4700:d0::a29f:c001]:4500")["peers"][0] + self.assertEqual((peer["address"], peer["port"]), ("2606:4700:d0::a29f:c001", 4500)) + with self.assertRaises(ConfigError): + build(WGCF, "warp", None, "162.159.192.1") + def test_awg3_keepalive_range(self): # Generator AWG 3 profiles range the keepalive; sing-box gets the lower bound. ob = build(WGCF.replace("[Peer]", "RekeyAfterTime = 100-120\n[Peer]\nPersistentKeepalive = 25-35"), "warp", None) diff --git a/scripts/warp_outbound.py b/scripts/warp_outbound.py index 8afe6ea..840c08f 100644 --- a/scripts/warp_outbound.py +++ b/scripts/warp_outbound.py @@ -35,9 +35,9 @@ def split_endpoint(endpoint: str) -> tuple[str, int]: return host.strip("[]"), int(port) -def build(text: str, tag: str, routing_mark: int | None) -> dict[str, Any]: +def build(text: str, tag: str, routing_mark: int | None, endpoint: str | None = None) -> dict[str, Any]: interface, peer = parse_conf(text) - host, port = split_endpoint(peer["endpoint"]) + host, port = split_endpoint(endpoint or peer["endpoint"]) sb_peer: dict[str, Any] = { "address": host, "port": port, @@ -74,10 +74,11 @@ def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--tag", default="warp") parser.add_argument("--routing-mark", type=int) + parser.add_argument("--endpoint", help="host:port in place of the profile's Endpoint") args = parser.parse_args() text = sys.stdin.read() try: - print(json.dumps(build(text, args.tag, args.routing_mark))) + print(json.dumps(build(text, args.tag, args.routing_mark, args.endpoint))) except ValueError as error: print(f"proxy-suite: {args.tag}: {error}", file=sys.stderr) return 1