feat: improve warp, outbounds reputation

This commit is contained in:
fufsob committed 2026-09-14 09:06:59 +00:00
1 parent 85c3e6cfaf
commit ab2167ff9c
18 files changed
+533 -224

No files matched your search

+12
View File
@@ -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))}
+13
View File
@@ -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:<page>" (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)"))})
+46 -14
View File
@@ -113,6 +113,12 @@ let
mv -f "$tmp" "$state"
}
# $1 JSON array of exit tags, $2 registrable domain, $3 wall:<page>|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:<page>, 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<TAB>".
@@ -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" '
+2
View File
@@ -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;
+4 -3
View File
@@ -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.
'';
};
-2
View File
@@ -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
;
@@ -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
@@ -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
-2
View File
@@ -22,7 +22,6 @@
xray,
parserScriptsPythonPath,
buildOutboundPy,
warpOutboundPy,
fetchSubscriptionPy,
tproxyFile,
tunFile,
@@ -125,7 +124,6 @@ let
python3
parserScriptsPythonPath
buildOutboundPy
warpOutboundPy
mkSubscriptionBlock
mkSubscriptionLoadHelperBlock
runtimeSubscriptionsBlock
@@ -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("^\\[?(?<server>.*?)\\]?:(?<port>[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"
+95 -28
View File
@@ -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" ];
};
})
];
}