diff --git a/docs/options/warp.md b/docs/options/warp.md index cd4552c..4b938f2 100644 --- a/docs/options/warp.md +++ b/docs/options/warp.md @@ -47,8 +47,9 @@ false ## services\.proxy-suite\.warp\.asOutbound -Add WARP as an outbound tagged “warp”\. sing-box runs it as a WireGuard endpoint, -XRay as a wireguard outbound\. +Add WARP as an outbound tagged “warp”: a SOCKS hop to proxy-suite-warp-tunnel, which +runs WARP as a sing-box WireGuard endpoint on 127\.0\.0\.1:18538 and restarts it on a new +source port when the handshake stops being answered\. *Type:* boolean @@ -67,7 +68,7 @@ Junk-packet lines (Jc, Jmin, Jmax) are honoured by the AmneziaWG profile only\. When null, proxy-suite-warp registers a device with wgcf (accepting Cloudflare’s terms) into /var/lib/proxy-suite/warp, through the local proxy when proxy\.enable is set, and -retries until it succeeds\. Until then the warp outbound blocks\. +retries until it succeeds\. Until then warp connections fail\. *Type:* null or string diff --git a/modules/proxy-suite/autoproxy-rounds.jq b/modules/proxy-suite/autoproxy-rounds.jq new file mode 100644 index 0000000..66af63f --- /dev/null +++ b/modules/proxy-suite/autoproxy-rounds.jq @@ -0,0 +1,12 @@ +# Probe order of the exits after direct, from probe-exits.json with the state +# slurped as $s. Round 1: one exit per network (AS). Round 2, only walked when +# round 1 all refused: the rest. Bad exits (autoproxy-strike.jq) never take +# a network's round-1 place and go last. +[.[1:][] | {tag, asn: ($s[0].exits[.tag].asn // ""), bad: ($s[0].exits[.tag].bad == true)}] +| (map(select(.bad | not)) + map(select(.bad))) as $ordered +| reduce $ordered[] as $e ({seen: {}, r1: [], r2: []}; + if $e.bad then .r2 += [$e.tag] + elif $e.asn == "" or (.seen[$e.asn] | not) + then .r1 += [$e.tag] | .seen[$e.asn] = true + else .r2 += [$e.tag] end) +| {r1: (.r1 | join(",")), r2: (.r2 | join(",")), ordered: ($ordered | map(.tag))} diff --git a/modules/proxy-suite/autoproxy-strike.jq b/modules/proxy-suite/autoproxy-strike.jq new file mode 100644 index 0000000..c7e8c2d --- /dev/null +++ b/modules/proxy-suite/autoproxy-strike.jq @@ -0,0 +1,13 @@ +# Strikes against exits, which autoproxy-rounds.jq probes last once bad: domain $d +# refused $tags at $now, or crawled on them. $why is "wall:" (a block page: +# the site's security layer refused the address while another egress got past), +# "refused" (the origin refused it while another egress got content) or "slow". +# A domain counts once per exit, for $ttl seconds. One wall makes an exit bad - +# it is the site's own verdict on the address; the guesses need two domains. +# Empty $tags only expires. +reduce $tags[] as $t (.; .exits[$t].strikes[$d] = {why: $why, at: $now}) +| .exits |= map_values( + ((.strikes // {}) | with_entries(select(.value.at + $ttl > $now))) as $s + | . + {strikes: $s, + bad: (($s | length) >= 2 or any($s[]; .why | startswith("wall:"))), + badBy: ($s | to_entries | sort_by(.value.at) | map("\(.key) \(.value.why)"))}) diff --git a/modules/proxy-suite/autoproxy.nix b/modules/proxy-suite/autoproxy.nix index 80628b7..e31ab97 100644 --- a/modules/proxy-suite/autoproxy.nix +++ b/modules/proxy-suite/autoproxy.nix @@ -113,6 +113,12 @@ let mv -f "$tmp" "$state" } + # $1 JSON array of exit tags, $2 registrable domain, $3 wall:|refused|slow. + strike() { + update --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$now" --argjson ttl "$ttl" \ + -f ${./autoproxy-strike.jq} + } + # $1 registrable domain, $2 host probed, $3 probe JSON. Routes apply to the # whole domain (geo-blocks are drawn around sites); other verdicts only to # the host probed. @@ -129,6 +135,20 @@ let at: $now } | del(.backlog[$h])' + # Exits refused on the path another egress reached: by a block page + # (wall:, the site turning the address away) or by the origin. + local t why + while IFS=$'\t' read -r t why; do + strike "$(jq -cn --arg t "$t" '[$t]')" "$1" "$why" + done < <(jq -r '(.path // "") as $p | .exit as $x + | ([(.exits // [])[] | select(.tag == $x and .path == $p) | .judgement][0]) as $won + | if $x == null then empty else + # An origin refusal only counts against an exit when the winner got content. + [(.exits // [])[] | select(.path == $p and .tag != "direct" and .tag != $x + and (.judgement == "wall" or (.judgement == "blocked" and $won == "ok"))) + | {tag, why: (if .judgement == "wall" then "wall:" + .block else "refused" end)}] + | unique_by(.tag)[] | "\(.tag)\t\(.why)" + end' <<<"$3") } # Prefixes each host line with "registrable-domain". @@ -171,26 +191,26 @@ let asn=$(jq -r '(.org // "") | split(" ")[0]' <<<"$info" 2>/dev/null || true) [ -n "$ip" ] || continue update --arg t "$tag" --arg ip "$ip" --arg asn "$asn" --argjson now "$now" \ - '.exits[$t] = {ip: $ip, asn: $asn, at: $now}' + '.exits[$t] += {ip: $ip, asn: $asn, at: $now}' done < <(jq -r '.[] | "\(.tag)\t\(.port)"' "$index") - # Round 1: one exit per AS. Round 2, only if all refused: the rest. - rounds=$(jq -c --slurpfile s "$state" ' - [.[1:][] | {tag, asn: ($s[0].exits[.tag].asn // "")}] - | reduce .[] as $e ({seen: {}, r1: [], r2: []}; - if $e.asn == "" or (.seen[$e.asn] | not) - then .r1 += [$e.tag] | .seen[$e.asn] = true - else .r2 += [$e.tag] end) - | {r1: (.r1 | join(",")), r2: (.r2 | join(","))}' "$index") + # --- 2b. strikes older than a TTL stop counting against an exit --- + strike '[]' "" "" + + # See autoproxy-rounds.jq: one exit per AS, then the rest, bad exits last. + rounds=$(jq -c --slurpfile s "$state" -f ${./autoproxy-rounds.jq} "$index") round1=$(jq -r .r1 <<<"$rounds") round2=$(jq -r .r2 <<<"$rounds") walk() { - local out verdict + local out first verdict out=$(proxy-ctl proxy auto probe --json --exits "$round1" "$1" 2>/dev/null || echo '{}') verdict=$(jq -r '.verdict // "error"' <<<"$out") if { [ "$verdict" = both-fail ] || [ "$verdict" = unreachable ]; } && [ -n "$round2" ]; then + first=$out out=$(proxy-ctl proxy auto probe --json --exits "$round2" "$1" 2>/dev/null || echo '{}') + # Round 1's refusals count against its exits too (see record). + out=$(jq -c --argjson f "$first" '.exits = ($f.exits // []) + (.exits // [])' <<<"$out") fi printf '%s' "$out" } @@ -241,10 +261,12 @@ let | {key: .[0], value: {domain: .[1], hits: (.[2] | tonumber)}}) | from_entries' ) # Skipped: hosts of an already routed domain, hosts judged within the TTL. - # Dropped: entries older than the TTL, and those a route now covers. + # Dropped: entries older than the TTL, and those a route now covers; host + # verdicts past the TTL, which would only be probed again anyway. update --argjson c "$counts" --argjson now "$now" --argjson ttl "$ttl" ' . as $s | .lastRun = $now + | .hosts |= with_entries(select(.value.at + $ttl > $now)) | .backlog = (reduce ($c | to_entries[]) as $e (($s.backlog // {}); if ($s.domains[$e.value.domain].exit != null) or ((($s.hosts[$e.key].at // 0) + $ttl) > $now) @@ -278,16 +300,26 @@ let # stays direct for a TTL. while IFS=$'\t' read -r dom host tried; do was=''${tried##*,} + # It crawled twice on the exit it was routed through. + [ -z "$was" ] || strike "$(jq -cn --arg t "$was" '[$t]')" "$dom" slow via="" while IFS= read -r tag; do [[ ",$tried," != *",$tag,"* ]] || continue tried="''${tried:+$tried,}$tag" - if [ "$(proxy-ctl proxy auto probe --json --via "$tag" "$host" < /dev/null 2>/dev/null | - jq -r '.verdict // ""' 2>/dev/null)" = ok ]; then + out=$(proxy-ctl proxy auto probe --json --via "$tag" "$host" < /dev/null 2>/dev/null || echo '{}') + verdict=$(jq -r '.verdict // ""' <<<"$out" 2>/dev/null || true) + if [ "$verdict" = ok ]; then via=$tag break fi - done < <(jq -r '.[1:][] | .tag' "$index") + # Refused what direct gets, by a block page or by the origin. + if [ "$verdict" = blocked ]; then + why=$(jq -r --arg t "$tag" '[.exits[] | select(.tag == $t)] as $r + | [$r[] | select(.judgement == "wall") | "wall:" + .block][0] + // (if any($r[]; .judgement == "blocked") then "refused" else "" end)' <<<"$out" 2>/dev/null || true) + [ -z "$why" ] || strike "$(jq -cn --arg t "$tag" '[$t]')" "$dom" "$why" + fi + done < <(jq -r '.ordered[]' <<<"$rounds") if [ -n "$via" ]; then echo "slow $dom: crawls ''${was:+via $was}''${was:-directly}, routed via $via" update --arg d "$dom" --arg h "$host" --arg e "$via" --arg tried "$tried" --argjson now "$now" ' diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 4bb2be7..c36aa30 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -42,6 +42,8 @@ let cfg.warp.configFile else "/var/lib/proxy-suite/warp/wgcf-profile.conf"; + # Loopback SOCKS listener of proxy-suite-warp-tunnel, which the "warp" outbound dials. + tunnelPort = 18538; }; warpOutboundTag = "warp"; warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound; diff --git a/modules/proxy-suite/options/warp.nix b/modules/proxy-suite/options/warp.nix index 7a1e450..aefaa66 100644 --- a/modules/proxy-suite/options/warp.nix +++ b/modules/proxy-suite/options/warp.nix @@ -16,7 +16,7 @@ in When null, proxy-suite-warp registers a device with wgcf (accepting Cloudflare's terms) into /var/lib/proxy-suite/warp, through the local proxy when proxy.enable is set, and - retries until it succeeds. Until then the warp outbound blocks. + retries until it succeeds. Until then warp connections fail. ''; example = "/run/secrets/wgcf-profile.conf"; }; @@ -25,8 +25,9 @@ in type = types.bool; default = false; description = '' - Add WARP as an outbound tagged "warp". sing-box runs it as a WireGuard endpoint, - XRay as a wireguard outbound. + Add WARP as an outbound tagged "warp": a SOCKS hop to proxy-suite-warp-tunnel, which + runs WARP as a sing-box WireGuard endpoint on 127.0.0.1:18538 and restarts it on a new + source port when the handshake stops being answered. ''; }; diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index f9e5800..1bad942 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -76,7 +76,6 @@ let proxySuiteScriptsDir = ../../../scripts; parserScriptsPythonPath = proxySuiteScriptsDir; buildOutboundPy = "${proxySuiteScriptsDir}/build-outbound.py"; - warpOutboundPy = "${proxySuiteScriptsDir}/warp_outbound.py"; buildInboundPy = "${proxySuiteScriptsDir}/build-inbound.py"; fetchSubscriptionPy = "${proxySuiteScriptsDir}/fetch-subscription.py"; @@ -112,7 +111,6 @@ let xray parserScriptsPythonPath buildOutboundPy - warpOutboundPy buildInboundPy fetchSubscriptionPy ; diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix index 5a663f6..aa5ef25 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -8,7 +8,9 @@ if pureXrayEnabled then '' def xray_bind_outbound($interface): - if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then + # A loopback hop (the WARP tunnel, the OpenSSH listener) cannot leave through the uplink. + if $interface == "" or .protocol == "blackhole" or .protocol == "dns" + or ((.settings.address? // "") | test("^(127\\.|::1$|localhost$)")) then . else .streamSettings = (.streamSettings // {}) @@ -87,10 +89,7 @@ else [.route.rules[] | select(((.action? // "") == "hijack-dns") and (((.inbound? // []) | index("xray-dns-in")) != null))]; - # sing-box runs WireGuard as an endpoint, not an outbound. - .outbounds = ($obs | map(select(.type != "wireguard"))) + .outbounds - | ($obs | map(select(.type == "wireguard"))) as $endpoints - | if $endpoints == [] then . else .endpoints = (.endpoints // []) + $endpoints end + .outbounds = $obs + .outbounds | if $auth_enabled then (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] else . end diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index 24a155e..1f775fb 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -18,7 +18,6 @@ python3, parserScriptsPythonPath, buildOutboundPy, - warpOutboundPy, mkSubscriptionBlock, mkSubscriptionLoadHelperBlock, runtimeSubscriptionsBlock, @@ -319,40 +318,31 @@ let _proxy_suite_record_tag_source ${sshProxyTag} ssh ''; - # The profile is a secret, so it is converted at start rather than baked into the store. - # Hybrid runs WARP in sing-box, like the SSH outbound. + # WARP runs in proxy-suite-warp-tunnel, which restarts it when the handshake stops being + # answered. Every backend reaches it as a loopback SOCKS hop. mkWarpOutboundBlock = - routingMark: let - markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"; - profile = lib.escapeShellArg warpCfg.profilePath; - convert = '' - OB_JSON=$(${python3} ${warpOutboundPy} --backend ${ - if pureXrayEnabled then "xray" else "sing-box" - } --tag warp${markArg} < ${profile}) || exit 1 - ''; - blockJson = + outbound = if pureXrayEnabled then - ''{"protocol":"blackhole","tag":"warp","settings":{}}'' + { + protocol = "socks"; + tag = "warp"; + settings = { + address = "127.0.0.1"; + port = warpCfg.tunnelPort; + }; + } else - ''{"type":"block","tag":"warp"}''; + { + type = "socks"; + tag = "warp"; + server = "127.0.0.1"; + server_port = warpCfg.tunnelPort; + }; in '' - # outbound: warp (${if pureXrayEnabled then "XRay wireguard" else "sing-box WireGuard endpoint"}) - ${ - if warpCfg.autoRegister then - '' - if [ -s ${profile} ]; then - ${convert} - else - # proxy-suite-warp restarts this service once wgcf has registered. - echo "proxy-suite: warning: no WARP profile yet; warp blocks until proxy-suite-warp registers" >&2 - OB_JSON='${blockJson}' - fi - '' - else - convert - } + # outbound: warp (SOCKS hop to proxy-suite-warp-tunnel) + OB_JSON=${lib.escapeShellArg (builtins.toJSON outbound)} ${ if hybridEnabled then ''_proxy_suite_add_sing_box_ob "$OB_JSON"'' @@ -420,9 +410,7 @@ let ) proxyCfg.subscriptions; sshProxyBlock = lib.optionalString sshProxyCfg.asOutbound (mkSshProxyOutboundBlock routingMark); - warpBlock = lib.optionalString (warpCfg.enable && warpCfg.asOutbound) ( - mkWarpOutboundBlock routingMark - ); + warpBlock = lib.optionalString (warpCfg.enable && warpCfg.asOutbound) mkWarpOutboundBlock; wrapperBlock = if pureXrayEnabled && selectionMode == "urltest" then diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 75f9f70..19b1587 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -22,7 +22,6 @@ xray, parserScriptsPythonPath, buildOutboundPy, - warpOutboundPy, fetchSubscriptionPy, tproxyFile, tunFile, @@ -125,7 +124,6 @@ let python3 parserScriptsPythonPath buildOutboundPy - warpOutboundPy mkSubscriptionBlock mkSubscriptionLoadHelperBlock runtimeSubscriptionsBlock diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index 75caaa9..6c0f9c2 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -242,22 +242,20 @@ let # proxy-ctl proxy outbounds test. Servers for its ping, keyed by the user's tag: # the wrapper may have renamed one outbound "proxy" or prefixed them all, and a # hybrid XRay outbound is a sing-box socks hop whose real server is the sidecar's. + # A loopback hop (the WARP tunnel, XRay's SSH listener) has no server worth timing. ENDPOINTS_TMP="$RUNTIME_DIR/outbound-endpoints.json.tmp" ${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" --arg collapsed "''${PROXY_TAG:-}" ' def endpoint: if .server then {server, port: .server_port} - elif (.peers | type) == "array" then {server: .peers[0].address, port: .peers[0].port} elif .settings.address then {server: .settings.address, port: .settings.port} elif .settings.vnext then {server: .settings.vnext[0].address, port: .settings.vnext[0].port} elif .settings.servers then {server: .settings.servers[0].address, port: .settings.servers[0].port} - elif .settings.peers then - .settings.peers[0].endpoint | capture("^\\[?(?.*?)\\]?:(?[0-9]+)$") | .port |= tonumber else null end; - def udp: (.type // .protocol) as $t | ["hysteria", "hysteria2", "tuic", "wireguard"] | index($t) != null; + def udp: (.type // .protocol) as $t | ["hysteria", "hysteria2", "tuic"] | index($t) != null; ($sidecar | map({key: .tag, value: .}) | from_entries) as $real | [.[] | select(.type != "selector" and .type != "urltest") | (.tag | ltrimstr("proxy-suite-ob-") | if . == "proxy" then $collapsed else . end) as $tag - | ($real[.tag] // .) | select(endpoint != null) + | ($real[.tag] // .) | select(endpoint != null and (endpoint.server | test("^(127\\.|::1$|localhost$)") | not)) | {key: $tag, value: (endpoint + {network: (if udp then "udp" else "tcp" end)})}] | from_entries ' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP" diff --git a/modules/proxy-suite/warp.nix b/modules/proxy-suite/warp.nix index 5257d74..341809d 100644 --- a/modules/proxy-suite/warp.nix +++ b/modules/proxy-suite/warp.nix @@ -1,4 +1,5 @@ -# Cloudflare WARP: the AmneziaWG profile and, without a configFile, wgcf registration. +# Cloudflare WARP: the tunnel behind the "warp" outbound, the AmneziaWG profile and, without a +# configFile, wgcf registration. { lib, pkgs, @@ -54,44 +55,110 @@ let userinfo= ${userinfo} HTTPS_PROXY="socks5://''${userinfo}${hostPart}:${toString listener.port}" register || register - ${lib.optionalString w.asOutbound "${pkgs.systemd}/bin/systemctl --no-block try-restart proxy-suite-socks.service"} '' else "register" } ''; + + # sing-box's "local" server has no upstream on hosts behind systemd-resolved, so the tunnel + # resolves like the main config: the peer hostname and destinations go to proxy.dns.local. + dnsServer = { + tag = "local"; + type = cfg.proxy.dns.local.type; + server = cfg.proxy.dns.local.address; + server_port = cfg.proxy.dns.local.port; + }; + + # Some lines drop a share of fresh WARP handshakes for good, and sing-box retries on the + # same source port forever. A new process binds a new port, so the probe exits after + # repeated failures and systemd starts the tunnel again. + tunnelScript = pkgs.writeShellScript "proxy-suite-warp-tunnel" '' + set -euo pipefail + profile=${lib.escapeShellArg w.profilePath} + if [ ! -s "$profile" ]; then + echo "proxy-suite: waiting for the WARP profile at $profile" >&2 + until [ -s "$profile" ]; do sleep 5; done + fi + + # The profile is a secret, so it is converted here rather than baked into the store. + endpoint=$(${pkgs.python3}/bin/python3 ${../../scripts/warp_outbound.py} --tag warp --routing-mark ${toString cfg.proxy.tproxy.proxyMark} < "$profile") + ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{ + log: {level: "warn"}, + dns: {servers: [${builtins.toJSON dnsServer}]}, + route: {default_domain_resolver: "local", final: "warp"}, + inbounds: [{type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString w.tunnelPort}}], + endpoints: [$ep] + }' > "$RUNTIME_DIRECTORY/config.json" + + ${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json" & + singbox=$! + + failures=0 + while sleep 10; do + kill -0 "$singbox" 2>/dev/null || { wait "$singbox"; exit 1; } + if ${pkgs.curl}/bin/curl -sf --noproxy "" -x socks5h://127.0.0.1:${toString w.tunnelPort} -m 10 -o /dev/null ${lib.escapeShellArg cfg.proxy.urlTest.url}; then + failures=0 + elif (( ++failures >= 3 )); then + echo "proxy-suite: WARP stopped answering; restarting the tunnel on a new source port" >&2 + exit 1 + fi + done + ''; in { services.proxy-suite.amneziaWg.profiles = lib.mkIf w.asAmneziaWg { warp.configFile = w.profilePath; }; - systemd.services = lib.mkIf w.autoRegister { - proxy-suite-warp = { - description = "proxy-suite - register a Cloudflare WARP device with wgcf"; - after = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; - wants = [ "network-online.target" ]; - wantedBy = [ "multi-user.target" ]; - path = [ pkgs.wgcf ]; - # Retried until it registers. Not a oneshot: a slow or failed registration must not - # hold up or fail a switch. - startLimitIntervalSec = 0; - serviceConfig = { - Type = "simple"; - RemainAfterExit = true; - Restart = "on-failure"; - RestartSec = 30; - StateDirectory = "proxy-suite/warp"; - StateDirectoryMode = "0700"; - WorkingDirectory = "/var/lib/proxy-suite/warp"; - UMask = "0077"; - ExecStart = registerScript; + systemd.services = lib.mkMerge [ + (lib.mkIf w.asOutbound { + proxy-suite-warp-tunnel = { + description = "proxy-suite - Cloudflare WARP tunnel behind the warp outbound"; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + # Probe-triggered restarts must not trip the start limit. + startLimitIntervalSec = 0; + serviceConfig = { + Type = "simple"; + ExecStart = tunnelScript; + Restart = "always"; + RestartSec = 2; + RuntimeDirectory = "proxy-suite-warp-tunnel"; + RuntimeDirectoryMode = "0700"; + UMask = "0077"; + }; }; - }; + }) - # Only pulls registration in: a simple unit gives the profile no ordering guarantee. - proxy-suite-awg-warp = lib.mkIf w.asAmneziaWg { - wants = [ "proxy-suite-warp.service" ]; - }; - }; + (lib.mkIf w.autoRegister { + proxy-suite-warp = { + description = "proxy-suite - register a Cloudflare WARP device with wgcf"; + after = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"; + wants = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + path = [ pkgs.wgcf ]; + # Retried until it registers. Not a oneshot: a slow or failed registration must not + # hold up or fail a switch. + startLimitIntervalSec = 0; + serviceConfig = { + Type = "simple"; + RemainAfterExit = true; + Restart = "on-failure"; + RestartSec = 30; + StateDirectory = "proxy-suite/warp"; + StateDirectoryMode = "0700"; + WorkingDirectory = "/var/lib/proxy-suite/warp"; + UMask = "0077"; + ExecStart = registerScript; + }; + }; + + # Only pulls registration in: a simple unit gives the profile no ordering guarantee. + proxy-suite-awg-warp = lib.mkIf w.asAmneziaWg { + wants = [ "proxy-suite-warp.service" ]; + }; + }) + ]; } diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index 3d5722a..c44a13b 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -467,6 +467,40 @@ touch "$out" ''; + # autoProxy probe order: one exit per network first, bad exits last; and the + # strikes that make an exit bad. + autoproxy-rounds = + pkgs.runCommand "proxy-suite-autoproxy-rounds-check" { nativeBuildInputs = [ pkgs.jq ]; } '' + echo '[{"tag":"direct"},{"tag":"a"},{"tag":"b"},{"tag":"a2"},{"tag":"b2"},{"tag":"c"}]' > index.json + echo '{"exits":{"a":{"asn":"AS1","bad":true},"b":{"asn":"AS2"},"a2":{"asn":"AS1"}, + "b2":{"asn":"AS2"},"c":{"asn":"AS3","bad":false}}}' > state.json + r="$(jq -c --slurpfile s state.json -f ${../../modules/proxy-suite/autoproxy-rounds.jq} index.json)" + printf '%s\n' "$r" + # A refused a takes neither AS1's first place (a2 does) nor any place before b2. + jq -e '. == {r1: "b,a2,c", r2: "b2,a", ordered: ["b", "a2", "b2", "c", "a"]}' <<<"$r" > /dev/null + + k() { + jq -c --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$4" --argjson ttl 100 \ + -f ${../../modules/proxy-suite/autoproxy-strike.jq} <<<"$5" + } + s='{"exits":{"a":{"asn":"AS1"},"b":{}}}' + # One destination is not enough, however often it strikes. + s="$(k '["a"]' sekai.test refused 1000 "$s")" + s="$(k '["a","b"]' sekai.test refused 1010 "$s")" + jq -e '.exits.a.bad == false and .exits.a.asn == "AS1" and .exits.b.bad == false' <<<"$s" > /dev/null + # A second one is. + s="$(k '["a"]' pximg.net slow 1020 "$s")" + jq -e '.exits.a | .bad and .badBy == ["sekai.test refused", "pximg.net slow"]' <<<"$s" > /dev/null + jq -e '.exits.b.bad == false' <<<"$s" > /dev/null + # A TTL later the older strike has expired. + s="$(k '[]' "" "" 1115 "$s")" + jq -e '.exits.a | (.bad | not) and .badBy == ["pximg.net slow"]' <<<"$s" > /dev/null + # A block page is the site's own verdict on the address: one is enough. + s="$(k '["b"]' colorfulpalette.org wall:aws-waf 1120 "$s")" + jq -e '.exits.b | .bad and .badBy == ["colorfulpalette.org wall:aws-waf"]' <<<"$s" > /dev/null + touch "$out" + ''; + # Per-user inbound traffic collection; `proxy-ctl inbounds stats` is in proxy-ctl-unit. inbound-stats = pkgs.runCommand "proxy-suite-inbound-stats-check" diff --git a/nix/checks/warp.nix b/nix/checks/warp.nix index 11f73c6..c26a635 100644 --- a/nix/checks/warp.nix +++ b/nix/checks/warp.nix @@ -7,7 +7,7 @@ let generated = import ./read-generated.nix; - inherit (pkgs.lib) hasInfix; + inherit (pkgs.lib) hasInfix escapeShellArg; profile = "/run/secrets/wgcf-profile.conf"; markOf = fixture: toString fixture.config.services.proxy-suite.proxy.tproxy.proxyMark; @@ -35,12 +35,18 @@ let fixture: generated.readDerivation fixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart; + tunnelOf = + fixture: + generated.readDerivation + fixture.config.systemd.services."proxy-suite-warp-tunnel".serviceConfig.ExecStart; convertCall = - fixture: flag: - "warp_outbound.py --backend ${flag} --tag warp --routing-mark ${markOf fixture} < ${pkgs.lib.escapeShellArg profile}"; + fixture: "warp_outbound.py --tag warp --routing-mark ${markOf fixture} < \"$profile\""; + singBoxHop = ''"server":"127.0.0.1","server_port":18538,"tag":"warp","type":"socks"''; + xrayHop = ''"protocol":"socks","settings":{"address":"127.0.0.1","port":18538},"tag":"warp"''; singBox = mkFixture "sing-box" { asOutbound = true; }; singBoxStart = startOf singBox; + singBoxTunnel = tunnelOf singBox; xray = mkFixture "xray" { asOutbound = true; }; xrayStart = startOf xray; hybrid = mkFixture "hybrid" { asOutbound = true; }; @@ -49,7 +55,7 @@ let asOutbound = true; configFile = null; }; - autoStart = startOf auto; + autoTunnel = tunnelOf auto; amneziaWg = evalProxySuite [ { @@ -115,29 +121,53 @@ let in { assertions = [ + # Every backend dials the tunnel unit's loopback listener. ( - assert hasInfix (convertCall singBox "sing-box") singBoxStart; + assert hasInfix singBoxHop singBoxStart; true ) ( assert hasInfix "_proxy_suite_record_tag_source warp warp" singBoxStart; true ) - # The profile is read at start; the private key never reaches the store. ( - assert !(hasInfix "PrivateKey" singBoxStart); + assert hasInfix xrayHop xrayStart; true ) ( - assert hasInfix (convertCall xray "xray") xrayStart; + assert hasInfix singBoxHop hybridStart && hasInfix "_proxy_suite_add_sing_box_ob \"$OB_JSON\"" hybridStart; + true + ) + # Only the tunnel reads the profile, at start; the private key never reaches the store. + ( + assert !(hasInfix "warp_outbound.py" singBoxStart) && !(hasInfix profile singBoxStart); true ) ( - assert hasInfix (convertCall hybrid "sing-box") hybridStart; + assert hasInfix "profile=${escapeShellArg profile}" singBoxTunnel; true ) ( - assert hasInfix "_proxy_suite_add_sing_box_ob \"$OB_JSON\"" hybridStart; + assert hasInfix (convertCall singBox) singBoxTunnel; + true + ) + ( + assert !(hasInfix "PrivateKey" singBoxTunnel); + true + ) + ( + assert hasInfix "listen_port: 18538" singBoxTunnel; + true + ) + # 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 ''type: "local"'' singBoxTunnel); + true + ) + ( + assert xray.config.systemd.services ? "proxy-suite-warp-tunnel"; true ) ( @@ -148,12 +178,11 @@ in assert auto.config.systemd.services ? "proxy-suite-warp"; true ) + # Before wgcf registers, the tunnel waits instead of failing its way through restarts. ( - assert hasInfix "if [ -s /var/lib/proxy-suite/warp/wgcf-profile.conf ]" autoStart; - true - ) - ( - assert hasInfix "OB_JSON='{\"type\":\"block\",\"tag\":\"warp\"}'" autoStart; + assert + hasInfix "profile=/var/lib/proxy-suite/warp/wgcf-profile.conf" autoTunnel + && hasInfix "until [ -s \"$profile\" ]" autoTunnel; true ) ( @@ -164,6 +193,10 @@ in assert amneziaWg.config.systemd.services ? "proxy-suite-awg-warp"; true ) + ( + assert !(amneziaWg.config.systemd.services ? "proxy-suite-warp-tunnel"); + true + ) ] ++ invalidAssertions; } diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 26622ea..862eb7b 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -502,13 +502,15 @@ def _status_autoproxy(): state = os.path.join(_autoproxy_dir(), "state.json") if not readable(state): return "" - counts = [] - for key in ("domains", "backlog"): - try: - counts.append(str(len(read_json(state).get(key) or {}))) - except (OSError, ValueError, AttributeError, TypeError): - counts.append("?") + try: + data = read_json(state) + counts = [str(len(data.get(key) or {})) for key in ("domains", "backlog")] + bad = sum(1 for e in (data.get("exits") or {}).values() if isinstance(e, dict) and e.get("bad") is True) + except (OSError, ValueError, AttributeError, TypeError): + counts, bad = ["?", "?"], 0 text = f"{counts[0]} routed, {counts[1]} queued" + if bad: + text += f", {bad} bad exit{'' if bad == 1 else 's'}" next_run = _autoproxy_next_run() if next_run: text += f", next run {_in_time(next_run)}" @@ -808,20 +810,23 @@ def _outbounds_list(): pinned = _s(inventory.get("pinned") or "") sources = inventory.get("sources") or {} current = _outbound_current() + reputation = _reputation_by_tag() print(f"Selection: {_s(inventory.get('selection') or 'first')}") print(f"Pinned: {pinned or '(auto)'}") if current: print(f"Current: {current}") print() - print(f" {'TAG':<34} SOURCE") + # The reputation column only once the autoProxy prober has checked some exit. + rep = (lambda tag: f"{reputation.get(tag, '-'):<16} ") if reputation else (lambda tag: "") + print(f" {'TAG':<34} {'REPUTATION':<16} SOURCE" if reputation else f" {'TAG':<34} SOURCE") for tag in _outbound_tags(): mark = " " if tag == pinned: mark = "*" elif not pinned and tag == current: mark = ">" - print(f" {mark}{tag:<34} {_s(sources.get(tag) or '-')}") + print(f" {mark}{tag:<34} {rep(tag)}{_s(sources.get(tag) or '-')}") def cmd_select(tag="", *_): @@ -1030,10 +1035,28 @@ def cmd_subscription(verb="list", *args): # this host and the local proxy. The apex decides when any exit gets content # from it; robots.txt breaks ties when the apex is refused everywhere. # -# A fetch result is "||||". +# A fetch result is "|||||". +# block-page names the vendor page a refusal came with (PROBE_BLOCK_PAGES): the +# site's security layer turning the address away, not its origin answering. PROBE_BLOCK_REDIRECT = re.compile(r"unavailable|not-available|blocked|geo|region|restricted", re.I) PROBE_WRITE_OUT = "%{exitcode}|%{time_appconnect}|%{http_code}|%{size_download}|%{redirect_url}" +# name -> (kind, pattern over a refusal's headers and first 8 KiB of body). "address": +# the address itself was refused, so an exit that gets past it reaches the site. +# "geo": its country was, which is an ordinary refusal. +PROBE_BLOCK_PAGES = { + name: (kind, re.compile(pattern)) + for name, kind, pattern in [ + # CloudFront's AWS WAF page (game-version.sekai.colorfulpalette.org). + ("aws-waf", "address", r"(?ims)^server: cloudfront\b.*Request blocked\."), + ("cloudfront-geo", "geo", r"(?i)configured to block access from your country"), + ("cloudflare", "address", r'(?im)^cf-mitigated: challenge|cf-error-code">10(06|07|08|20)<|error code: 10(06|07|08|20)\b'), + ("cloudflare-geo", "geo", r'(?i)cf-error-code">1009<|error code: 1009\b'), + ("akamai", "address", r"(?ims)^server: AkamaiGHost\b.*Access Denied"), + ("imperva", "address", r"(?i)Incapsula incident ID"), + ("datadome", "address", r"(?im)^x-datadome:"), + ] +} def _probe_paths(): @@ -1068,38 +1091,58 @@ def _probe_fetch(domain, path, *selector): # An impersonating curl must keep its browser's own User-Agent. ua = [] if curl else ["-A", env("PROBE_UA", "Mozilla/5.0 (X11; Linux x86_64) proxy-suite-probe")] result = "" - for _ in range(6): - status, result = run_curl( - [ - curl or "curl", - "-sS", - "-o", - "/dev/null", - *ua, - "--connect-timeout", - env("PROBE_CONNECT_TIMEOUT", "8"), - "--max-time", - env("PROBE_MAX_TIME", "15"), - "-w", - PROBE_WRITE_OUT, - *selector, - url, - ] - ) - # Not a dead site: curl itself did not start. - if not result and status >= 126: - die(f"Cannot run {curl or 'curl'} (exit {status}).") - result = result or "99|0|000|0|" - if not re.fullmatch(r"3..", _probe_field(result, 3)) or _probe_redirect_is_block(result): - break - url = _probe_field(result, 5) - if not url or _probe_site(url) != site: - break + with tempfile.TemporaryDirectory(prefix="proxy-ctl-probe-") as tmp: + for hop in range(6): + head, body = os.path.join(tmp, f"{hop}.head"), os.path.join(tmp, f"{hop}.body") + status, out = run_curl( + [ + curl or "curl", + "-sS", + "-D", + head, + "-o", + body, + *ua, + "--connect-timeout", + env("PROBE_CONNECT_TIMEOUT", "8"), + "--max-time", + env("PROBE_MAX_TIME", "15"), + "-w", + PROBE_WRITE_OUT, + *selector, + url, + ] + ) + # Not a dead site: curl itself did not start. + if not out and status >= 126: + die(f"Cannot run {curl or 'curl'} (exit {status}).") + fields = (out or "99|0|000|0|").split("|", 4) + fields += [""] * (5 - len(fields)) + result = "|".join([*fields[:4], _probe_block_page(fields[2], head, body), fields[4]]) + if not re.fullmatch(r"3..", _probe_field(result, 3)) or _probe_redirect_is_block(result): + break + url = _probe_field(result, 6) + if not url or _probe_site(url) != site: + break return result +def _probe_block_page(code, head, body): + """The PROBE_BLOCK_PAGES name a refusal's page matches; "" for none.""" + if not re.fullmatch(r"[45]..", code): + return "" + text = "" + for path, limit in ((head, -1), (body, 8192)): + try: + with open(path, "rb") as f: + text += f.read(limit).decode("latin-1") + "\n\n" + except OSError: + pass + return next((name for name, (_, pattern) in PROBE_BLOCK_PAGES.items() if pattern.search(text)), "") + + def _probe_field(result, n): - fields = result.split("|", 4) + fields = result.split("|", 5) return fields[n - 1] if n <= len(fields) else "" @@ -1109,7 +1152,7 @@ def _probe_tls_ok(result): def _probe_redirect_is_block(result): - return bool(PROBE_BLOCK_REDIRECT.search(_probe_field(result, 5))) + return bool(PROBE_BLOCK_REDIRECT.search(_probe_field(result, 6))) def _probe_http_ok(result): @@ -1124,11 +1167,23 @@ def _probe_http_ok(result): def _probe_exit_verdict(result): """dead: failed before the origin spoke (the censor's doing, zapret's job). + wall: the site's security layer refused this address (an exit past it helps). blocked: the origin answered and refused (a proxy hop can fix it). """ if not _probe_tls_ok(result) or _probe_field(result, 3) == "000": return "dead" - return "ok" if _probe_http_ok(result) else "blocked" + if _probe_http_ok(result): + return "ok" + return "wall" if PROBE_BLOCK_PAGES.get(_probe_field(result, 5), ("",))[0] == "address" else "blocked" + + +def _probe_reaches(direct_judgement, judgement): + """Content, or - where direct hit a wall - any answer from the origin past it. + + ponytail: an origin refusing behind the wall (its own geo-block) counts as + reached too; compare with robots.txt if that misroutes a site. + """ + return judgement == "ok" or (direct_judgement == "wall" and judgement == "blocked") def _probe_verdict(direct, via): @@ -1136,7 +1191,7 @@ def _probe_verdict(direct, via): v = _probe_exit_verdict(via) if d == "ok": return "ok" - if v == "ok": + if _probe_reaches(d, v): return "censor" if d == "dead" else "destination" return "unreachable" if d == "dead" else "both-fail" @@ -1158,7 +1213,9 @@ def _probe_describe(result): if status == "000": return f"TLS {_probe_field(result, 2)}s, then no response" text = f"TLS {_probe_field(result, 2)}s, {status}, {_probe_field(result, 4)} bytes" - location = _probe_field(result, 5) + if _probe_field(result, 5): + text += f", {_probe_field(result, 5)} page" + location = _probe_field(result, 6) return f"{text} -> {location}" if location else text @@ -1181,7 +1238,8 @@ def _walk(**fields): def _probe_walk(domain, exits, paths, keep_going): - """Walks exits (direct first) and stops at the first that gets content. + """Walks exits (direct first) and stops at the first that reaches it: gets + content, or gets past a wall direct hit (_probe_reaches). keep_going still tries the rest, keeping that first one. rows are (tag, path, result, judgement) per request. @@ -1191,10 +1249,10 @@ def _probe_walk(domain, exits, paths, keep_going): first_direct = "" for path in paths: direct = _probe_fetch_exit(domain, path, direct_url) - judgement = _probe_exit_verdict(direct) - w["rows"].append((direct_tag, path, direct, judgement)) + dj = _probe_exit_verdict(direct) + w["rows"].append((direct_tag, path, direct, dj)) first_direct = first_direct or direct - if judgement == "ok" and not w["verdict"]: + if dj == "ok" and not w["verdict"]: w.update(verdict="ok", path=path, direct=direct) if not keep_going: return w @@ -1202,7 +1260,7 @@ def _probe_walk(domain, exits, paths, keep_going): result = _probe_fetch_exit(domain, path, url) judgement = _probe_exit_verdict(result) w["rows"].append((tag, path, result, judgement)) - if judgement == "ok" and not w["verdict"]: + if _probe_reaches(dj, judgement) and not w["verdict"]: w.update(verdict=_probe_verdict(direct, result), exit=tag, path=path, direct=direct, via=result) if not keep_going: return w @@ -1292,7 +1350,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)) for row in w["rows"]], + "exits": [dict(zip(("tag", "path", "result", "judgement"), row), block=_probe_field(row[2], 5)) for row in w["rows"]], } print(json.dumps(out, separators=(",", ":"), ensure_ascii=False)) return @@ -1316,6 +1374,31 @@ def cmd_proxy_probe(*args): print(f" try: proxy-ctl zapret auto add {domain}") +# --- bad exits ----------------------------------------------------------------- +# +# The autoProxy prober strikes an exit when a destination refuses it while +# another egress gets content, or crawls on it (autoproxy-strike.jq). An exit +# struck by several destinations within a TTL is bad, and probed last. + + +def _reputation_by_tag(): + """User tag -> "bad" or "ok" once the prober has judged its exit; {} before it has.""" + if env("AUTOPROXY_ENABLED") != "1": + return {} + exits = _autoproxy_state(_autoproxy_dir()).get("exits") or {} + # Exits are keyed by the backend's tag; outbound-test.json maps the user's to it. + try: + backend = read_json(_runtime_file("outbound-test.json")).get("outbounds") or {} + except (OSError, ValueError, AttributeError): + backend = {} + out = {} + for tag in _outbound_tags(): + e = exits.get(_s(backend.get(tag) or tag)) + if isinstance(e, dict) and "strikes" in e: + out[tag] = "bad" if e.get("bad") is True else "ok" + return out + + def _autoproxy_dir(): return env("AUTOPROXY_STATE_DIR", "/var/lib/proxy-suite/autoproxy") @@ -1442,6 +1525,13 @@ def cmd_proxy_learned(*_): print() print(f"Hosts judged: {judged or 'none yet'}") + bad = {t: e.get("badBy") or [] for t, e in (state.get("exits") or {}).items() if isinstance(e, dict) and e.get("bad") is True} + if bad: + print() + print("Probed last, refused or crawled by several destinations:") + for tag, by in sorted(bad.items()): + print(f" {_s(tag):<28} {', '.join(_s(b) for b in by)}") + def cmd_proxy_learn(host="", *_): """Queues the host for the prober's own unit, recorded under the same lock as a timer run.""" diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index a613cd6..ac128fb 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -63,23 +63,30 @@ class ProbeVerdictTest(unittest.TestCase): def test_table(self): # Origin refuses direct, accepts the proxy: chatgpt.com/robots.txt. - self.expect("destination", "0|0.146175|403|6633|", "0|0.230116|200|4302|") + self.expect("destination", "0|0.146175|403|6633||", "0|0.230116|200|4302||") # The same through a redirect: claude.ai/robots.txt. - self.expect("destination", "0|0.141625|302|143|https://claude.com/app-unavailable-in-region", "0|0.181276|200|281|") + self.expect("destination", "0|0.141625|302|143||https://claude.com/app-unavailable-in-region", "0|0.181276|200|281||") # TLS never completed: censorship, zapret's job. - self.expect("censor", "35|0.000000|000|0|", "0|0.119348|200|6258|") + self.expect("censor", "35|0.000000|000|0||", "0|0.119348|200|6258||") # Handshake, then silence: the post-handshake throttle. - self.expect("censor", "0|0.125029|000|0|", "0|0.143772|200|32881|") + self.expect("censor", "0|0.125029|000|0||", "0|0.143772|200|32881||") # Direct works. Nothing to do, whoever else also works. - self.expect("ok", "0|0.099546|200|2678|", "0|0.146822|200|2678|") + self.expect("ok", "0|0.099546|200|2678||", "0|0.146822|200|2678||") # robots.txt legitimately absent is not a failure. - self.expect("ok", "0|0.161330|404|559|", "0|0.214667|404|559|") + self.expect("ok", "0|0.161330|404|559||", "0|0.214667|404|559||") # An ordinary redirect must not read as a block. - self.expect("ok", "0|0.10|301|0|https://www.example.com/robots.txt", "0|0.20|301|0|https://www.example.com/robots.txt") + self.expect("ok", "0|0.10|301|0||https://www.example.com/robots.txt", "0|0.20|301|0||https://www.example.com/robots.txt") # Refused everywhere: not an egress problem. - self.expect("both-fail", "0|0.10|403|100|", "0|0.20|403|100|") + self.expect("both-fail", "0|0.10|403|100||", "0|0.20|403|100||") + # AWS WAF's page for direct, the origin's own 403 through the proxy: it got + # past the wall (game-version.sekai.colorfulpalette.org, S3 behind CloudFront). + self.expect("destination", "0|0.12|403|919|aws-waf|", "0|0.19|403|243||") + # A wall everywhere is not an egress problem either (a bot challenge, say). + self.expect("both-fail", "0|0.12|403|919|aws-waf|", "0|0.19|403|919|aws-waf|") + # A country refused is an ordinary refusal: nothing to get past. + self.expect("both-fail", "0|0.12|403|500|cloudfront-geo|", "0|0.19|403|243||") # Nothing reaches it at all - a dead name, not a blocked one. - self.expect("unreachable", "6|0.000000|000|0|", "35|0.000000|000|0|") + self.expect("unreachable", "6|0.000000|000|0||", "35|0.000000|000|0||") class ProbeFetchTest(EnvTest): @@ -108,6 +115,42 @@ class ProbeFetchTest(EnvTest): ctl._probe_fetch("loop.test", "/", "--noproxy", "*") self.assertLessEqual(len(calls), 6) + def test_block_pages(self): + waf_head = "HTTP/2 403\r\nserver: CloudFront\r\nx-cache: Error from cloudfront\r\n\r\n" + waf_body = "

