diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index b0499b2..5cbecaa 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -66,6 +66,8 @@ let tunAddress ? globalTun.address, tunMtu ? globalTun.mtu, tunAutoRoute ? true, + tunAutoRouteTableIndex ? 2022, + tunAutoRouteRuleIndex ? 9000, tunAutoRedirect ? true, tunStrictRoute ? true, forceLocalDnsViaProxy ? false, @@ -95,17 +97,25 @@ let listen = "127.0.0.1"; listen_port = globalTproxy.port; } - ++ lib.optional enableTun { - type = "tun"; - tag = "tun-in"; - interface_name = tunInterface; - address = [ tunAddress ]; - mtu = tunMtu; - auto_route = tunAutoRoute; - auto_redirect = tunAutoRedirect; - strict_route = tunStrictRoute; - stack = "mixed"; - }; + ++ lib.optional enableTun ( + { + type = "tun"; + tag = "tun-in"; + interface_name = tunInterface; + address = [ tunAddress ]; + mtu = tunMtu; + auto_route = tunAutoRoute; + auto_redirect = tunAutoRedirect; + strict_route = tunStrictRoute; + stack = "mixed"; + } + // lib.optionalAttrs tunAutoRoute { + # Keep sing-box auto_route indexes explicit so service cleanup can + # reliably remove stale policy-routing state after unclean stops. + iproute2_table_index = tunAutoRouteTableIndex; + iproute2_rule_index = tunAutoRouteRuleIndex; + } + ); # proxy outbound(s) are prepended at runtime by the start script outbounds = [ diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index a08b5c9..77b0a07 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -36,6 +36,8 @@ let perAppZapretCfg ; + globalTunAutoRouteTable = 2022; + featureAssertions = [ (requireAvailable singBoxCfg.enable ( singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ] @@ -123,6 +125,24 @@ let ]; collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [ + { + condition = globalTun.enable && perAppRoutingTun.enable; + left = globalTun.interface; + right = perAppRoutingTun.interface; + message = "proxy-suite: singBox.tun.interface and singBox.tun.perApp.interface must differ"; + } + { + condition = globalTun.enable && perAppRoutingTun.enable; + left = globalTun.address; + right = perAppRoutingTun.address; + message = "proxy-suite: singBox.tun.address and singBox.tun.perApp.address must differ"; + } + { + condition = globalTun.enable && perAppRoutingTun.enable; + left = perAppRoutingTun.routeTable; + right = globalTunAutoRouteTable; + message = "proxy-suite: singBox.tun.perApp.routeTable must differ from the global TUN auto-route table 2022"; + } { condition = perAppRoutingTun.enable && globalTproxy.enable; left = perAppRoutingTun.fwmark; @@ -202,6 +222,64 @@ let 134217728 ]; + positiveNumberAssertions = map (item: mkAssertion (!item.condition || item.value > 0) item.message) [ + { + condition = globalTun.enable; + value = globalTun.mtu; + message = "proxy-suite: singBox.tun.mtu must be greater than zero"; + } + { + condition = perAppRoutingTun.enable; + value = perAppRoutingTun.mtu; + message = "proxy-suite: singBox.tun.perApp.mtu must be greater than zero"; + } + { + condition = globalTproxy.enable; + value = globalTproxy.fwmark; + message = "proxy-suite: singBox.tproxy.fwmark must be greater than zero"; + } + { + condition = globalTproxy.enable; + value = globalTproxy.proxyMark; + message = "proxy-suite: singBox.tproxy.proxyMark must be greater than zero"; + } + { + condition = globalTproxy.enable; + value = globalTproxy.routeTable; + message = "proxy-suite: singBox.tproxy.routeTable must be greater than zero"; + } + { + condition = perAppRoutingTun.enable; + value = perAppRoutingTun.fwmark; + message = "proxy-suite: singBox.tun.perApp.fwmark must be greater than zero"; + } + { + condition = perAppRoutingTun.enable; + value = perAppRoutingTun.routeTable; + message = "proxy-suite: singBox.tun.perApp.routeTable must be greater than zero"; + } + { + condition = perAppRoutingTproxy.enable; + value = perAppRoutingTproxy.fwmark; + message = "proxy-suite: singBox.tproxy.perApp.fwmark must be greater than zero"; + } + { + condition = perAppRoutingTproxy.enable; + value = perAppRoutingTproxy.routeTable; + message = "proxy-suite: singBox.tproxy.perApp.routeTable must be greater than zero"; + } + { + condition = perAppZapretCfg.enable; + value = perAppZapretCfg.filterMark; + message = "proxy-suite: zapret.perApp.filterMark must be greater than zero"; + } + { + condition = perAppZapretCfg.enable; + value = perAppZapretCfg.qnum; + message = "proxy-suite: zapret.perApp.qnum must be greater than zero"; + } + ]; + localProxyAuthCfg = singBoxCfg.auth; localProxyAuthUsed = localProxyAuthCfg.username != null @@ -286,6 +364,7 @@ in featureAssertions ++ perAppRoutingAssertions ++ collisionAssertions +++ positiveNumberAssertions ++ localProxyAuthAssertions ++ forbiddenValueAssertions ++ secretAssertions diff --git a/modules/proxy-suite/service/builders.nix b/modules/proxy-suite/service/builders.nix index 14c18ff..5597aeb 100644 --- a/modules/proxy-suite/service/builders.nix +++ b/modules/proxy-suite/service/builders.nix @@ -46,6 +46,7 @@ rec { wants ? [ ], requires ? [ ], conflicts ? [ ], + execStartPre ? null, execStartPost ? null, execStopPost ? null, extraServiceConfig ? { }, @@ -70,6 +71,7 @@ rec { RuntimeDirectory = runtimeDirectory; } // lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; } + // lib.optionalAttrs (execStartPre != null) { ExecStartPre = execStartPre; } // lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; } // lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; } // extraServiceConfig; diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 95300fc..6cf9bdc 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -85,17 +85,47 @@ let singBoxCfg.auth.username != null && (singBoxCfg.auth.password != null || singBoxCfg.auth.passwordFile != null); + # Must match the explicit iproute2_* indexes written to the global TUN + # sing-box template in config.nix. + tunAutoRouteTableIndex = 2022; + tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" '' + set -euo pipefail + + # Start from a clean policy-routing state. `ip rule add` permits duplicate + # rules on some iproute2 versions, and a stale rule can keep packets routed + # into a dead local table after a failed restart. ${nft} delete table ip singbox 2>/dev/null || true + while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done + ${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true + ${nft} -f ${nftablesRulesFile} - ${ip} route add local default dev lo table ${toString globalTproxy.routeTable} + ${ip} route replace local default dev lo table ${toString globalTproxy.routeTable} ${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} ''; tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" '' + set +e + ${nft} delete table ip singbox 2>/dev/null || true + while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done ${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true - ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null || true + ''; + + tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" '' + set +e + + # sing-box normally removes these on graceful shutdown, but stale + # auto_route/auto_redirect state leaves the host routing through a dead TUN + # interface after `proxy-ctl tun off` or an unclean service stop. + ${nft} delete table inet sing-box 2>/dev/null || true + + while ${ip} -4 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done + while ${ip} -6 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done + ${ip} -4 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true + ${ip} -6 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true + + ${ip} link del dev ${lib.escapeShellArg globalTun.interface} 2>/dev/null || true ''; systemServiceEntries = [ @@ -139,7 +169,9 @@ let wants = [ "network-online.target" ]; wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ]; conflicts = [ "${serviceNames.tproxy}.service" ]; + execStartPre = tunCleanupScript; execStart = scripts.startTun; + execStopPost = tunCleanupScript; runtimeDirectory = serviceNames.tun; stateDirectory = "proxy-suite"; }; @@ -151,6 +183,7 @@ let description = "sing-box per-app-routing TUN backend"; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; + execStartPre = perAppRouting.perAppTunDownScript; execStart = scripts.startPerAppTun; execStartPost = perAppRouting.perAppTunUpScript; execStopPost = perAppRouting.perAppTunDownScript; @@ -264,9 +297,14 @@ in { environment.systemPackages = [ control.proxyCtl ]; - # nftables must be on for TProxy to work. + # nftables must be on for transparent routing backends. Global TUN uses + # sing-box auto_redirect, which programs an `inet sing-box` nftables table. networking.nftables.enable = lib.mkIf ( - globalTproxy.enable || perAppRoutingTun.enable || perAppRoutingTproxy.enable || perAppZapretEnabled + globalTun.enable + || globalTproxy.enable + || perAppRoutingTun.enable + || perAppRoutingTproxy.enable + || perAppZapretEnabled ) (lib.mkDefault true); users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) { diff --git a/modules/proxy-suite/service/per-app-routing.nix b/modules/proxy-suite/service/per-app-routing.nix index 317de7c..099347d 100644 --- a/modules/proxy-suite/service/per-app-routing.nix +++ b/modules/proxy-suite/service/per-app-routing.nix @@ -120,25 +120,33 @@ let ''; perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" '' - set -euo pipefail + set +e + + # Best-effort cleanup for graceful stops and for unclean previous exits. ${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true + while ${ip} rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done ${ip} route del default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true - ${ip} rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true + ${ip} link del dev ${lib.escapeShellArg perAppRoutingTun.interface} 2>/dev/null || true ''; perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" '' set -euo pipefail + ${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true + while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done + ${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true + ${nft} -f ${perAppTproxyRulesFile} ${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable} - ${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true + ${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} ''; perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" '' - set -euo pipefail + set +e + ${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true + while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done ${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true - ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true ''; # Generate a "start" script that adds a per-user cgroup nftables mark rule. diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index c96c670..5e9c541 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -23,6 +23,7 @@ let globalTproxy = singBoxCfg.tproxy; + systemctl = "${pkgs.systemd}/bin/systemctl"; localProxyAuth = singBoxCfg.auth; localProxyAuthEnabled = localProxyAuth.username != null @@ -139,6 +140,13 @@ let sub: mkSubscriptionBlock sub routingMark ) singBoxCfg.subscriptions; + requireOutboundsBlock = '' + if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then + echo "proxy-suite: no proxy outbounds are available; check static outbound definitions and subscription caches" >&2 + exit 1 + fi + ''; + wrapperBlock = if collapseNamedOutbounds then # When there are no static outbounds, subscription outbounds keep their @@ -173,7 +181,7 @@ let OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") ''; in - outboundBlocks + subscriptionBlocks + wrapperBlock; + outboundBlocks + subscriptionBlocks + requireOutboundsBlock + wrapperBlock; writeProxychainsConfigBlock = '' { @@ -195,6 +203,16 @@ let modeBaseline = if singBoxCfg.proxyByDefault then "blacklist" else "whitelist"; + restartActiveConfigConsumersBlock = lib.concatMapStrings (svc: '' + if ${systemctl} is-active --quiet ${svc}; then + ${systemctl} restart ${svc} + fi + '') [ + "proxy-suite-socks" + "proxy-suite-tun" + "proxy-suite-per-app-tun" + ]; + mkStartScript = { name, @@ -212,8 +230,9 @@ let ROUTE_MODE="" ROUTE_FINAL="" DNS_FINAL="" - ROUTE_RULES_JSON="" - CLEAR_DNS_RULES=0 + ROUTE_RULES_JSON='[]' + ROUTE_MODE_ACTIVE=false + CLEAR_DNS_RULES=false ${lib.optionalString enableLocalProxyAuth '' umask 077 LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" @@ -227,6 +246,7 @@ let blacklist) ROUTE_FINAL="proxy" DNS_FINAL="remote" + ROUTE_MODE_ACTIVE=true ROUTE_RULES_JSON=$(${jq} -c ' .common + (.custom | map(.entries) | add // []) @@ -240,6 +260,7 @@ let whitelist) ROUTE_FINAL="direct" DNS_FINAL="local" + ROUTE_MODE_ACTIVE=true ROUTE_RULES_JSON=$(${jq} -c ' .common + (.custom | map(.entries) | add // []) @@ -253,7 +274,8 @@ let all-proxy) ROUTE_FINAL="proxy" DNS_FINAL="remote" - CLEAR_DNS_RULES=1 + ROUTE_MODE_ACTIVE=true + CLEAR_DNS_RULES=true ROUTE_RULES_JSON=$(${jq} -c ' .common + (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // []) @@ -266,7 +288,8 @@ let all-bypass) ROUTE_FINAL="direct" DNS_FINAL="local" - CLEAR_DNS_RULES=1 + ROUTE_MODE_ACTIVE=true + CLEAR_DNS_RULES=true ROUTE_RULES_JSON=$(${jq} -c ' .common + (.custom | map(select(.category == "block") | .entries) | add // []) @@ -281,85 +304,30 @@ let ${mkOutboundScript routingMark} - ${ - if enableLocalProxyAuth then - '' - if [ -n "$ROUTE_MODE" ]; then - if [ "$CLEAR_DNS_RULES" -eq 1 ]; then - ${jq} \ - --argjson obs "$OUTBOUNDS_JSON" \ - --arg user ${lib.escapeShellArg localProxyAuth.username} \ - --arg password "$LOCAL_PROXY_PASSWORD" \ - --argjson route_rules "$ROUTE_RULES_JSON" \ - --arg route_final "$ROUTE_FINAL" \ - --arg dns_final "$DNS_FINAL" \ - '.outbounds = $obs + .outbounds - | (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] - | .route.rules = $route_rules - | .route.final = $route_final - | .dns.rules = [] - | .dns.final = $dns_final' \ - "${configFile}" > "$RUNTIME_DIR/config.json" - else - ${jq} \ - --argjson obs "$OUTBOUNDS_JSON" \ - --arg user ${lib.escapeShellArg localProxyAuth.username} \ - --arg password "$LOCAL_PROXY_PASSWORD" \ - --argjson route_rules "$ROUTE_RULES_JSON" \ - --arg route_final "$ROUTE_FINAL" \ - --arg dns_final "$DNS_FINAL" \ - '.outbounds = $obs + .outbounds - | (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] - | .route.rules = $route_rules - | .route.final = $route_final - | .dns.final = $dns_final' \ - "${configFile}" > "$RUNTIME_DIR/config.json" - fi - else - ${jq} \ - --argjson obs "$OUTBOUNDS_JSON" \ - --arg user ${lib.escapeShellArg localProxyAuth.username} \ - --arg password "$LOCAL_PROXY_PASSWORD" \ - '.outbounds = $obs + .outbounds - | (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]' \ - "${configFile}" > "$RUNTIME_DIR/config.json" - fi - chmod 600 "$RUNTIME_DIR/config.json" - '' - else - '' - if [ -n "$ROUTE_MODE" ]; then - if [ "$CLEAR_DNS_RULES" -eq 1 ]; then - ${jq} \ - --argjson obs "$OUTBOUNDS_JSON" \ - --argjson route_rules "$ROUTE_RULES_JSON" \ - --arg route_final "$ROUTE_FINAL" \ - --arg dns_final "$DNS_FINAL" \ - '.outbounds = $obs + .outbounds - | .route.rules = $route_rules - | .route.final = $route_final - | .dns.rules = [] - | .dns.final = $dns_final' \ - "${configFile}" > "$RUNTIME_DIR/config.json" - else - ${jq} \ - --argjson obs "$OUTBOUNDS_JSON" \ - --argjson route_rules "$ROUTE_RULES_JSON" \ - --arg route_final "$ROUTE_FINAL" \ - --arg dns_final "$DNS_FINAL" \ - '.outbounds = $obs + .outbounds - | .route.rules = $route_rules - | .route.final = $route_final - | .dns.final = $dns_final' \ - "${configFile}" > "$RUNTIME_DIR/config.json" - fi - else - ${jq} --argjson obs "$OUTBOUNDS_JSON" \ - '.outbounds = $obs + .outbounds' \ - "${configFile}" > "$RUNTIME_DIR/config.json" - fi - '' - } + ${jq} \ + --argjson obs "$OUTBOUNDS_JSON" \ + --argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \ + --arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \ + --arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \ + --argjson route_enabled "$ROUTE_MODE_ACTIVE" \ + --argjson route_rules "$ROUTE_RULES_JSON" \ + --arg route_final "$ROUTE_FINAL" \ + --arg dns_final "$DNS_FINAL" \ + --argjson clear_dns_rules "$CLEAR_DNS_RULES" \ + '.outbounds = $obs + .outbounds + | if $auth_enabled then + (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] + else . end + | if $route_enabled then + .route.rules = $route_rules + | .route.final = $route_final + | .dns.final = $dns_final + | if $clear_dns_rules then .dns.rules = [] else . end + else . end' \ + "${configFile}" > "$RUNTIME_DIR/config.json" + ${lib.optionalString enableLocalProxyAuth '' + chmod 600 "$RUNTIME_DIR/config.json" + ''} exec ${singBox} run -c "$RUNTIME_DIR/config.json" ''; @@ -410,26 +378,10 @@ let CACHE_DIR="${subscriptionCacheDir}" mkdir -p "$CACHE_DIR" FAILED=0 - SOCKS_WAS_ACTIVE=0 - TUN_WAS_ACTIVE=0 - PER_APP_TUN_WAS_ACTIVE=0 - - systemctl is-active --quiet proxy-suite-socks && SOCKS_WAS_ACTIVE=1 || true - systemctl is-active --quiet proxy-suite-tun && TUN_WAS_ACTIVE=1 || true - systemctl is-active --quiet proxy-suite-per-app-tun && PER_APP_TUN_WAS_ACTIVE=1 || true - ${lib.concatMapStrings mkSubscriptionFetchBlock singBoxCfg.subscriptions} if [ "$FAILED" -eq 0 ]; then - if [ "$SOCKS_WAS_ACTIVE" -eq 1 ]; then - systemctl restart proxy-suite-socks - fi - if [ "$TUN_WAS_ACTIVE" -eq 1 ]; then - systemctl restart proxy-suite-tun - fi - if [ "$PER_APP_TUN_WAS_ACTIVE" -eq 1 ]; then - systemctl restart proxy-suite-per-app-tun - fi + ${restartActiveConfigConsumersBlock} fi exit "$FAILED" ''; @@ -462,23 +414,7 @@ let printf '%s\n' "$mode" > "${routeModeStateFile}" fi - SOCKS_WAS_ACTIVE=0 - TUN_WAS_ACTIVE=0 - PER_APP_TUN_WAS_ACTIVE=0 - - systemctl is-active --quiet proxy-suite-socks && SOCKS_WAS_ACTIVE=1 || true - systemctl is-active --quiet proxy-suite-tun && TUN_WAS_ACTIVE=1 || true - systemctl is-active --quiet proxy-suite-per-app-tun && PER_APP_TUN_WAS_ACTIVE=1 || true - - if [ "$SOCKS_WAS_ACTIVE" -eq 1 ]; then - systemctl restart proxy-suite-socks - fi - if [ "$TUN_WAS_ACTIVE" -eq 1 ]; then - systemctl restart proxy-suite-tun - fi - if [ "$PER_APP_TUN_WAS_ACTIVE" -eq 1 ]; then - systemctl restart proxy-suite-per-app-tun - fi + ${restartActiveConfigConsumersBlock} ''; subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" ( diff --git a/modules/proxy-suite/zapret.nix b/modules/proxy-suite/zapret.nix index 3174920..14a221f 100644 --- a/modules/proxy-suite/zapret.nix +++ b/modules/proxy-suite/zapret.nix @@ -296,14 +296,22 @@ let ${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true ''; - exemptStart = lib.concatMapStrings (cidr: '' - ${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN + exemptStart = '' + set -euo pipefail + '' + + lib.concatMapStrings (cidr: '' + while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done + while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done + ${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN ${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN '') zapretCfg.cidrExemption.cidrs; - exemptStop = lib.concatMapStrings (cidr: '' - ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN || true - ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN || true + exemptStop = '' + set +e + '' + + lib.concatMapStrings (cidr: '' + while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done + while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done '') zapretCfg.cidrExemption.cidrs; in { diff --git a/nix/checks.nix b/nix/checks.nix index 2a819e0..6b296f4 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -285,6 +285,9 @@ let services.proxy-suite.singBox.tproxy.enable = true; } ]; + tproxyManualServiceConfig = tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig; + tproxyManualStartScript = builtins.readFile tproxyManualServiceConfig.ExecStart; + tproxyManualStopScript = builtins.readFile tproxyManualServiceConfig.ExecStop; tproxyAutostartFixture = evalProxySuite [ baseModule @@ -401,6 +404,8 @@ let ]; dnsRemoteOverrideConfig = mkTProxyConfig dnsRemoteOverrideFixture; tunDefaultConfig = mkTunConfig tunManualFixture; + tunServiceConfig = tunManualFixture.config.systemd.services."proxy-suite-tun".serviceConfig; + tunCleanupScript = builtins.readFile tunServiceConfig.ExecStopPost; zapretSyncFixture = evalProxySuite [ baseModule @@ -908,8 +913,9 @@ let perAppRoutingTunWrapper = _perAppRoutingTun.wrapper; perAppRoutingTunScript = _perAppRoutingTun.script; perAppRoutingTunProfiles = _perAppRoutingTun.profiles; - perAppRoutingTunStartScript = - builtins.readFile perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart; + perAppRoutingTunServiceConfig = perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig; + perAppRoutingTunStartScript = builtins.readFile perAppRoutingTunServiceConfig.ExecStart; + perAppRoutingTunCleanupScript = builtins.readFile perAppRoutingTunServiceConfig.ExecStopPost; perAppRoutingTunConfig = mkPerAppTunConfig perAppRoutingTunFixture; perAppRoutingTunDirectOutbound = builtins.head (builtins.filter (item: item.tag == "direct") perAppRoutingTunConfig.outbounds); @@ -965,8 +971,9 @@ let perAppRoutingTproxyWrapper = _perAppRoutingTproxy.wrapper; perAppRoutingTproxyScript = _perAppRoutingTproxy.script; perAppRoutingTproxyProfiles = _perAppRoutingTproxy.profiles; - perAppRoutingTproxyStartScript = - builtins.readFile perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy".serviceConfig.ExecStart; + perAppRoutingTproxyServiceConfig = perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy".serviceConfig; + perAppRoutingTproxyStartScript = builtins.readFile perAppRoutingTproxyServiceConfig.ExecStart; + perAppRoutingTproxyStopScript = builtins.readFile perAppRoutingTproxyServiceConfig.ExecStop; perAppRoutingTproxyUserStartExec = perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy-user@".serviceConfig.ExecStart; perAppRoutingTproxyUserStartScript = @@ -1368,11 +1375,39 @@ let == [ "multi-user.target" ]; true ) + ( + assert pkgs.lib.hasInfix "set -euo pipefail" tproxyManualStartScript; + assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStartScript; + assert pkgs.lib.hasInfix "route replace local default dev lo table 100" tproxyManualStartScript; + assert pkgs.lib.hasInfix "set +e" tproxyManualStopScript; + assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStopScript; + true + ) ( assert tunManualFixture.config.services.proxy-suite.singBox.tun.autostart == false; assert tunManualFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ ]; true ) + ( + let + inbound = builtins.head (builtins.filter (item: item.tag == "tun-in") tunDefaultConfig.inbounds); + in + assert inbound.iproute2_table_index == 2022; + assert inbound.iproute2_rule_index == 9000; + true + ) + ( + assert tunManualFixture.config.networking.nftables.enable; + true + ) + ( + assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost; + assert pkgs.lib.hasInfix ''delete table inet sing-box'' tunCleanupScript; + assert pkgs.lib.hasInfix ''rule del table 2022'' tunCleanupScript; + assert pkgs.lib.hasInfix ''route flush table 2022'' tunCleanupScript; + assert pkgs.lib.hasInfix "link del dev 'singtun0'" tunCleanupScript; + true + ) ( assert tunAutostartFixture.config.systemd.services."proxy-suite-tun".wantedBy @@ -1700,20 +1735,20 @@ let true ) - # -- subscription/runtime: refresh only restarts sing-box units that were already active -- + # -- subscription/runtime: refresh only restarts sing-box units that are active -- ( - assert pkgs.lib.hasInfix ''SOCKS_WAS_ACTIVE=0'' subscriptionOnlyUpdateScript; - assert pkgs.lib.hasInfix ''if [ "$SOCKS_WAS_ACTIVE" -eq 1 ]; then'' subscriptionOnlyUpdateScript; - assert pkgs.lib.hasInfix ''if [ "$TUN_WAS_ACTIVE" -eq 1 ]; then'' subscriptionOnlyUpdateScript; - assert pkgs.lib.hasInfix ''systemctl restart proxy-suite-socks'' subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix ''is-active --quiet proxy-suite-socks'' subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix ''restart proxy-suite-socks'' subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix ''is-active --quiet proxy-suite-tun'' subscriptionOnlyUpdateScript; + assert !(pkgs.lib.hasInfix ''SOCKS_WAS_ACTIVE'' subscriptionOnlyUpdateScript); true ) # -- subscription/runtime: refresh also handles the per-app TUN sing-box service when present -- ( - assert pkgs.lib.hasInfix ''PER_APP_TUN_WAS_ACTIVE=0'' subscriptionPerAppTunUpdateScript; - assert pkgs.lib.hasInfix ''systemctl is-active --quiet proxy-suite-per-app-tun'' subscriptionPerAppTunUpdateScript; - assert pkgs.lib.hasInfix ''systemctl restart proxy-suite-per-app-tun'' subscriptionPerAppTunUpdateScript; + assert pkgs.lib.hasInfix ''is-active --quiet proxy-suite-per-app-tun'' subscriptionPerAppTunUpdateScript; + assert pkgs.lib.hasInfix ''restart proxy-suite-per-app-tun'' subscriptionPerAppTunUpdateScript; + assert !(pkgs.lib.hasInfix ''PER_APP_TUN_WAS_ACTIVE'' subscriptionPerAppTunUpdateScript); true ) @@ -1862,6 +1897,14 @@ let true ) + # -- proxy-ctl: restart skips services that are not present in zapret-only or tg-only builds -- + ( + assert pkgs.lib.hasInfix "if _svc_exists proxy-suite-socks; then" minimalProxyCtlScript; + assert pkgs.lib.hasInfix "_svc_exists \"$svc\" && _svc_active \"$svc\"" minimalProxyCtlScript; + assert pkgs.lib.hasInfix "proxy-suite-tg-ws-proxy" minimalProxyCtlScript; + true + ) + # -- perAppRouting: generated proxy-ctl script dispatches through proxychains4 -- ( assert pkgs.lib.hasInfix "export PROXYCHAINS_QUIET_ARG='-q'" perAppRoutingProxychainsScript; @@ -1911,6 +1954,8 @@ let assert inbound.auto_route == false; assert inbound.auto_redirect == false; assert inbound.strict_route == false; + assert !(inbound ? iproute2_table_index); + assert !(inbound ? iproute2_rule_index); true ) @@ -1945,6 +1990,9 @@ let assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun"; assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun-user@"; assert perAppRoutingTunFixture.config.systemd.user.services ? "proxy-suite-per-app-tun-anchor"; + assert perAppRoutingTunServiceConfig.ExecStartPre == perAppRoutingTunServiceConfig.ExecStopPost; + assert pkgs.lib.hasInfix "link del dev 'psperapptun0'" perAppRoutingTunCleanupScript; + assert pkgs.lib.hasInfix "rule del fwmark 16 table 101" perAppRoutingTunCleanupScript; true ) @@ -2019,8 +2067,11 @@ let # -- perAppRouting: app TProxy startup installs nftables and loopback policy route -- ( assert pkgs.lib.hasInfix "proxy_suite_per_app_tproxy" perAppRoutingTproxyStartScript; + assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStartScript; assert pkgs.lib.hasInfix "route replace local default dev lo table 102" perAppRoutingTproxyStartScript; assert pkgs.lib.hasInfix "rule add fwmark 17 table 102" perAppRoutingTproxyStartScript; + assert pkgs.lib.hasInfix "set +e" perAppRoutingTproxyStopScript; + assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStopScript; true ) diff --git a/pkgs/proxy-ctl-lib.sh b/pkgs/proxy-ctl-lib.sh index c2b1fbc..65913ae 100644 --- a/pkgs/proxy-ctl-lib.sh +++ b/pkgs/proxy-ctl-lib.sh @@ -57,6 +57,21 @@ _svc_active() { systemctl is-active --quiet "$1" } +_require_service() { + local svc="$1" message="$2" + if ! _svc_exists "$svc"; then + echo "$message" + exit 1 + fi +} + +_stop_if_exists() { + local svc="$1" + if _svc_exists "$svc"; then + systemctl stop "$svc" || true + fi +} + _route_mode_default() { printf '%s' "${DEFAULT_ROUTE_MODE:-blacklist}" } @@ -159,6 +174,18 @@ _check_no_global_proxy() { fi } +_cleanup_slice_if_idle() { + local slice_base="$1" anchor_unit="$2" user_svc="$3" backend_svc="$4" + + if ! _scope_running "$slice_base"; then + systemctl stop "$user_svc" || true + systemctl --user stop "$anchor_unit" || true + if ! _any_user_active "$slice_base-user@"; then + systemctl stop "$backend_svc" || true + fi + fi +} + # _wrap_slice [cmd...] _wrap_slice() { local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4" @@ -171,22 +198,21 @@ _wrap_slice() { local scope_unit="$slice_base-${profile}-$$" local anchor_unit="$slice_base-anchor.service" local user_svc="$slice_base-user@$uid.service" - - systemctl --user start "$anchor_unit" - systemctl start "$backend_svc" - systemctl start "$user_svc" - local status=0 - systemd-run --user --scope --quiet --collect --same-dir \ - --slice="$slice_base" --unit="$scope_unit" "$@" || status=$? - if ! _scope_running "$slice_base"; then - systemctl stop "$user_svc" || true - systemctl --user stop "$anchor_unit" || true - if ! _any_user_active "$slice_base-user@"; then - systemctl stop "$backend_svc" || true - fi + systemctl --user start "$anchor_unit" || status=$? + if [ "$status" -eq 0 ]; then + systemctl start "$backend_svc" || status=$? fi + if [ "$status" -eq 0 ]; then + systemctl start "$user_svc" || status=$? + fi + if [ "$status" -eq 0 ]; then + systemd-run --user --scope --quiet --collect --same-dir \ + --slice="$slice_base" --unit="$scope_unit" "$@" || status=$? + fi + + _cleanup_slice_if_idle "$slice_base" "$anchor_unit" "$user_svc" "$backend_svc" exit "$status" } @@ -210,11 +236,13 @@ cmd_status() { cmd_proxy() { case "${1:-on}" in on) + _require_service proxy-suite-socks "SOCKS proxy service is not available because singBox is not enabled." systemctl start proxy-suite-socks ;; off) - systemctl stop proxy-suite-tproxy || true - systemctl stop proxy-suite-tun || true + _require_service proxy-suite-socks "SOCKS proxy service is not available because singBox is not enabled." + _stop_if_exists proxy-suite-tproxy + _stop_if_exists proxy-suite-tun systemctl stop proxy-suite-socks ;; *) @@ -228,6 +256,7 @@ cmd_mode_toggle() { local name="$1" local default_action="${2:-on}" local display="${4:-${name#proxy-suite-}}" + _require_service "$name" "Service '$name' is not available in this proxy-suite configuration." case "${3:-$default_action}" in on) systemctl start "$name" @@ -272,13 +301,17 @@ cmd_route_mode() { RESTART_SERVICES=( proxy-suite-tproxy proxy-suite-tun + proxy-suite-tg-ws-proxy zapret-discord-youtube ) cmd_restart() { - systemctl restart proxy-suite-socks + if _svc_exists proxy-suite-socks; then + systemctl restart proxy-suite-socks + fi + for svc in "${RESTART_SERVICES[@]}"; do - if systemctl is-active --quiet "$svc"; then + if _svc_exists "$svc" && _svc_active "$svc"; then systemctl restart "$svc" fi done @@ -421,6 +454,7 @@ cmd_subscription() { done ;; update) + _require_service proxy-suite-subscription-update "Subscription updates are unavailable because no subscriptions are configured." systemctl start proxy-suite-subscription-update echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update" ;; diff --git a/scripts/proxy_url_parsers.py b/scripts/proxy_url_parsers.py index 14753ce..523c1eb 100644 --- a/scripts/proxy_url_parsers.py +++ b/scripts/proxy_url_parsers.py @@ -10,6 +10,15 @@ def _qs(query: str) -> dict: return dict(urllib.parse.parse_qsl(query)) +def _split_host_port(hostpart: str) -> tuple[str, str]: + host, separator, port = hostpart.rpartition(":") + if not separator or not host or not port: + raise ValueError("URL must include host and port") + if host.startswith("[") and host.endswith("]"): + host = host[1:-1] + return host, port + + def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]: rest = url[len(f"{scheme}://") :] rest, _, _ = rest.partition("#") @@ -18,9 +27,7 @@ def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]: else: userinfo = "" hostpart, _, query = rest.partition("?") - host, _, port = hostpart.rpartition(":") - if host.startswith("[") and host.endswith("]"): - host = host[1:-1] + host, port = _split_host_port(hostpart) return userinfo, host, port, _qs(query) @@ -183,18 +190,44 @@ def parse_trojan(url: str, tag: str) -> dict: return ob -def parse_shadowsocks(url: str, tag: str) -> dict: - userinfo, host, port, _ = _parse_url_parts(url, "ss") +def _decode_ss_userinfo(userinfo: str) -> tuple[str, str]: + plain = urllib.parse.unquote(userinfo) + if ":" in plain: + return tuple(plain.split(":", 1)) pad = "=" * (-len(userinfo) % 4) try: decoded = base64.urlsafe_b64decode(userinfo + pad).decode() if ":" not in decoded: raise ValueError - method, password = decoded.split(":", 1) - except (binascii.Error, UnicodeDecodeError, ValueError): - plain = urllib.parse.unquote(userinfo) - method, password = plain.split(":", 1) + return tuple(decoded.split(":", 1)) + except (binascii.Error, UnicodeDecodeError, ValueError) as exc: + raise ValueError("invalid shadowsocks userinfo") from exc + + +def parse_shadowsocks(url: str, tag: str) -> dict: + # Support both SIP002 form: + # ss://base64(method:password)@host:port#name + # and legacy subscriptions that base64-encode the whole endpoint: + # ss://base64(method:password@host:port)#name + rest = url[len("ss://") :] + rest, _, _ = rest.partition("#") + endpoint, _, _ = rest.partition("?") + + if "@" in endpoint: + userinfo, host, port, _ = _parse_url_parts(url, "ss") + else: + pad = "=" * (-len(endpoint) % 4) + try: + decoded = base64.urlsafe_b64decode(endpoint + pad).decode() + except (binascii.Error, UnicodeDecodeError) as exc: + raise ValueError("invalid shadowsocks URL") from exc + userinfo, separator, hostpart = decoded.rpartition("@") + if not separator: + raise ValueError("invalid legacy shadowsocks URL") + host, port = _split_host_port(hostpart) + + method, password = _decode_ss_userinfo(userinfo) return { "type": "shadowsocks", diff --git a/scripts/test-build-outbound.py b/scripts/test-build-outbound.py index f68f591..2615b86 100644 --- a/scripts/test-build-outbound.py +++ b/scripts/test-build-outbound.py @@ -55,6 +55,39 @@ class BuildOutboundTests(unittest.TestCase): self.assertEqual(ob["type"], "shadowsocks") self.assertEqual(ob["method"], "chacha20-ietf-poly1305") + + def test_shadowsocks_legacy_full_base64(self): + legacy = ( + base64.urlsafe_b64encode( + b"chacha20-ietf-poly1305:passw0rd@legacy.example.com:8388" + ) + .decode() + .rstrip("=") + ) + ob = run_parser(f"ss://{legacy}#Legacy Server") + self.assertEqual(ob["type"], "shadowsocks") + self.assertEqual(ob["server"], "legacy.example.com") + self.assertEqual(ob["server_port"], 8388) + self.assertEqual(ob["method"], "chacha20-ietf-poly1305") + self.assertEqual(ob["password"], "passw0rd") + + + def test_shadowsocks_plain_userinfo(self): + ob = run_parser("ss://none:plain%20pass@plain.example.com:8388") + self.assertEqual(ob["type"], "shadowsocks") + self.assertEqual(ob["method"], "none") + self.assertEqual(ob["password"], "plain pass") + + def test_shadowsocks_legacy_ipv6_strips_brackets(self): + legacy = ( + base64.urlsafe_b64encode(b"none:pass@[2001:db8::1]:8388") + .decode() + .rstrip("=") + ) + ob = run_parser(f"ss://{legacy}#Legacy IPv6") + self.assertEqual(ob["server"], "2001:db8::1") + self.assertEqual(ob["server_port"], 8388) + def test_hysteria2(self): ob = run_parser( "hy2://secret@example.com:443?sni=hy.example.com&insecure=1&obfs=salamander&obfs-password=mask"