403 ERROR

\n

The request could not be satisfied.

\n
\nRequest blocked.\n" + pages = { + # Measured through two exits: AWS WAF's page, and past it S3 refusing "/". + "waf.test": ("403", waf_head, waf_body), + "s3.test": ("403", "HTTP/2 403\r\nserver: AmazonS3\r\n\r\n", "AccessDeniedAccess Denied"), + "cf.test": ("403", "HTTP/2 403\r\nserver: cloudflare\r\n\r\n", '1020'), + "cfgeo.test": ("403", "HTTP/2 403\r\nserver: cloudflare\r\n\r\n", "error code: 1009"), + # Content that merely quotes a block page is content. + "article.test": ("200", waf_head, waf_body), + } + + def curl(argv): + code, head, body = pages[argv[-1].split("/")[2]] + for flag, text in (("-D", head), ("-o", body)): + with open(argv[argv.index(flag) + 1], "w") as f: + f.write(text) + return 0, f"0|0.1|{code}|{len(body)}|" + + self.patch("run_curl", curl) + got = {} + for host in pages: + result = ctl._probe_fetch(host, "/", "--noproxy", "*") + got[host] = (ctl._probe_field(result, 5), ctl._probe_exit_verdict(result)) + self.assertEqual( + got, + { + "waf.test": ("aws-waf", "wall"), + "s3.test": ("", "blocked"), + "cf.test": ("cloudflare", "wall"), + "cfgeo.test": ("cloudflare-geo", "blocked"), + "article.test": ("", "ok"), + }, + ) + def test_curl_that_cannot_start(self): # An error, not a dead site. os.environ.update(PROBE_CURL="/nonexistent", PROBE_EXITS_FILE="/nonexistent") @@ -140,16 +183,16 @@ class ProbeWalkTest(EnvTest): # --- which path decides: the apex, robots.txt only breaks ties --- def test_apex_decides(self): # last.fm: apex geo-blocked, robots.txt served everywhere. - out = self.probe_with("0|0.11|403|424|", "0|0.17|200|59809|", "0|0.11|200|400|", "0|0.17|200|400|") + out = self.probe_with("0|0.11|403|424||", "0|0.17|200|59809||", "0|0.11|200|400||", "0|0.17|200|400||") self.assertEqual((out["verdict"], out["url"]), ("destination", "https://example.test/")) def test_robots_breaks_ties(self): # chatgpt.com: apex 403 everywhere, robots.txt separates. - out = self.probe_with("0|0.14|403|6633|", "0|0.23|403|8442|", "0|0.14|403|6633|", "0|0.23|200|4302|") + out = self.probe_with("0|0.14|403|6633||", "0|0.23|403|8442||", "0|0.14|403|6633||", "0|0.23|200|4302||") self.assertEqual((out["verdict"], out["url"]), ("destination", "https://example.test/robots.txt")) def test_working_apex_is_not_second_guessed(self): - out = self.probe_with("0|0.10|200|500|", "0|0.20|200|500|", "0|0.10|403|10|", "0|0.20|200|10|") + out = self.probe_with("0|0.10|200|500||", "0|0.20|200|500||", "0|0.10|403|10||", "0|0.20|200|10||") self.assertEqual(out["verdict"], "ok") # --- walking more than two exits --- @@ -163,7 +206,7 @@ class ProbeWalkTest(EnvTest): def test_multi_exit(self): # Direct and the first proxy share a WAF; only the third exit gets through. # Every exit, direct included, goes through its pinned listener. - self.use_exits(lambda domain, path, flag, url: "0|0.10|200|500|" if url.endswith(":18542") else "0|0.10|403|919|") + self.use_exits(lambda domain, path, flag, url: "0|0.10|200|500||" if url.endswith(":18542") else "0|0.10|403|919||") out = self.probe("sekai.test") self.assertEqual((out["verdict"], out["exit"]), ("destination", "de")) @@ -197,16 +240,29 @@ class ProbeWalkTest(EnvTest): def test_via_refused_front_page(self): # Refused a front page direct gets: not a stand-in (www.reddit.com). - self.use_exits(lambda domain, path, flag, url: "0|0.10|403|190240|" if url.endswith(":18541") and path == "/" else "0|0.10|200|500|") + self.use_exits(lambda domain, path, flag, url: "0|0.10|403|190240||" if url.endswith(":18541") and path == "/" else "0|0.10|200|500||") self.assertEqual(self.probe("--via", "fi", "geo.test")["verdict"], "blocked") def test_via_robots_decides(self): # i.pximg.net: the front page is 400 everywhere, so robots.txt decides. - self.use_exits(lambda domain, path, flag, url: "0|0.10|400|0|" if path == "/" else "0|0.10|200|43|") + self.use_exits(lambda domain, path, flag, url: "0|0.10|400|0||" if path == "/" else "0|0.10|200|43||") self.assertEqual(self.probe("--via", "fi", "cdn.test")["verdict"], "ok") + def test_past_a_wall(self): + # game-version.sekai.colorfulpalette.org: AWS WAF for direct and fi, S3's own 403 for de. + self.use_exits(lambda domain, path, flag, url: "0|0.19|403|243||" if url.endswith(":18542") else "0|0.12|403|919|aws-waf|") + out = self.probe("sekai.test") + self.assertEqual((out["verdict"], out["exit"], out["path"]), ("destination", "de", "/")) + self.assertEqual( + [(e["tag"], e["judgement"], e["block"]) for e in out["exits"]], + [("direct", "wall", "aws-waf"), ("fi", "wall", "aws-waf"), ("de", "blocked", "")], + ) + # Walled everywhere: nobody got past. + self.use_exits(lambda domain, path, flag, url: "0|0.12|403|919|aws-waf|") + self.assertEqual(self.probe("sekai.test")["verdict"], "both-fail") + def test_text_output(self): - self.use_exits(lambda domain, path, flag, url: "0|0.10|200|500|" if url.endswith(":18542") else "0|0.10|403|919|") + self.use_exits(lambda domain, path, flag, url: "0|0.10|200|500||" if url.endswith(":18542") else "0|0.10|403|919||") out = ok(ctl.cmd_proxy_probe, "sekai.test") self.assertRegex(out, r"(?m)^ de +/ +TLS 0\.10s, 200, 500 bytes +ok <- chosen$") self.assertIn('pin: proxy.routing.rules = [ { outbound = "de"; domains = [ "sekai.test" ]; } ]', out) @@ -484,5 +540,30 @@ class OutboundTestTest(EnvTest): self.assertIn("enable userControl, or run with sudo", err) +class BadExitTest(EnvTest): + def test_shown_from_state(self): + os.environ.update( + AUTOPROXY_ENABLED="1", + AUTOPROXY_STATE_DIR=self.dir, + OUTBOUND_INVENTORY_FILE=self.write("outbounds.json", {"tags": ["mine", "fresh", "new"], "sources": {}}), + ) + # The user's "mine" is the backend's "proxy". + self.write("outbound-test.json", {"outbounds": {"mine": "proxy", "fresh": "fresh", "new": "new"}}) + exits = { + "proxy": {"strikes": {"sekai.test": {}, "pximg.net": {}}, "bad": True, "badBy": ["sekai.test refused", "pximg.net slow"]}, + "fresh": {"strikes": {"sekai.test": {}}, "bad": False, "badBy": ["sekai.test refused"]}, + "new": {"ip": "192.0.2.1"}, + } + self.write("state.json", {"domains": {}, "exits": exits}) + self.patch("_outbound_current", lambda: "") + self.patch("_autoproxy_next_run", lambda: None) + rows = {line.split()[0]: line.split() for line in ctl.lines(ok(ctl.cmd_outbounds, "list")) if line.startswith(" ")} + self.assertEqual(rows["mine"][1], "bad") + self.assertEqual(rows["fresh"][1], "ok") + # Not judged yet. + self.assertEqual(rows["new"][1], "-") + self.assertIn("1 bad exit", ctl._status_autoproxy()) + self.assertRegex(ok(ctl.cmd_proxy_learned), r"(?m)^ proxy +sekai\.test refused, pximg\.net slow$") + if __name__ == "__main__": unittest.main() diff --git a/scripts/test-warp-outbound.py b/scripts/test-warp-outbound.py index e8ab4ee..82cbc27 100644 --- a/scripts/test-warp-outbound.py +++ b/scripts/test-warp-outbound.py @@ -18,7 +18,7 @@ Endpoint = engage.cloudflareclient.com:2408 class WarpOutboundTest(unittest.TestCase): def test_sing_box_endpoint(self): - ob = build(WGCF, "sing-box", "warp", 255) + ob = build(WGCF, "warp", 255) self.assertEqual(ob["type"], "wireguard") self.assertEqual(ob["address"], ["172.16.0.2/32", "2606:4700:110:8d58::2/128"]) self.assertEqual(ob["private_key"], "priv=") @@ -28,20 +28,14 @@ class WarpOutboundTest(unittest.TestCase): [{"address": "engage.cloudflareclient.com", "port": 2408, "public_key": "pub=", "allowed_ips": ["0.0.0.0/0", "::/0"]}], ) - def test_xray_outbound(self): - ob = build(WGCF, "xray", "warp", None) - self.assertEqual(ob["protocol"], "wireguard") - self.assertEqual(ob["settings"]["secretKey"], "priv=") - self.assertEqual(ob["settings"]["peers"][0]["endpoint"], "engage.cloudflareclient.com:2408") - self.assertNotIn("streamSettings", ob) - def test_ipv6_endpoint(self): - ob = build(WGCF.replace("engage.cloudflareclient.com:2408", "[2606:4700:d0::a29f:c001]:500"), "sing-box", "warp", None) + ob = build(WGCF.replace("engage.cloudflareclient.com:2408", "[2606:4700:d0::a29f:c001]:500"), "warp", None) self.assertEqual((ob["peers"][0]["address"], ob["peers"][0]["port"]), ("2606:4700:d0::a29f:c001", 500)) + self.assertNotIn("routing_mark", ob) def test_rejects_missing_peer(self): with self.assertRaises(ConfigError): - build(WGCF.split("[Peer]")[0], "sing-box", "warp", None) + build(WGCF.split("[Peer]")[0], "warp", None) if __name__ == "__main__": diff --git a/scripts/warp_outbound.py b/scripts/warp_outbound.py index 6aa6cc8..05f690b 100644 --- a/scripts/warp_outbound.py +++ b/scripts/warp_outbound.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Turn a WireGuard .conf (e.g. wgcf-profile.conf) into a WARP outbound for sing-box or XRay.""" +"""Turn a WireGuard .conf (e.g. wgcf-profile.conf) into a sing-box WireGuard endpoint for WARP.""" from __future__ import annotations @@ -44,56 +44,25 @@ def split_endpoint(endpoint: str) -> tuple[str, int]: return host.strip("[]"), int(port) -def build(text: str, backend: str, tag: str, routing_mark: int | None) -> dict[str, Any]: +def build(text: str, tag: str, routing_mark: int | None) -> dict[str, Any]: interface, peer = parse_conf(text) - addresses = _split(interface["address"]) - allowed_ips = _split(peer.get("allowedips", "")) or ["0.0.0.0/0", "::/0"] - mtu = int(interface.get("mtu") or 1280) - keepalive = int(peer["persistentkeepalive"]) if peer.get("persistentkeepalive") else None - psk = peer.get("presharedkey") host, port = split_endpoint(peer["endpoint"]) - - if backend == "xray": - xray_peer: dict[str, Any] = { - "publicKey": peer["publickey"], - "endpoint": peer["endpoint"], - "allowedIPs": allowed_ips, - } - if keepalive is not None: - xray_peer["keepAlive"] = keepalive - if psk: - xray_peer["preSharedKey"] = psk - outbound: dict[str, Any] = { - "protocol": "wireguard", - "tag": tag, - "settings": { - "secretKey": interface["privatekey"], - "address": addresses, - "peers": [xray_peer], - "mtu": mtu, - }, - } - if routing_mark is not None: - outbound["streamSettings"] = {"sockopt": {"mark": routing_mark}} - return outbound - - # sing-box >= 1.11: WireGuard is an endpoint; the start script moves it out of outbounds. sb_peer: dict[str, Any] = { "address": host, "port": port, "public_key": peer["publickey"], - "allowed_ips": allowed_ips, + "allowed_ips": _split(peer.get("allowedips", "")) or ["0.0.0.0/0", "::/0"], } - if keepalive is not None: - sb_peer["persistent_keepalive_interval"] = keepalive - if psk: - sb_peer["pre_shared_key"] = psk + if peer.get("persistentkeepalive"): + sb_peer["persistent_keepalive_interval"] = int(peer["persistentkeepalive"]) + if peer.get("presharedkey"): + sb_peer["pre_shared_key"] = peer["presharedkey"] endpoint: dict[str, Any] = { "type": "wireguard", "tag": tag, - "address": addresses, + "address": _split(interface["address"]), "private_key": interface["privatekey"], - "mtu": mtu, + "mtu": int(interface.get("mtu") or 1280), "peers": [sb_peer], } if routing_mark is not None: @@ -103,12 +72,11 @@ def build(text: str, backend: str, tag: str, routing_mark: int | None) -> dict[s def main() -> int: parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--backend", choices=["sing-box", "xray"], required=True) parser.add_argument("--tag", default="warp") parser.add_argument("--routing-mark", type=int) args = parser.parse_args() try: - print(json.dumps(build(sys.stdin.read(), args.backend, args.tag, args.routing_mark))) + print(json.dumps(build(sys.stdin.read(), args.tag, args.routing_mark))) except (ConfigError, ValueError) as error: print(f"proxy-suite: warp: {error}", file=sys.stderr) return 1