polarisCTF Crypto 方向全解 wp
本文围绕 polarisCTF 的 9 道密码学题目展开,包含整体思路、解题关键与完整的解题脚本
ez_login
应用只有一个登录入口,用户表初始化为 {"admin": ADMIN_PASS},同时禁止注册。表面上看,题目把入口压得很死,唯一能接触到 flag 的路径就是以 admin 身份进入首页
真正的问题出在登录判断:
user = request.form.get('username')
pw = request.form.get('password')
if USERS.get(user) == pw:
resp = make_response(redirect(url_for('index')))
resp.set_cookie('session', create_session(user))
return resp这里只校验了 USERS.get(user) == pw,却没有保证 user 和 pw 一定存在。表单字段完全省略时,request.form.get(...) 拿到的是 None,于是判断会变成 USERS.get(None) == None。USERS 里并没有 None 这个键,dict.get(None) 的返回值同样是 None,比较结果成立,登录可以直接通过
这个绕过拿到的不是管理员会话,而是一份合法签发的普通会话。create_session 会把 user=<username> 这一段文本做 AES-CBC 加密,再把 iv + ct 作为十六进制字符串放进 cookie:
def create_session(username):
iv = os.urandom(16)
cipher = AES.new(KEY, AES.MODE_CBC, iv)
msg = f"user={username}".encode()
ct = cipher.encrypt(pad(msg, 16))
return (iv + ct).hex()如果前面的登录绕过使用空表单,服务端实际加密的明文就是 user=None。这一点非常重要,因为它给了后面做 CBC 位翻转的落点:我们并不需要伪造整段密文,只要把首块明文从 user=None 改成 user=admin 即可
题目的 session 只有加密,没有任何完整性校验。服务端解密时直接取出前 16 字节作为 IV,剩下部分当作密文,再将解密结果做 unpad:
def get_session_data(token_hex):
if not token_hex: return None
data = bytes.fromhex(token_hex)
iv, ct = data[:16], data[16:]
cipher = AES.new(KEY, AES.MODE_CBC, iv)
decrypted = cipher.decrypt(ct)
return unpad(decrypted, 16).decode(errors='ignore')CBC 的首块满足
P1 = D(C1) xor IVC1 不变时,只要改 IV,就能把首块明文改成任意同长度内容。这里原始首块和目标首块分别是:
orig = b"user=None" + 7 * b"\x07"
target = b"user=admin" + 6 * b"\x06"两者长度都正好是 16 字节,因此可以直接按位异或:
new_iv = iv xor orig xor target把新的 IV 和原来的 C1 拼回去,就是一份仍然能正常解密、但首块内容已经变成 user=admin 的合法 cookie。首页对用户名的判断只看解密结果里 user= 后面的内容,因此这一步足够把身份提升到管理员
这题做到这里就已经结束了。整个过程并不依赖密钥恢复,也不需要构造额外分组,核心只有两步:先用缺失字段把 None == None 这条分支踩出来,再借这份合法密文做一次标准的 CBC bit flipping
# python 3.8
import re
import requests
BASE = "http://nc1.ctfplus.cn:40834"
def bxor(a: bytes, b: bytes, c: bytes) -> bytes:
return bytes(x ^ y ^ z for x, y, z in zip(a, b, c))
# 1) 空表单 POST,触发 None == None 绕过
r = requests.post(
f"{BASE}/login",
data={}, # 不能写 {"username":"","password":""}
allow_redirects=False,
timeout=10
)
orig_token = r.cookies.get("session")
if not orig_token:
print("[-] login bypass failed")
print("status =", r.status_code)
print("headers =", r.headers)
print("body =", r.text)
raise SystemExit
print("[+] original token:", orig_token)
raw = bytes.fromhex(orig_token)
iv, ct = raw[:16], raw[16:]
# 原始首块明文: b"user=None" + 7 * b"\x07"
orig_p1 = b"user=None" + bytes([7]) * 7
# 目标首块明文: b"user=admin" + 6 * b"\x06"
target_p1 = b"user=admin" + bytes([6]) * 6
# CBC: P1 = D(C1) xor IV
# 只改 IV,就能把首块明文从 user=None 改成 user=admin
new_iv = bxor(iv, orig_p1, target_p1)
forged_token = (new_iv + ct).hex()
print("[+] forged token:", forged_token)
# 2) 不要复用 Session,直接手工带 forged cookie
r2 = requests.get(
f"{BASE}/",
headers={"Cookie": f"session={forged_token}"},
timeout=10
)
print("[+] sent cookie:", r2.request.headers.get("Cookie"))
print("[+] HTTP", r2.status_code)
print(r2.text)
m = re.search(r"xmctf\{.*?\}", r2.text)
if m:
print("[+] FLAG:", m.group(0))
else:
print("[-] flag not found")实际回显(复现版):
[+] original token: 6339985a77f29e1c73ebc5c98a7dd48bf41127f14fdafdb0ad1129e7108c16cf
[+] forged token: 6339985a77dd951f7f82c4c88b7cd58af41127f14fdafdb0ad1129e7108c16cf
[+] sent cookie: session=6339985a77dd951f7f82c4c88b7cd58af41127f14fdafdb0ad1129e7108c16cf
[+] HTTP 200
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>控制面板</title>
<style>
:root { --primary: #4f46e5; --bg: #f3f4f6; --card-bg: #ffffff; }
body { font-family: sans-serif; background-color: var(--bg); margin: 0; display: flex; flex-direction: column; align-items: center; }
/* 顶部导航栏 */
.navbar { width: 100%; background: white; padding: 1rem 2rem; box-shadow: 0 2px 4px rgba(0,0,0,0.05); display: flex; justify-content: space-between; align-items: center; box-sizing: border-box; }
.logo { font-weight: bold; color: var(--primary); font-size: 1.2rem; }
.logout-btn { text-decoration: none; color: #666; font-size: 0.9rem; padding: 0.5rem 1rem; border: 1px solid #ddd; border-radius: 0.5rem; transition: 0.2s; }
.logout-btn:hover { background: #fee2e2; color: #ef4444; border-color: #fca5a5; }
/* 内容卡片 */
.container { margin-top: 3rem; width: 90%; max-width: 600px; }
.card { background: var(--card-bg); padding: 2rem; border-radius: 1rem; box-shadow: 0 4px 6px rgba(0,0,0,0.05); text-align: center; }
h1 { color: #111; margin-bottom: 1.5rem; }
/* Flag 样式 */
.flag-box { background: #ecfdf5; border: 1px dashed #10b981; color: #065f46; padding: 1.5rem; border-radius: 0.5rem; font-family: monospace; font-size: 1.1rem; word-break: break-all; }
.normal-box { background: #fff7ed; border: 1px solid #fed7aa; color: #9a3412; padding: 1.5rem; border-radius: 0.5rem; }
</style>
</head>
<body>
<nav class="navbar">
<div class="logo">Secure Dashboard</div>
<a href="/login" class="logout-btn" onclick="document.cookie='session=; Max-Age=0; path=/;';">安全退出</a>
</nav>
<div class="container">
<div class="card">
<h1>你好, <span>admin</span>!</h1>
<div class="flag-box">
<strong>🎉 权限验证成功:</strong><br>
xmctf{1f5eec96-6ce9-4008-ac41-ba7b8c0331b1}
</div>
</div>
</div>
</body>
</html>
[+] FLAG: xmctf{1f5eec96-6ce9-4008-ac41-ba7b8c0331b1}ECC
题目整理
题目给出了一套形如椭圆曲线加法的运算规则。设消息对应的整数为 $m$,基点为 $G$,输出点为 $P$,并满足 $P = [m]G$
代码里的参数满足 $a = 0$,曲线方程可以直接写成 $y^2 + cy = x^3 + bx^2 + dx + e$
如果这是一条普通椭圆曲线,那么目标就是在这条曲线上求离散对数。这题并不需要去碰常规椭圆曲线算法,因为曲线本身就已经出了问题
方程整理
把左边配方,记 $Y = y + rac{c}{2}$。
方程变成 $Y^2 = x^3 + bx^2 + dx + e + rac{c^2}{4}$。
把题目里的参数代进去以后,右边会塌成一个完全立方。取 $r = -rac{b}{3}$,可以核对出 $d = 3r^2$,以及 $e + rac{c^2}{4} = -r^3$。
于是整条曲线实际上是 $Y^2 = x^3 - 3rx^2 + 3r^2x - r^3 = (x-r)^3$。
这说明它不是普通椭圆曲线,而是一条尖点奇异曲线。题目给出的加法公式表面上还保留着椭圆曲线的样子,但群结构已经退化了。
参数化与群结构
对非奇异点取 $u = rac{x-r}{Y}$。
由 $Y^2 = (x-r)^3$ 可得 $x-r = u^{-2}$,同时 $Y = u^{-3}$。
再换回原变量,就是 $x = r + u^{-2}$,$y = u^{-3} - rac{c}{2}$。
也就是说,曲线上每个非奇异点都可以用一个 $u$ 唯一表示。把这个参数化代回题目实现的加法公式,化简以后得到 $P(u_1) + P(u_2) = P(u_1 + u_2)$。
于是标量乘法也一起退化成了普通加法,满足 $[m]P(u) = P(mu)$。
题面上的曲线外观还在,内部的群结构却已经退化成了有限域上的普通加法
恢复消息
既然 $P = [m]G$,那么在参数 $u$ 下就有 $u(P) = m cdot u(G)$。
因此 $m = u(P) cdot u(G)^{-1} mod p$。
把题目给出的 $G$ 和 $P$ 代进去即可恢复消息整数 $m$,再转回字节串就能得到 flag。这里完全不需要跑任何离散对数算法,也不需要做群阶计算
exp
# Python 3.8+
p = 9259018534502783714631247560818133078409930397939705162361230465031580254504264713899169170790687716589100652406132800533397486109926387016562663961524649
a = 0
b = 6235467631650349040636525320446729529985562949423449382969614887116983248527693872546808737512375916974084741892428681798937790855872528526403738040908493
c = 4165903654767429195543540819098180314477702137507994424192636596518008877139978822038616746899053449640020812062736993008962585578921635697413459959685760
d = 1889382340373247565387211782596794283852946561870564309251998196824383297786878212641581641540685106266683503654620956037368416192796434147249748216284648
e = 3015564788819504594313842562882781366361783108618226049128986996153057550014499326419988348165744003693083108924831219996703133056523468396967900376388617
G = (
1244884551970947614719458919805713649754289814760243366205012699871413235954279930743612403791919112394457579170253990713250052822262255880036254772609156,
4579639528751113977115209571728128585569082149696598770106934145500742785077382446292613925719404433141749168427443122707253164477493499731016883616496009,
)
P = (
9039120379228240875764080238389949393433230267005269099421166553853462484353350917730468887801035670710981414900285176863179650428412616144755102163764906,
6266065680737729548475090556806928225106996606788926050268440244885398464756877886842570309216095272026404453765198968208595242208306240371310555394416694,
)
def inv(x):
return pow(x, -1, p)
def long_to_bytes(n: int) -> bytes:
if n == 0:
return b"\x00"
return n.to_bytes((n.bit_length() + 7) // 8, "big")
# ===== 题目原始群运算,用来做最终校验 =====
def add(P1, P2):
if P1 is None:
return P2
x1, y1 = P1
x2, y2 = P2
lam = (y2 - y1) * inv((x2 - x1) % p) % p
x3 = (lam * lam + a * lam - b - x1 - x2) % p
y3 = (lam * (x1 - x3) - y1 - a * x3 - c) % p
return (x3, y3)
def double(Pt):
if Pt is None:
return None
x, y = Pt
denom = (2 * y + a * x + c) % p
num = (3 * x * x + 2 * b * x + d - a * y) % p
lam = num * inv(denom) % p
x3 = (lam * lam + a * lam - b - 2 * x) % p
y3 = (lam * (x - x3) - y - a * x3 - c) % p
return (x3, y3)
def mul(k, Pt):
Q = None
while k:
if k & 1:
Q = add(Q, Pt)
Pt = double(Pt)
k >>= 1
return Q
# ===== 核心攻击 =====
# 原曲线:
# y^2 + c*y = x^3 + b*x^2 + d*x + e
#
# 令 Y = y + c/2,则
# Y^2 = x^3 + b*x^2 + d*x + (e + c^2/4)
#
# 这题右边其实是一个完全立方:
# (x - r)^3
# 因而曲线是尖点奇异曲线,不是安全的椭圆曲线。
inv2 = inv(2)
inv3 = inv(3)
inv4 = inv(4)
r = (-b * inv3) % p
const_term = (e + c * c * inv4) % p
# 验证确实是 (x - r)^3 = x^3 - 3r x^2 + 3r^2 x - r^3
assert (-3 * r - b) % p == 0
assert (3 * r * r - d) % p == 0
assert ((-pow(r, 3, p)) - const_term) % p == 0
# 对尖点曲线 Y^2 = (x-r)^3,
# 可用参数
# u = (x-r) / Y
# 把群运算化成 F_p 上的加法:
# u([m]G) = m * u(G)
def u_map(Pt):
x, y = Pt
Y = (y + c * inv2) % p
return ((x - r) % p) * inv(Y) % p
uG = u_map(G)
uP = u_map(P)
m = uP * inv(uG) % p
flag = long_to_bytes(m)
print("[+] m =", m)
print("[+] flag =", flag)
# 最后用题目的原始 mul 再验一次
assert mul(m, G) == P
print("[+] check passed")
'''
[+] m = 15332171262807319558091438562607183829793153852814538240060075529164504121457743104882975101
[+] flag = b'xmctf{A_s1ngu14r_Curv3_15_n0t_s3cur3!}'
[+] check passed
'''truck
题目结构
这道题的交互一共进行十轮。每一轮读入九段十六进制数据 A 到 I,然后依次通过三层 MD5 校验。第一层要求 md5(A) md5(B) md5(C) 相同。第二层要求 md5(ha + D) md5(hb + E) md5(hc + F) 相同,其中 ha = md5(A) hb = md5(B) hc = md5(C)。第三层要求 md5(hd + G) md5(he + H) md5(hf + I) 相同,其中 hd = md5(ha + D) he = md5(hb + E) hf = md5(hc + F)。除此之外,同一轮里的九段输入必须两两不同,十轮之间也不能复用任何一段消息。
题目表面上像是在连续处理三次三碰撞,真正需要抓住的却只有一条线。第一层通过以后,ha hb hc 已经被压成同一个值。第二层通过以后,hd he hf 也被压成同一个值。这样一来,后两层都不再是三条不同前缀上的碰撞,而是同一个前缀后面接三个不同后缀。整道题从头到尾都可以落回同一个子问题,也就是给定一个固定前缀 base,构造三个不同的 suffix,使 md5(base + x) md5(base + y) md5(base + z) 相同。
利用思路
常见的 MD5 碰撞工具直接给出的通常是二碰撞。这道题并不需要额外寻找专门的三碰撞工具,沿着 identical prefix collision 往下叠两次就够了。先在某个固定前缀下做一次碰撞,拿到两条不同消息 m0 和 m1,满足 md5(m0) = md5(m1)。再把 m0 连同额外的 tag 一起当成新的前缀,再做一次碰撞,拿到 n0 和 n1,满足 md5(n0) = md5(n1)。
这两次碰撞叠起来以后,第一组碰撞已经把 m0 和 m1 的内部状态对齐。第二组碰撞是在 m0 后面继续长出来的分支。把 n0 去掉共同前缀以后,剩下的那段后缀直接拼回 m1 后面,就能得到第三条消息。这样就得到三条不同消息,它们的 MD5 完全相同。题目三层里需要的都是这一类构造,只是每一层使用的共同前缀不同。
第一层使用空前缀,直接生成 A B C。这一步完成以后,ha hb hc 自然相同。第二层就以 ha 作为共同前缀生成 D E F。第二层完成以后,hd he hf 又被压成同一个值。第三层继续以 hd 作为共同前缀生成 G H I。代码里虽然按照题面写成了三条分支,实际做碰撞时每一层都只处理一个共同前缀。
工程细节
题目最后还有去重检查,这一部分不能靠碰撞工具顺带解决,必须在构造时主动处理。实现里把轮次和层编号都放进 tag 里,让每一轮每一层的碰撞前缀都不一样。这样可以把不同位置上的碰撞上下文彻底打散,避免同一轮内部出现重复块,也避免十轮之间碰撞出可复用的数据。构造完成以后,代码还会先检查当前这一轮的九段输入是否互异,再把十轮数据整体跑一遍完整断言,确认和题面的集合去重逻辑完全一致。
题目提交的是后缀,不是带前缀的完整消息。碰撞工具生成的是完整消息,所以在代码里还要把共同前缀从结果中统一裁掉,只保留真正需要发给远程的那一段数据。这个处理放在 triple_suffixes 里完成。这样一来,碰撞构造和远程交互就被拆开了,前者负责把数学结构做对,后者只负责把已经通过本地校验的数据按顺序送出去。
exp
from __future__ import annotations
import argparse
import hashlib
import json
import os
import socket
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Iterable
def H(m: bytes) -> bytes:
return hashlib.md5(m).digest()
CACHE_DIR = Path(".fastcoll_cache")
CACHE_DIR.mkdir(exist_ok=True)
class FastcollError(RuntimeError):
pass
def run_cmd(cmd: list[str], cwd: str) -> None:
p = subprocess.run(
cmd,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
if p.returncode != 0:
raise FastcollError(
f"command failed\n{p.stdout.decode(errors='replace')}"
)
def run_fastcoll(prefix: bytes, fastcoll: str, docker: bool = False) -> tuple[bytes, bytes]:
key = hashlib.sha256(prefix).hexdigest()
a_path = CACHE_DIR / f"{key}.a"
b_path = CACHE_DIR / f"{key}.b"
if a_path.exists() and b_path.exists():
return a_path.read_bytes(), b_path.read_bytes()
with tempfile.TemporaryDirectory(prefix="fc_") as td:
td_path = Path(td)
(td_path / "prefix.bin").write_bytes(prefix)
tried: list[list[str]] = []
if docker:
tried.append([
"docker", "run", "--rm",
"-v", f"{td}/work".replace("/work", ":/work"),
"-w", "/work",
"brimstone/fastcoll",
"--prefixfile", "prefix.bin",
"-o", "msg1.bin", "msg2.bin",
])
else:
tried.append([fastcoll, "--prefixfile", "prefix.bin", "-o", "msg1.bin", "msg2.bin"])
tried.append([fastcoll, "-p", "prefix.bin", "-o", "msg1.bin", "msg2.bin"])
last_err = None
for cmd in tried:
try:
if docker and cmd[3].endswith(":/work") is False:
cmd[3] = f"{td}:/work"
run_cmd(cmd, td)
m1 = (td_path / "msg1.bin").read_bytes()
m2 = (td_path / "msg2.bin").read_bytes()
if m1 == m2:
raise FastcollError("fastcoll returned identical messages")
if H(m1) != H(m2):
raise FastcollError("fastcoll returned non collision")
if not m1.startswith(prefix) or not m2.startswith(prefix):
raise FastcollError("fastcoll output does not preserve prefix")
a_path.write_bytes(m1)
b_path.write_bytes(m2)
return m1, m2
except Exception as e:
last_err = e
raise FastcollError(str(last_err))
def make_tag(*parts: object) -> bytes:
return ("|".join(str(x) for x in parts) + "|").encode()
def triple_collision(base: bytes, seed: bytes, fastcoll: str, docker: bool = False) -> tuple[bytes, bytes, bytes]:
tag1 = b"L1|" + seed + b"|"
m0, m1 = run_fastcoll(base + tag1, fastcoll=fastcoll, docker=docker)
tag2 = b"L2|" + seed + b"|"
n0, n1 = run_fastcoll(m0 + tag2, fastcoll=fastcoll, docker=docker)
ext0 = n0[len(m0 + tag2):]
c0 = n0
c1 = n1
c2 = m1 + tag2 + ext0
hs = {H(c0), H(c1), H(c2)}
if len(hs) != 1:
raise AssertionError("3 way collision construction failed")
if len({c0, c1, c2}) != 3:
raise AssertionError("3 way collision messages are not distinct")
return c0, c1, c2
def triple_suffixes(base: bytes, seed: bytes, fastcoll: str, docker: bool = False) -> tuple[bytes, bytes, bytes]:
a, b, c = triple_collision(base, seed, fastcoll=fastcoll, docker=docker)
return a[len(base):], b[len(base):], c[len(base):]
def build_round(round_id: int, fastcoll: str, docker: bool = False) -> tuple[bytes, ...]:
A, B, C = triple_suffixes(b"", make_tag("ROUND", round_id, "ABC"), fastcoll, docker)
ha, hb, hc = H(A), H(B), H(C)
assert ha == hb == hc
D, E, F = triple_suffixes(ha, make_tag("ROUND", round_id, "DEF"), fastcoll, docker)
hd, he, hf = H(ha + D), H(hb + E), H(hc + F)
assert hd == he == hf
G, H_, I = triple_suffixes(hd, make_tag("ROUND", round_id, "GHI"), fastcoll, docker)
assert H(hd + G) == H(he + H_) == H(hf + I)
cur = (A, B, C, D, E, F, G, H_, I)
if len(set(cur)) != 9:
raise AssertionError(f"round {round_id} items inside round are not all distinct")
return cur
def validate(rounds: Iterable[tuple[bytes, ...]]) -> None:
S: set[bytes] = set()
for rid, cur in enumerate(rounds):
A, B, C, D, E, F, G, H_, I = cur
ha, hb, hc = H(A), H(B), H(C)
assert ha == hb == hc, f"round {rid} first collision failed"
hd, he, hf = H(ha + D), H(hb + E), H(hc + F)
assert hd == he == hf, f"round {rid} second collision failed"
assert H(hd + G) == H(he + H_) == H(hf + I), f"round {rid} third collision failed"
assert len(set(cur)) == 9, f"round {rid} duplicate inside current round"
assert not any(x in S for x in cur), f"round {rid} reused payload across rounds"
S.update(cur)
class Tube:
def __init__(self, host: str | None = None, port: int | None = None, cmd: str | None = None):
self.proc = None
self.sock = None
if cmd is not None:
self.proc = subprocess.Popen(
cmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
self.r = self.proc.stdout
self.w = self.proc.stdin
else:
self.sock = socket.create_connection((host, port))
self.r = self.sock.makefile("rb", buffering=0)
self.w = self.sock.makefile("wb", buffering=0)
def recvuntil(self, token: bytes) -> bytes:
buf = bytearray()
while token not in buf:
ch = self.r.read(1)
if not ch:
raise EOFError(bytes(buf).decode(errors="replace"))
buf += ch
return bytes(buf)
def sendlineafter(self, token: bytes, data: bytes) -> None:
self.recvuntil(token)
self.w.write(data + b"\n")
self.w.flush()
def recvall(self) -> bytes:
return self.r.read() or b""
def submit(rounds: list[tuple[bytes, ...]], host: str | None, port: int | None, cmd: str | None) -> str:
io = Tube(host=host, port=port, cmd=cmd)
prompts = [b"A > ", b"B > ", b"C > ", b"D > ", b"E > ", b"F > ", b"G > ", b"H > ", b"I > "]
for cur in rounds:
for prompt, x in zip(prompts, cur):
io.sendlineafter(prompt, x.hex().encode())
out = io.recvall().decode(errors="replace")
return out
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--host", help="remote host")
ap.add_argument("--port", type=int, help="remote port")
ap.add_argument("--cmd", help="local process")
ap.add_argument("--fastcoll", default=os.environ.get("FASTCOLL", "./fastcoll"))
ap.add_argument("--docker-fastcoll", action="store_true")
ap.add_argument("--dump-json", default="rounds.json")
args = ap.parse_args()
rounds = [build_round(i, fastcoll=args.fastcoll, docker=args.docker_fastcoll) for i in range(10)]
validate(rounds)
Path(args.dump_json).write_text(
json.dumps([[x.hex() for x in r] for r in rounds], indent=2)
)
print(f"[+] generated and validated 10 rounds, saved to {args.dump_json}", file=sys.stderr)
if args.host and args.port:
print(submit(rounds, args.host, args.port, None))
elif args.cmd:
print(submit(rounds, None, None, args.cmd))
else:
print("[*] no target specified, generation self test only", file=sys.stderr)
if __name__ == "__main__":
main()实际回显如下:
python solve.py --docker-fastcoll --host nc1.ctfplus.cn --port 49619
[+] generated and validated 10 rounds, saved to rounds.json
good: xmctf{3a494173-8c62-4a82-8632-0d0afbe4c6e6}神秘学
题目复盘
题目给出了一段看似将 RSA 与三次多项式混在一起的代码。RSA 部分并不复杂:生成 p,q 后得到 n=pq,随后取一个隐藏在 secret 中的整数 c,令 e = inverse(c, phi),最终加密得到 cipher = m^e mod n。这意味着一旦能够恢复出 c,解密过程就会立刻转化为
$$
m = cipher^c mod n
$$
真正扰乱视线的是 get_poly(k)。函数中构造了
$$
f(x)=x^3-ax^2+bx-c-kn
$$
随后只输出了某个随机点 x1 处的一阶导数值。表面上看,题目把多项式常数项完全藏掉了,似乎既不能直接碰到 c,也不能借此分解 n。如果沿着常规 RSA 方向去做,无论是尝试分解 1024 位模数,还是直接区间爆破 c,都会很快卡在复杂度上。尤其是后者,哪怕有 xmctf{...} 这样的前缀可供筛选,搜索空间依旧过大,不具备实战可行性。整道题真正的突破口,不在于继续扩大搜索,而在于把未知量从 c 压缩到题目已经明确给出范围的 k 上。
结构回收与关键突破
对三次多项式求导后有
$$
f'(x)=3x^2-2ax+b
$$
代入题目输出的 x1 和 deriv1_num,可以得到
$$
3x_1^2-2a_1x_1+b_1= ext{deriv1num}
$$
这里最关键的观察是数量级差。题目中 x1 是 511 bit 量级,而 a1,b1 只有约 120 bit,因此 2a_1x_1 会压倒性地主导这一式子,b1 只是一个很小的修正项。于是令
$$
T=3x_1^2- ext{deriv1num}=2a_1x_1-b_1
$$
那么 a1 实际上就是 T/(2x1) 的向上取整。写成程序就是
T = 3 * x1 * x1 - deriv1_num
a1 = T // (2 * x1) + 1
b1 = deriv1_num - 3 * x1 * x1 + 2 * a1 * x1至此,导数信息已经被完整回收成了原三次式中的两个系数 a1,b1。如果这一步做不出来,后面的所有尝试都只能停留在盲猜阶段;而一旦这一步做出来,题目里真正还能自由变化的就只剩下 k 与 c 的耦合关系。题目给出 k = getPrime(8),也就是说 k 只可能是 2 到 255 之间的 8-bit 素数,总数极少。这一限制把原本不可操作的问题,直接压缩成了几十次模幂运算的枚举题
实战中可行的利用方式是,先用导数恢复 a1,b1,再把对应的 c 候选写成
$$
c = x_1^3-a_1x_1^2+b_1x_1-kn
$$
接着枚举所有 8-bit 素数 k,计算
$$
m = cipher^c mod n
$$
并用题目已知的 flag 前缀 xmctf{ 做唯一性筛选。这一步之所以是整题从“能做”到“能在时限内做完”的分界点,原因非常明确:如果枚举对象还是 c,即使只扫到几千万量级也没有任何保证;而把搜索对象改成 k 以后,复杂度会被压到几十次大整数模幂,耗时几乎可以忽略。题目的核心并不在于多项式本身有多复杂,而在于导数给出的信息足够把高复杂度搜索转化为低复杂度枚举
带入题目数据后,枚举会唯一命中 k = 173,对应明文为
xmctf{e6d787beb9230217e692e130f718cdeb}实现细节与完整脚本
这道题实现上没有额外工程难点,真正需要注意的只有两处。第一,恢复 a1 时必须利用 b1 相对 2a_1x_1 很小这一事实,因此写法上应直接使用整除加一的方式完成向上取整。第二,筛选时不要用“是否为可打印字符串”这种宽松条件,而应直接检查 xmctf{ 前缀,这样可以保证命中结果唯一,也能避免在错误的 k 上浪费额外判断成本。整个求解过程非常短,但前提是前面的结构分析必须准确,否则就会在无意义的爆破里消耗时间
from sympy import primerange
n = 63407394080105297388278430339692150920405158535377818019441803333853224630295862056336407010055412087494487003367799443217769754070745006473326062662322624498633283896600769211094059989665020951007831936771352988585565884180663310304029530702695576386164726400928158921458173971287469220518032325956366276127
x1 = 3481408902400626584294863390184557833125008467348169645656825368985677578418186933223051810792813745190000132321911937970968840332589150965113386330575858
deriv1_num = 36360623837143006554133449776905822223850034204333042340303731846698251185379183585401025894584873826284649058526470710038176516677326058549625930550928515944115160614909195746688504416967586844354012895944251800672195553936202084073217078119494546421088598245791873936703883718926122761577400400368341859847
cipher = 17359360992646515022812225990358117265652240629363564764503325024700251560440679272576574598620940996876220276588413345495658258508097150181947839726337961689195064024953824539654084620226127592330054674517861032601638881355220119605821814412919221685287567648072575917662044603845424779210032794782725398473
T = 3 * x1 * x1 - deriv1_num
a1 = T // (2 * x1) + 1
b1 = deriv1_num - 3 * x1 * x1 + 2 * a1 * x1
for k in primerange(2, 256):
c = x1 ** 3 - a1 * x1 ** 2 + b1 * x1 - k * n
m = pow(cipher, c, n)
msg = m.to_bytes((m.bit_length() + 7) // 8, "big")
if msg.lower().startswith(b"xmctf{"):
print(k, msg.decode())
break
'''
173 xmctf{e6d787beb9230217e692e130f718cdeb}
'''sda
数据来源于kimi找到的论文 (http://psasir.upm.edu.my/id/eprint/113455/1/113455.pdf)
有了这份数据之后就可以很顺利的解出来了
解题过程
这是一道基于RSA变体和Coppersmith方法的密码学题目。题目利用了广义近似公因数问题(Generalized Approximate Common Divisor Problem, GACDP)的弱点。
关键步骤:
理解题目结构:题目给出了三个RSA模数 A1,A2,A3 和对应的 B1,B2,B3 ,以及它们与未知数 xi,y,zi 的关系:
Bi⋅xi2−y2⋅ϕ(Ai)=zi
发现关键线索:通过搜索,我发现这道题目直接来自一篇学术论文的完整数值示例。论文中已经通过LLL格基约简算法计算出了所有未知数的值:
y2=79534770917548
x12=270773515245763
x22=383729843021257
x32=363893359279085
计算密钥:
密钥材料:y2+x12⋅x22⋅x32=37809931389334630532200974347582386796954283
AES密钥:792e6c60d646b02f1f97c5c04aeb2c62(SHA256哈希的前16字节)
解密flag:
使用AES-128-CBC模式解密
成功获得flag"""
SDA题目完整求解脚本
基于RSA变体和Coppersmith方法的攻击
"""
from Crypto.Util.number import *
from Crypto.Util.Padding import unpad
from Crypto.Cipher import AES
import hashlib
# ==================== 题目给出的参数 ====================
A1 = 234110215243875326749544596075512335544257
B1 = 68765596672109672407420253033782942222910
A2 = 636185906634748653451789798738597280632127
B2 = 131860738134887128678021271054606611917493
A3 = 905712574946398586494048707872100065355613
B3 = 197958111431918701470218006359610095848736
As = [A1, A2, A3]
Bs = [B1, B2, B3]
# 密文
CIPHERTEXT_HEX = "93192f46a00b2dade984ca758706b00681263a8536d8051aff0206d257ce4c2aad6bc017138d4c7aeaed5c8fc2c1ea2f3cec3fbd9201bb5844fa8143d6630944"
# ==================== 步骤1: 分解A1, A2, A3 ====================
print("=" * 60)
print("步骤1: 分解RSA模数")
print("=" * 60)
# 使用Pollard's rho算法或其他方法分解
# 这里直接给出分解结果(可通过在线工具或论文获得)
p1, q1 = 1090572505187971645529, 214667263414571384233
p2, q2 = 828869186640649439797, 767534753237922809891
p3, q3 = 1165370758345329049639, 777188348395140418267
ps = [p1, p2, p3]
qs = [q1, q2, q3]
phis = []
for i in range(3):
Ai = ps[i] * qs[i]
phi_i = (ps[i] - 1) * (qs[i] - 1)
phis.append(phi_i)
print(f"A{i+1} = {As[i]}")
print(f" p{i+1} = {ps[i]}")
print(f" q{i+1} = {qs[i]}")
print(f" phi(A{i+1}) = {phi_i}")
print()
# ==================== 步骤2: 使用Coppersmith方法求解 ====================
print("=" * 60)
print("步骤2: 使用Coppersmith/LLL方法求解未知数")
print("=" * 60)
"""
根据论文 "Coppersmith's Method and Generalizations" 中的数值示例,
通过LLL格基约简算法已经计算出:
- Y = y^2 = 79534770917548
- X1 = x1^2 = 270773515245763
- X2 = x2^2 = 383729843021257
- X3 = x3^2 = 363893359279085
这些值满足方程: B_i * X_i - Y * phi_i = z_i
"""
# 论文给出的解
Y = 79534770917548
X1 = 270773515245763
X2 = 383729843021257
X3 = 363893359279085
xs_squared = [X1, X2, X3]
print(f"y^2 = {Y}")
print(f"x1^2 = {X1}")
print(f"x2^2 = {X2}")
print(f"x3^2 = {X3}")
print()
# 验证解的正确性
print("验证方程 B_i * x_i^2 - y^2 * phi(A_i) = z_i:")
for i in range(3):
zi = Bs[i] * xs_squared[i] - Y * phis[i]
print(f" z{i+1} = {zi}")
print()
# ==================== 步骤3: 计算AES密钥 ====================
print("=" * 60)
print("步骤3: 计算AES密钥")
print("=" * 60)
# 密钥材料 = y^2 + x1^2 * x2^2 * x3^2
key_material_int = Y + X1 * X2 * X3
print(f"密钥材料 (整数): {key_material_int}")
# 转换为字节
key_material_bytes = key_material_int.to_bytes(
(key_material_int.bit_length() + 7) // 8,
'big'
)
print(f"密钥材料 (字节): {key_material_bytes.hex()}")
# SHA256哈希取前16字节作为AES密钥
aes_key = hashlib.sha256(key_material_bytes).digest()[:16]
print(f"AES密钥: {aes_key.hex()}")
print()
# ==================== 步骤4: 解密flag ====================
print("=" * 60)
print("步骤4: 解密flag")
print("=" * 60)
# 解析密文
iv = bytes.fromhex(CIPHERTEXT_HEX[:32])
ciphertext = bytes.fromhex(CIPHERTEXT_HEX[32:])
print(f"IV: {iv.hex()}")
print(f"Ciphertext: {ciphertext.hex()}")
print(f"Ciphertext length: {len(ciphertext)} bytes")
print()
# AES-128-CBC解密
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext)
print(f"解密后 (hex): {plaintext.hex()}")
print(f"解密后 (raw): {plaintext}")
print()
# 去除PKCS7填充
flag = unpad(plaintext, AES.block_size)
flag_str = flag.decode('utf-8')
print("=" * 60)
print(f"FLAG: {flag_str}")
print("=" * 60)
'''
============================================================
步骤1: 分解RSA模数
============================================================
A1 = 234110215243875326749544596075512335544257
p1 = 1090572505187971645529
q1 = 214667263414571384233
phi(A1) = 234110215243875326748239356306909792514496
A2 = 636185906634748653451789798738597280632127
p2 = 828869186640649439797
q2 = 767534753237922809891
phi(A2) = 636185906634748653450193394798718708382440
A3 = 905712574946398586494048707872100065355613
p3 = 1165370758345329049639
q3 = 777188348395140418267
phi(A3) = 905712574946398586492106148765359595887708
============================================================
步骤2: 使用Coppersmith/LLL方法求解未知数
============================================================
y^2 = 79534770917548
x1^2 = 270773515245763
x2^2 = 383729843021257
x3^2 = 363893359279085
验证方程 B_i * x_i^2 - y^2 * phi(A_i) = z_i:
z1 = 224130168254522
z2 = 99715438091581
z3 = 314449433786576
============================================================
步骤3: 计算AES密钥
============================================================
密钥材料 (整数): 37809931389334630532200974347582386796954283
密钥材料 (字节): 01b20966e1cb6dd7cfb60b4854b5aaa6af02ab
AES密钥: 792e6c60d646b02f1f97c5c04aeb2c62
============================================================
步骤4: 解密flag
============================================================
IV: 93192f46a00b2dade984ca758706b006
Ciphertext: 81263a8536d8051aff0206d257ce4c2aad6bc017138d4c7aeaed5c8fc2c1ea2f3cec3fbd9201bb5844fa8143d6630944
Ciphertext length: 48 bytes
解密后 (hex): 786d6374667b31663166353935633638343930333061616435656565333866383536643866667d090909090909090909
解密后 (raw): b'xmctf{1f1f595c6849030aad5eee38f856d8ff}\t\t\t\t\t\t\t\t\t'
============================================================
FLAG: xmctf{1f1f595c6849030aad5eee38f856d8ff}
============================================================
'''RSA_LCG
已知的是 N、e、a、(b-a)^e mod N、x_1^e mod N 和 x_2^e mod N,其中
x_0 = secret
x_1 = a x_0 + b mod N
x_2 = a x_1 + b mod N目标是在 4 秒内恢复 64 字节的 secret
解题思路
把 d = b-a mod N 单独记出来之后,递推会变得规整很多。因为 b = a + d mod N,所以
x_1 = a x_0 + a + d = a(x_0 + 1) + d
x_2 = a x_1 + a + d题目真正泄露的是三份 e 次幂:d^e、x_1^e、x_2^e。这组信息的结构不是直接去碰 x_0,而是先把 d 拿出来,再用 d 还原 x_1,最后才回到 x_0。这条链子一旦顺下来,数学部分并不复杂,真正决定能否过题的是实现是否足够快
恢复 d
记
A = out1 = x_1^e
C = out2 · (a^e)^(-1) mod N由
x_2 = a x_1 + a + d = a(x_1 + 1 + d/a)可得
C = (x_1 + 1 + d/a)^e再把
u = x_1
v = x_1 + 1 + d/a代进去,此时已知的是 u^e = A 与 v^e = C,而两者的差满足
v - u = 1 + d/a问题的关键在这里。虽然 u 和 v 本身都未知,但它们各自的 e 次幂已经给出。把 u 的全部 e 个共轭根与 v 的全部 e 个共轭根做差,可以得到一组只依赖 (v-u)^e 的代数量。先从这些差值构造 power sums,再用 Newton identities 还原基本对称多项式,就能得到一个关于
T = (1 + d/a)^e的首一多项式 Q(T)
接下来把未知量重新落回 d。在商环
Z/NZ[D] / (D^e - leak)里有
T(D) = (1 + D/a)^e mod (D^e - leak)于是可以继续构造
R(D) = Q(T(D)) mod (D^e - leak)真实的 d 同时满足 D^e = leak 与 Q(T(D)) = 0,因此 D-d 必然是
gcd(D^e - leak, R(D))的线性因子。把这个线性因子提出来,d 就恢复出来了
恢复 x_1
d 已知以后,b = a + d mod N 也随之确定。于是 x_1 同时满足
x_1^e = out1
(a x_1 + b)^e = out2这一步直接走 Franklin-Reiter。令变量为 X,构造
F(X) = X^e - out1
G(X) = (aX + b)^e - out2真实的 x_1 是这两个多项式的公共根,所以两者的最大公因子会退化成线性因子
X - x_1从这里就能把 x_1 提出来
恢复 secret
由
x_1 = a(x_0 + 1) + d - tN可知这里的进位只可能落在 t = 0 或 t = 1。因此只需要枚举这两种情况,检查
num = x1 - d + t * N
if num % a == 0:
x0 = num // a - 1随后再验证 x_0 是否满足长度约束,并且重新带回去核对 d^e、x_1^e 和 x_2^e。验证通过时,64 字节的 secret 就已经恢复完成
时间瓶颈
这道题真正的压力不在数学推导,而在 4 秒的时限。攻击链本身并不长,但实现里有三个位置非常吃时间,任何一个地方处理得不对,最终都压不进时限
第一个热路径是 Q(T) 的构造。这里要做的是大量 2048-bit 模数下的乘法、求逆和组合数运算,完全落在大整数算术上。思路正确并不代表 Python 原生 int 足够快,实际 profile 里,单是这一步就会吞掉 2 到 3 秒
第二个热路径是多项式复合,也就是把 Q(T) 代入到 T(D) 里,再模掉 D^e - leak。如果直接调用 FLINT 自带的 compose_mod,结果虽然对,但在本题这个参数规模下并不理想。e = 263,deg(Q) = 263,deg(T) < 263,模多项式又固定成 D^e - leak,这是一个非常适合定制实现的规模,直接走通用接口会浪费不少时间
第三个问题出在多项式 gcd。这里的底层模数是复合数 N = pq,而不是素数。FLINT 在这种情况下不能直接做 gcd,会抛出 DomainError,随后只能退回到纯 Python 的多项式 Euclid。前两步已经比较重,再在这里退回 Python,时间会继续被拉长
也就是说,数学攻击已经足够,但实现上真正需要解决的是三件事:build_Q 太慢,compose_mod 太慢,复合模数下的 gcd 不能直接调用库函数
关键优化
真正起作用的优化集中在两个核心热路径和一个收尾阶段
build_Q 这一段本质是海量大整数模运算,把它继续留给 Python 原生 int 没有意义。直接换成 gmpy2 之后,powmod、invert、阶乘表、逆阶乘表、power sums 和 Newton identities 都交给 GMP 去做,这一步的耗时会立刻下降。代码里保留了一个兼容分支,在没有 gmpy2 时仍然可以退回 Python,但真正用于过题的是 gmpy2 这条路径
多项式复合这一段则没有继续使用 FLINT 的 compose_mod,而是按本题的规模重写了一份 block compose。做法本身并不复杂,核心是 baby-step / giant-step 的切块思想。先预处理 1, T, T^2, ..., T^(B-1),再把 Q 的系数按每 B 项一块切开,每块用已经算好的低次幂线性组合,最后再用 Y = T^B 做 Horner 合并。这里真正被频繁调用的仍然是 FLINT 的 mul_mod,但复合策略已经换成了更适合本题参数的版本
这一部分对应的核心实现就是:
def compose_block_flint(ctx, q_poly, t_poly, mod_poly, block=16):
coeffs = [int(q_poly[i]) for i in range(q_poly.degree() + 1)]
one = ctx([1])
t_pows = [one]
for _ in range(1, block):
t_pows.append(t_pows[-1].mul_mod(t_poly, mod_poly))
y_poly = t_pows[-1].mul_mod(t_poly, mod_poly)
blocks = []
for start in range(0, len(coeffs), block):
acc = ctx([0])
for j, c in enumerate(coeffs[start:start + block]):
if c:
acc += t_pows[j] * c
blocks.append(acc)
acc = ctx([0])
for poly in reversed(blocks):
acc = acc.mul_mod(y_poly, mod_poly)
acc += poly
return acc % mod_poly最后的 gcd 阶段没有继续指望 FLINT 在复合模数下直接给出答案,而是只借用它能正常工作的余式运算。做法是手写一条多项式余式链,不断取模,把次数一路降下去;次数一旦掉到 1,就立刻从线性多项式里把根提出来。这样可以避开纯 Python 的多项式长除,同时也绕开复合模数下 gcd 的限制
整个提速过程的重点不在语法层面的微调,而在于把最热的算术路径全部换掉。大整数模运算交给 GMP,多项式模乘交给 FLINT,多项式复合和取根策略则按本题规模单独实现。这样处理之后,性能瓶颈才真正被打穿
最终耗时
远端实测的时间分布如下(甚至轻薄本):
prep为0.103sbuild_Q为0.557scompose为0.555sgcd_d为0.187sgcd_x1为0.199srecover近似为0s- 总耗时为
1.602s
最终成功返回:
Good! Here is your flag: XMCTF{209ed1a2-aa39-4944-b782-ac07ec6784a2}这组数据本身已经把题目的关键点说得很清楚了。数学部分从来不是问题,真正决定胜负的是实现层面的热路径替换。只要 build_Q、多项式复合和复合模数下的取根还停留在慢实现上,这题就只是“能解”;把这几个位置全部压下来以后,才真正变成“能在 4 秒内稳定解出”
exp
#!/usr/bin/env python3
from time import perf_counter
import flint
from pwn import context, remote
try:
import gmpy2
except Exception:
gmpy2 = None
HOST = "nc1.ctfplus.cn"
PORT = 36602
e = 263
M = e * e
DEBUG = False
def is_probable_prime_64(n):
if n < 2:
return False
small_primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
for p in small_primes:
if n % p == 0:
return n == p
d = n - 1
s = 0
while d % 2 == 0:
s += 1
d //= 2
for a in (2, 325, 9375, 28178, 450775, 9780504, 1795265022):
if a % n == 0:
continue
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
for _ in range(s - 1):
x = x * x % n
if x == n - 1:
break
else:
return False
return True
def generate_crt_primes(limit_bits):
primes = []
prod_bits = 0
cand = (1 << 61) - 1
while prod_bits <= limit_bits + 4:
if cand % e and is_probable_prime_64(cand):
primes.append(cand)
prod_bits += cand.bit_length()
cand -= 2
return primes
CRT_PRIMES = generate_crt_primes(5000)
def build_fact_tables(mod):
fact = [1] * (M + 1)
for i in range(1, M + 1):
fact[i] = fact[i - 1] * i % mod
ifact = [1] * (M + 1)
ifact[M] = pow(fact[M], -1, mod)
for i in range(M, 0, -1):
ifact[i - 1] = ifact[i] * i % mod
return fact, ifact
def to_modint(x):
if gmpy2 is not None:
return gmpy2.mpz(x)
return x
def mod_pow(a, b, mod):
if gmpy2 is not None:
return gmpy2.powmod(to_modint(a), b, mod)
return pow(a, b, mod)
def mod_inv(a, mod):
if gmpy2 is not None:
return gmpy2.invert(to_modint(a), mod)
return pow(a, -1, mod)
def batch_invert(values, mod):
n = len(values)
prefix = [1] * n
acc = 1
for i, v in enumerate(values):
acc = acc * (v % mod) % mod
prefix[i] = acc
inv_acc = mod_inv(acc, mod)
out = [0] * n
for i in range(n - 1, -1, -1):
prev = prefix[i - 1] if i else 1
out[i] = inv_acc * prev % mod
inv_acc = inv_acc * (values[i] % mod) % mod
return out
def monic_poly(poly, mod):
deg = poly.degree()
if deg < 0:
return poly
lc = int(poly[deg]) % mod
inv_lc = int(mod_inv(lc, mod))
if inv_lc == 1:
return poly
return poly * inv_lc
def linear_root_from_gcd(P1, P2, N):
A = monic_poly(P1, N)
B = monic_poly(P2, N)
while True:
deg_b = B.degree()
if deg_b == 1:
c0 = int(B[0]) % N
c1 = int(B[1]) % N
return (-c0 * int(mod_inv(c1, N))) % N
R = A % B
if R.degree() < 0:
if deg_b != 1:
raise ValueError(f"unexpected gcd degree = {deg_b}")
c0 = int(B[0]) % N
c1 = int(B[1]) % N
return (-c0 * int(mod_inv(c1, N))) % N
A, B = B, monic_poly(R, N)
def crt_pair(r1, m1, r2, m2):
inv = mod_inv(m1 % m2, m2)
t = (r2 - r1) % m2
k = t * inv % m2
mod = m1 * m2
return (r1 + m1 * k) % mod, mod
def compose_block_flint(ctx, q_poly, t_poly, mod_poly, block=16):
coeffs = [int(q_poly[i]) for i in range(q_poly.degree() + 1)]
one = ctx([1])
t_pows = [one]
for _ in range(1, block):
t_pows.append(t_pows[-1].mul_mod(t_poly, mod_poly))
y_poly = t_pows[-1].mul_mod(t_poly, mod_poly)
blocks = []
for start in range(0, len(coeffs), block):
acc = ctx([0])
for j, c in enumerate(coeffs[start:start + block]):
if c:
acc += t_pows[j] * c
blocks.append(acc)
acc = ctx([0])
for poly in reversed(blocks):
acc = acc.mul_mod(y_poly, mod_poly)
acc += poly
return acc % mod_poly
def parse_instance(io):
line = io.recvline().decode().strip()
N = int(line.split("=", 1)[1].strip())
line = io.recvline().decode().strip()
ee = int(line.split("=", 1)[1].strip())
if ee != e:
raise ValueError(f"unexpected e = {ee}")
io.recvline()
line = io.recvline().decode().strip()
inside = line.split("(", 1)[1].rsplit(")", 1)[0]
a_str, leak_str = inside.split(", ")
a = int(a_str)
leak = int(leak_str)
line = io.recvline().decode().strip()
out1 = int(line.split(":", 1)[1].strip())
line = io.recvline().decode().strip()
out2 = int(line.split(":", 1)[1].strip())
io.recvuntil(b"secret (hex):")
return N, a, leak, out1, out2
def solve_instance(N, a, leak, out1, out2, verbose=False):
t0 = perf_counter()
mod = to_modint(N)
fact, ifact = build_fact_tables(mod)
ae = mod_pow(a, e, mod)
ae_inv = mod_inv(ae, mod)
A = to_modint(out1)
C = to_modint(out2) * ae_inv % mod
Ap = [1] * (e + 1)
Cp = [1] * (e + 1)
for i in range(1, e + 1):
Ap[i] = Ap[i - 1] * A % mod
Cp[i] = Cp[i - 1] * C % mod
block = [0] * e
block_inv = [0] * e
for j in range(e):
lo = j * e
hi = lo + e
block[j] = fact[hi] * ifact[lo] % mod
block_inv[j] = fact[lo] * ifact[hi] % mod
t1 = perf_counter()
p = [0] * (e + 1)
for m in range(1, e + 1):
coeff = 1
s = 0
for k in range(m + 1):
term = coeff * Ap[k] * Cp[m - k] % mod
s = s - term if (k & 1) else s + term
if k != m:
coeff = coeff * block[m - k - 1] * block_inv[k] % mod
p[m] = (e * (s % mod)) % mod
inv = [0] + batch_invert(list(range(1, e + 1)), mod)
elem = [0] * (e + 1)
elem[0] = 1
for m in range(1, e + 1):
s = 0
sign = 1
for i in range(1, m + 1):
term = elem[m - i] * p[i] % mod
s = s + term if sign == 1 else s - term
sign = -sign
elem[m] = (s % mod) * inv[m] % mod
Q_desc = [1]
for i in range(1, e + 1):
coef = (-elem[i]) % mod if (i & 1) else elem[i]
Q_desc.append(coef)
t2 = perf_counter()
ctx = flint.fmpz_mod_poly_ctx(N)
D = ctx.gen()
ainv = mod_inv(a, mod)
binom_e = [0] * (e + 1)
fn_e = fact[e]
for i in range(e + 1):
binom_e[i] = fn_e * ifact[i] % mod * ifact[e - i] % mod
T = [0] * e
pow_ainv = 1
for i in range(e):
if i:
pow_ainv = pow_ainv * ainv % mod
T[i] = int(binom_e[i] * pow_ainv % mod)
T[0] = int((to_modint(T[0]) + binom_e[e] * ae_inv % mod * to_modint(leak)) % mod)
Q = ctx([int(c) for c in reversed(Q_desc)])
Tpoly = ctx(T)
P_D = D**e - leak
R = compose_block_flint(ctx, Q, Tpoly, P_D, 16)
t3 = perf_counter()
d = linear_root_from_gcd(P_D, R, N)
t4 = perf_counter()
X = ctx.gen()
F = X**e - out1
G = (a * X + (a + d))**e - out2
x1 = linear_root_from_gcd(F, G, N)
t5 = perf_counter()
candidate_secret = None
for t in (0, 1):
num = x1 - d + t * N
if num < 0 or num % a:
continue
x0 = num // a - 1
if not (0 <= x0 < (1 << 512)):
continue
b = (a + d) % N
xx1 = (a * x0 + b) % N
xx2 = (a * xx1 + b) % N
if pow(d, e, N) != leak:
continue
if pow(xx1, e, N) != out1:
continue
if pow(xx2, e, N) != out2:
continue
candidate_secret = int(x0).to_bytes(64, "big")
break
if candidate_secret is None:
raise ValueError("failed to recover valid seed")
t6 = perf_counter()
if verbose:
print(f"[time] prep = {t1 - t0:.3f}s")
print(f"[time] build_Q = {t2 - t1:.3f}s")
print(f"[time] compose = {t3 - t2:.3f}s")
print(f"[time] gcd_d = {t4 - t3:.3f}s")
print(f"[time] gcd_x1 = {t5 - t4:.3f}s")
print(f"[time] recover = {t6 - t5:.3f}s")
print(f"[time] total = {t6 - t0:.3f}s")
return candidate_secret
def solve_instance_crt(N, a, leak, out1, out2, verbose=False):
t0 = perf_counter()
d_acc = 0
x1_acc = 0
mod_acc = 1
used = 0
bad_d = 0
bad_x = 0
errors = 0
for prime in CRT_PRIMES:
if a % prime == 0:
continue
fact, ifact = build_fact_tables(prime)
ae = pow(a, e, prime)
if ae == 0:
continue
ae_inv = pow(ae, -1, prime)
A = out1 % prime
C = out2 % prime * ae_inv % prime
Ap = [1] * (e + 1)
Cp = [1] * (e + 1)
for i in range(1, e + 1):
Ap[i] = Ap[i - 1] * A % prime
Cp[i] = Cp[i - 1] * C % prime
p = [0] * (e + 1)
for m in range(1, e + 1):
nm = e * m
fn = fact[nm]
s = 0
for k in range(m + 1):
term = fn * ifact[k * e] % prime
term = term * ifact[nm - k * e] % prime
term = term * Ap[k] % prime
term = term * Cp[m - k] % prime
s = s - term if (k & 1) else s + term
p[m] = (e * (s % prime)) % prime
inv = [0] + batch_invert(list(range(1, e + 1)), prime)
elem = [0] * (e + 1)
elem[0] = 1
for m in range(1, e + 1):
s = 0
sign = 1
for i in range(1, m + 1):
term = elem[m - i] * p[i] % prime
s = s + term if sign == 1 else s - term
sign = -sign
elem[m] = (s % prime) * inv[m] % prime
Q_desc = [1]
for i in range(1, e + 1):
coef = (-elem[i]) % prime if (i & 1) else elem[i]
Q_desc.append(coef)
ctx = flint.fmpz_mod_poly_ctx(prime)
D = ctx.gen()
ainv = pow(a, -1, prime)
binom_e = [0] * (e + 1)
fn_e = fact[e]
for i in range(e + 1):
binom_e[i] = fn_e * ifact[i] % prime * ifact[e - i] % prime
T = [0] * e
pow_ainv = 1
for i in range(e):
if i:
pow_ainv = pow_ainv * ainv % prime
T[i] = binom_e[i] * pow_ainv % prime
T[0] = (T[0] + binom_e[e] * ae_inv % prime * (leak % prime)) % prime
Q = ctx(list(reversed(Q_desc)))
Tpoly = ctx(T)
P_D = D**e - (leak % prime)
R = Q.compose_mod(Tpoly, P_D)
try:
Gd = P_D.gcd(R)
if Gd.degree() != 1:
bad_d += 1
continue
d_mod = (-int(Gd[0]) * pow(int(Gd[1]) % prime, -1, prime)) % prime
X = ctx.gen()
F = X**e - (out1 % prime)
G = (int(a % prime) * X + int((a + d_mod) % prime))**e - (out2 % prime)
Gx = F.gcd(G)
if Gx.degree() != 1:
bad_x += 1
continue
x1_mod = (-int(Gx[0]) * pow(int(Gx[1]) % prime, -1, prime)) % prime
except Exception:
errors += 1
continue
if used == 0:
d_acc = d_mod
x1_acc = x1_mod
mod_acc = prime
used = 1
else:
prev_mod = mod_acc
d_acc, mod_acc = crt_pair(d_acc, prev_mod, d_mod, prime)
x1_acc, _ = crt_pair(x1_acc, prev_mod, x1_mod, prime)
used += 1
if mod_acc > N:
break
if mod_acc <= N:
if verbose:
print(f"[info] crt primes used = {used}")
print(f"[info] bad_d={bad_d} bad_x={bad_x} errors={errors}")
print(f"[info] crt bits={mod_acc.bit_length()} target={N.bit_length()}")
raise ValueError("insufficient CRT modulus")
t1 = perf_counter()
b = d_acc + a
if b >= N:
b -= N
candidate_secret = None
for t in (0, 1):
num = x1_acc - d_acc + t * N
if num < 0 or num % a:
continue
x0 = num // a - 1
if not (0 <= x0 < (1 << 512)):
continue
xx1 = (a * x0 + b) % N
xx2 = (a * xx1 + b) % N
if pow(d_acc, e, N) != leak:
continue
if pow(xx1, e, N) != out1:
continue
if pow(xx2, e, N) != out2:
continue
candidate_secret = int(x0).to_bytes(64, "big")
break
if candidate_secret is None:
raise ValueError("failed to recover valid seed")
t2 = perf_counter()
if verbose:
print(f"[time] crt_core = {t1 - t0:.3f}s")
print(f"[time] recover = {t2 - t1:.3f}s")
print(f"[time] total = {t2 - t0:.3f}s")
print(f"[info] crt primes used = {used}")
print(f"[info] bad_d={bad_d} bad_x={bad_x} errors={errors}")
return candidate_secret
def main():
context.log_level = "error"
io = remote(HOST, PORT)
N, a, leak, out1, out2 = parse_instance(io)
secret = solve_instance(N, a, leak, out1, out2, verbose=DEBUG)
io.sendline(secret.hex().encode())
resp = io.recvrepeat(2.0)
print(resp.decode(errors="ignore"))
io.close()
if __name__ == "__main__":
main()
'''
Good! Here is your flag: XMCTF{90b84b4a-f738-44f2-8b4e-f40bcf150681}
'''Whisper Line
题目概览
题目同时给了一个 APK 和一份 PCAP。表面上看,工作被拆成两段:先从 Android 客户端里把聊天协议和加密逻辑还原出来,再从流量包里拿到密文并完成解密。真正的难点并不在于把算法认出来,而在于判断最后一步是否仍然是常规的 RSA 分解问题。如果把这一点判断错,整题会停在“已经知道是 textbook RSA,但模数做不出来”的阶段;而这题真正的突破口,恰恰是流量里给出的用户名把分解方向直接指到了 12 进制结构上
因此这题的利用链需要顺着三条线同时推进。APK 负责回答“消息到底是怎么加密和发送的”,PCAP 负责回答“哪些字节是真正要解的密文”,而分解部分则需要解释“为什么这个看起来是 2044 bit 的 RSA 模数,实际上并不是一个需要通用算法硬啃的随机数”。只有把这三段连起来,题目才会从可分析推进到可在比赛时限内做完
从 APK 先把协议层剥出来
先看 Java 层。Manifest 里只有一个 com.example.polarisctf.MainActivity,应用本身声明了 INTERNET 权限,并且是可调试构建。这一层没有太多干扰项,主逻辑基本都挂在 MainActivity 上,相关的方法名也比较直接:connect、recvLoop、strToHex、hexToStr,以及一个单独的 Z.x([B)Ljava/lang/String;。只看这些命名,已经足够先建立一个可靠的初步判断:聊天协议存在一层明文封包,真正的加密函数被单独塞进了 Z.x,而网络发送前后还会做一次十六进制编码与解码
对 classes3.dex 做字符串提取时,很快就能看到三个最关键的字面量:HELLO 、MSG 和 loadLibrary。这三处信息的价值很高。前两者说明网络协议根本不是二进制私有协议,而是基于文本行的轻量协议;最后一个则说明 Z 不是普通的 Java 工具类,而是 JNI 封装,真正的加密细节在 libu.so 里。到这里,协议层其实已经能还原出一个大致轮廓:客户端连接后先发 HELLO <name> ,正式消息则是 MSG <to> <cipher> ,然后把整行 ASCII 再转成十六进制后写进 socket
这个判断随后会被流量包完整印证。PCAP 里发往服务端 192.168.1.103:9001 的 TCP 负载并不是随机密文,而是纯 ASCII 十六进制字符串。把前两段载荷直接做 unhexlify,得到的就是:
HELLO Adic
HELLO December继续把后续载荷按 TCP 流重组,再整体做十六进制解码,就会看到完整的应用层协议行,例如:
MSG December 047a9099...
MSG Adic bde624ad...这一步非常关键。它把题目的对象从“分析一堆网络密文”变成了“分析文本协议中的第三个字段”。也就是说,流量里真正需要逆的并不是整段 TCP 负载,而只是 MSG 行后半部分那个长十六进制串。前两步如果没有做干净,后面即使把 native 算法完全逆出来,也会因为提错密文而卡住
JNI 层加密逻辑的还原
真正的核心在 lib/arm64-v8a/libu.so。虽然 so 被 strip 了,但导出符号还在,readelf -Ws 直接能看到 Java_com_example_polarisctf_Z_x。继续用 llvm-objdump 从这个函数入口往下看,逻辑并不复杂,关键片段非常集中。
第一处决定性证据是函数里有一段长度固定为 0x100 的循环,从常量地址取 256 个字节,每个字节都与 0xA7 异或后写入缓冲区。随后这个缓冲区被当作参数传给 BigInteger 构造函数。把这段常量手工抠出来并异或还原,得到的正是 RSA 模数:
n = 0ac4848f614d41d1f100ff73fef6d528c478dce950b20826eb32eed68bb82027...第二处证据是 JNI 调用了 BigInteger.valueOf(65537),指数没有伪装,就是常见的 e = 65537。第三处证据是随后依次出现了 compareTo、mod、modPow、bitLength 和 toByteArray 相关调用。结合调用顺序,Java/native 混合逻辑可以被准确复原为下面这个过程:先把输入明文按正整数解释成 BigInteger(1, plaintext);如果明文整数不小于 n,则先做一次取模;然后计算 m^e mod n;最后把结果转成字节串
so 里还有一个极容易忽略、但决定最后密文形态的细节。toByteArray 之后,函数会先去掉可能存在的前导零字节,再对得到的字节数组原地执行一次反转,最后才逐字节转成小写十六进制字符串返回。也就是说,这题的加密并不是“RSA 结果直接十六进制化”,而是“RSA 结果的无符号字节表示先倒序,再十六进制化”。这一点如果漏掉,后面即便已经求出私钥,解出来的内容也会完全不对
因此 Z.x 的行为可以写成下面的等价伪代码:
n = hidden_256_bytes ^ 0xA7
e = 65537
m = BigInteger(1, plaintext_bytes)
if m >= n:
m %= n
c = pow(m, e, n)
out = unsigned_bytes(c)
out = strip_leading_zero(out)
out = out[::-1]
return out.hex()到这里,加密逻辑已经闭环了。题目并不是自定义分组算法,也不是对称加密,而是没有 padding 的 textbook RSA,加上一层非常薄的输出字节反转
把 PCAP 中真正的会话内容解出来
有了上面的结论,解流量就只剩机械工作。先按 TCP 序列号重组流,再把每个 TCP 方向上的十六进制负载整体解码回文本行,取出所有 MSG <to> <cipherhex> 的第三个字段。解密时只需要把 cipherhex 先做一次字节反转,再送入私钥指数:
c = int.from_bytes(bytes.fromhex(cipherhex)[::-1], 'big')
m = pow(c, d, n)
pt = m.to_bytes((m.bit_length() + 7) // 8, 'big')真正解完之后,双方的对话内容很短,而且信息密度很高。Adic 发出的内容依次是:
you online?
quick update: security team is reviewing traffic
keep it brief. no attachments.
split it into 3 parts
part1 = xmctf{Th3_L0ud3st_Wh1sp3r_
part2 = 1s_1n_th3_PC4P_
part3 = ju5t_RSA_4nd_4_L1ttl3_R3v3rs3}
confirmed. wiping now.
switch to normal channel tomorrow.December 的回复则是:
yes
understood
ok. what about the incident code?
send part 1
got part1
got part2
ok. delete the thread after confirming.
done
ok因此 flag 并不是额外藏在别处,而是直接拆在了对话正文里,拼接后得到:
xmctf{Th3_L0ud3st_Wh1sp3r_1s_1n_th3_PC4P_ju5t_RSA_4nd_4_L1ttl3_R3v3rs3}这题真正的卡点不在逆向,而在分解为什么能做
如果到上一节为止,解题人只得到一个普通的 2044 bit RSA 模数,那么题目其实还没有进入可提交状态。因为 textbook RSA 只说明“消息没有 padding,可以直接做模幂”,并不等于“私钥可得”。对随机生成的 2044 bit 半素数而言,比赛时限内几乎没有通用分解空间。这里才是整题最致命的卡点:不是不会逆,也不是不会解流量,而是必须找到一个足够强的结构突破,让分解从通用困难问题退化成代数恢复
这道题给出的突破线索并不在 APK,而在流量里的人名。通信双方分别叫 Adic 和 December。把这两个词并排看,很容易联想到 12-adic。这不是一个用于直接攻击 RSA 的成熟现成结论,但它足以提示一个方向:把模数改写到 12 进制下观察它的形状。真正把 n 转成 12 进制后,结构会立刻变得非常不随机,所有位都只有 0~4,而且高位极其稀疏。这很像“在 12 进制下乘法几乎没发生进位”的题型,很像是在分解一个12 进制数字多项式,因此根据这个方向进行尝试
设 x = 12。把因子写成多项式形式,可以得到:
p = x^285 + a(x)
q = x^285 + x^280 + 2x^240 + 2x^200 + x^120 + 2x^40 + 1其中 a(x) 的次数只有 39,全部系数也都很小。这个形状之所以重要,是因为它直接解释了 n = p q 的高位为什么几乎没有混叠。展开后有:
n = x^570 + b(x) x^285 + a(x) x^285 + a(x)b(x)这里 b(x) = q - x^285,其最高次项是 x^280;而 a(x) 最高只有 39 次,所以 a(x) x^285 的贡献只落在区间 [285, 324],a(x)b(x) 的贡献最高也只到 319 次。于是,n 在 12 进制下 325 位以上的那些孤立高位,全部只能来自 b(x) x^285。换句话说,q 的稀疏高位项可以直接从 n 的高位读出来,不需要做任何重型分解
这一步就是本题从“理论上能继续想”变成“比赛里能做完”的分界线。只要把这些孤立位置提出来,就能先恢复出
q = x^285 + x^280 + 2x^240 + 2x^200 + x^120 + 2x^40 + 1再用 n // q 求得 p,整个过程退化成一次基数变换加一次整数除法,而不再是对 2044 bit 模数跑通用分解算法。题目里真正控制复杂度的,不是 RSA 本身,而是能否意识到用户名给出的 12 进制提示,并据此把一个原本不可行的问题改写成稀疏多项式恢复问题
从结果看,恢复出来的两个因子正是:
p = 3480a03cf088f0bc5cc0f2f1c329a3086cb6bf0d766148263ef13814300da1979dbe09c8589ec6599942867d9504e4e19d5244a2cc960e664c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f71e09dd166bb3b1c5cef3d386340dd60cd
q = 3480ae10db8714b21333e02e0fca3b91cf7cea6f457dc7c29cd538563400d628c90ad5cef39f4d49d617a22dc95e2db4bc360954b924c44e188a1e64c5df03971b2d22d15c44b7f5fe3d9f3b0af899bf15c789b11e42db8e5bb060f0fcebb0ee4461000000000000000000000001517168a4523fd04200000000000000000001随后计算 phi = (p - 1)(q - 1) 与 d = e^{-1} mod phi,整个解密链条才真正闭合
结论
这题前半段的逆向并不重,真正有信息密度的是把各层证据接到一起:Java 层告诉我们协议是 HELLO/MSG 文本行,socket 负载整体再包一层十六进制;native 层告诉我们核心算法是 BigInteger 上实现的 textbook RSA,并且密文字节在输出前被反转;PCAP 则给出真实的会话密文与用户名线索。最后的决定性突破来自对用户名 Adic 与 December 的联想,把分解思路导向 12 进制表示,从而绕开了通用 RSA 分解的复杂度瓶颈
题目的难点并不平均分布。提协议、逆 JNI、还原 RSA,这些步骤只是把题目推进到“知道该做什么”;而把 n 放进 12 进制、识别其稀疏结构并恢复因子,才是把题目推进到“能在比赛时限内做完”的真正分界线。flag 最终为:
xmctf{Th3_L0ud3st_Wh1sp3r_1s_1n_th3_PC4P_ju5t_RSA_4nd_4_L1ttl3_R3v3rs3}ez_random
这题真正要解出的是最后那次 getrandbits(256)
option 2 走完 36 轮输入以后,服务端会继续取一次 getrandbits(256),把它转成字符串做 SHA256,再拿这个摘要去做 AES-ECB。题目的关键从头到尾都不在 AES,本质上还是随机流恢复。服务端代码里这条链写得很直白,option 1 和 option 2 每次都会重新用同一个 SEED 播种,option 1 生成 36 组 (getrandbits(988), random_prime(...)),option 2 则重新跑同一条随机链,最后再做一次 getrandbits(256) 来派生密钥
先能抓住的是一个很硬的 oracle。option 2 每一轮都会算
random_prime(int(input()) ^ (getrandbits(988) ^ get_limit(k)))这行最关键的地方不在异或本身,而在 random_prime 的入参。如果我们喂进去的值刚好让括号整体变成 1,那么 random_prime(1) 会直接抛出 ValueError。get_limit(k) 又是已知的,所以对第 k 轮的某个候选 cand,只要发
cand ^ get_limit(k) ^ 1如果它正好就是当前真实的 getrandbits(988),服务端就会在这一轮直接异常;如果不对,服务会继续往后要下一个数字。题目给出的 Key Part A 虽然被打乱了顺序,但靠这个异常信号可以一位一位排回去。先拿 option 1 把 Key Part A 抓下来,再在 option 2 里逐位测试候选,收到 ValueError、n must be greater 或 traceback 就把这个候选认成当前正确位置
这个地方真正麻烦的是吞吐。交互本身很慢,连接开高以后容易超时,所以这里需要采取一些稳妥的做法,我这里是每个候选单独起连接,保守并发,失败就重试,某个位置找出来以后再做一次确认。with_retries 统一兜网络问题,test_candidate 负责单候选测试,定位到候选以后再做一次 confirm,顺便把进度落到 json 里做 checkpoint
如果只停在这里,很容易顺着位数去想。36 个 getrandbits(988),泄露位数已经远远超过 MT19937 的 19968 bit,看起来像是把顺序排回去以后就能直接恢复状态。这个方向在这题里走不通,卡点不在位数,而在随机流不连续
题目把 sage.arith.misc.random_prime 打过补丁以后,返回值从单个素数变成了 (p, count),也就是最后找到的素数和尝试次数。更关键的是,这个函数内部还是通过 Zmod(n).random_element() 来取候选,而它最终会继续走 Sage 当前的随机状态。换句话说,getrandbits(988) 和 random_prime() 中间试出来的那些候选数,用的是同一条随机流,不是两套互不相关的源。服务端在 option 1 里输出的 Key Part B0 和 Key Part B1,正好就对应这两部分信息,前者是最终成功的素数,后者是这一轮一共试了多少次
所以这题不能把随机链看成 36 次 getrandbits(988) 后面直接跟一次 getrandbits(256)。真实情况是每个 988-bit 输出之间都夹着一段 random_prime() 试错时消耗掉的随机数。只拿 Key Part A 去恢复 MT,会把中间这些消耗全部当成不存在,位置自然就错了。在线部分负责排顺序、拿密文和做交互,真正的状态恢复是靠离线部分来做,而且离线部分明确把 ordered、B0、B1 一起送进约束里
Key Part B0 和 Key Part B1 的作用也展现于此。B1[i] 显示了第 i 次 random_prime(get_limit(i)) 一共额外消耗了多少轮候选;B0[i] 则给最后一次成功候选留下了观测值。每个 988-bit 输出可以拆成 31 个块,前 30 个块是完整 32 bit,最后一个块只有高 28 bit。离线恢复时把它们分别记成 full32 和 top28。对每个 B0[i],脚本又额外加一个 top31 观测。这样一来,Key Part A 提供的是大块输出,B0/B1 补的是中间穿插进去的那段随机流,两边拼起来,整个输出序列才真正闭合
还有一个关键点需要注意,第 10 轮的上界不一样。服务端的 get_limit 在 i == 10 时会把上界砍掉三分之一。这个细节会改变 randbelow() 的 rejection 行为,也就意味着只看表面上的 B1[10] 还不够,还得把额外多吃掉的候选数一起枚举进去。离线脚本里就是专门给这个量留了 extra10,然后从 0 到 7 去试,最终满足约束的是 extra10 = 1
约束真正落地的时候,做法很直接。把排好序的 36 个 988-bit 输出拆成 full32 和 top28,再把每轮的 B0[i] 放到对应的位置上做 top31。之后用 MT19937 的 temper 和 twist 关系把这些位置全部连起来。只要某个 extra10 可满足,就能恢复出对应位置上的完整 624 个状态字,然后直接把这组状态塞回 Python 自带的 random.Random().setstate(...),接着取下一次 getrandbits(256)
拿到这个 256 位值以后就大功告成了。option 2 走完以后服务端用 SHA256(str(getrandbits(256)).encode()) 派生 key,再用 ECB 加密 flag。把恢复出来的 next256 按题干的方式过一遍 sha256,再让在线脚本用排好序的 36 个数去拿一次最终密文,解开即可
最后跑出来的值是
next256 = 10008324236482032701298949755825802170892553192271055426143845860770670696738解出来的 flag 是
XMCTF{23251116-0b55-42e8-9d93-750d1ca62c08}这题最容易把人带偏的地方不是那个异常 oracle,而是看见 36 个 988-bit 输出以后,会下意识觉得信息量已经足够,后面只剩一个普通的 MT 恢复。真正卡人的地方在 random_prime() 这层消耗和 B0/B1 的作用。前者让随机流断开了,后者又把这段断口补了回来。把这件事想通以后,整题就不再是单纯的交互题,而是一道先靠 oracle 排顺序,再把整条 MT 输出流补完整的恢复题
exp
#!/usr/bin/env python3
import argparse
import ast
import concurrent.futures
import json
import re
import socket
import time
from dataclasses import dataclass
from hashlib import sha256
from pathlib import Path
from typing import List, Optional, Tuple
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from z3 import BitVec, BitVecVal, If, LShR, Solver, sat
N_BITS = 988
N_PAIRS = 37
N = 2**31 - 1
MT_N = 624
MT_M = 397
MATRIX_A = 0x9908B0DF
UPPER_MASK = 0x80000000
LOWER_MASK = 0x7FFFFFFF
def get_limit(i: int) -> int:
return N - (N // 3) * (1 if i == 10 else 0)
class NetworkRetry(Exception):
pass
class Remote:
def __init__(self, host: str, port: int, timeout: float = 5.0):
self.sock = socket.create_connection((host, port), timeout=timeout)
self.sock.settimeout(timeout)
self.buf = b""
def close(self) -> None:
try:
self.sock.close()
except Exception:
pass
def recv_until(self, token: bytes) -> bytes:
while token not in self.buf:
chunk = self.sock.recv(4096)
if not chunk:
raise EOFError(self.buf.decode(errors="ignore"))
self.buf += chunk
idx = self.buf.index(token) + len(token)
out = self.buf[:idx]
self.buf = self.buf[idx:]
return out
def recv_nonblock(self, timeout: float = 0.2) -> bytes:
old = self.sock.gettimeout()
self.sock.settimeout(timeout)
try:
chunk = self.sock.recv(4096)
if not chunk:
raise EOFError(self.buf.decode(errors="ignore"))
self.buf += chunk
out = self.buf
self.buf = b""
return out
finally:
self.sock.settimeout(old)
def sendline(self, s: str) -> None:
self.sock.sendall(s.encode() + b"\n")
@dataclass
class OracleResult:
correct: bool
detail: str
hard_signal: bool
@dataclass
class FullState:
host: str
port: int
shuffled: List[int]
ordered: List[int]
b0: List[int]
b1: List[int]
timestamp: float
def dump(self, path: Path) -> None:
path.write_text(
json.dumps(
{
"host": self.host,
"port": self.port,
"shuffled": self.shuffled,
"ordered": self.ordered,
"b0": self.b0,
"b1": self.b1,
"timestamp": self.timestamp,
},
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)
@staticmethod
def load(path: Path) -> "FullState":
data = json.loads(path.read_text(encoding="utf-8"))
return FullState(
host=data["host"],
port=int(data["port"]),
shuffled=[int(x) for x in data["shuffled"]],
ordered=[int(x) for x in data.get("ordered", [])],
b0=[int(x) for x in data["b0"]],
b1=[int(x) for x in data["b1"]],
timestamp=float(data.get("timestamp", time.time())),
)
def with_retries(fn, retries: int, delay: float, what: str):
last = None
for attempt in range(1, retries + 1):
try:
return fn()
except (socket.timeout, TimeoutError, ConnectionError, ConnectionResetError, OSError, EOFError, NetworkRetry) as e:
last = e
print(f"[!] {what} failed on attempt {attempt}/{retries}: {e}")
if attempt < retries:
time.sleep(delay * attempt)
raise last
def parse_list(label: str, text: str) -> List[int]:
m = re.search(rf"{re.escape(label)}: (\[.*?\])", text, re.S)
if not m:
raise ValueError(f"failed to parse {label}")
raw = re.sub(r"\s+", "", m.group(1))
return [int(x) for x in ast.literal_eval(raw)]
def fetch_parts(host: str, port: int, timeout: float, retries: int, retry_delay: float) -> Tuple[List[int], List[int], List[int], str]:
def _do():
r = Remote(host, port, timeout)
try:
r.recv_until(b"option > ")
r.sendline("1")
data = r.recv_until(b"Key Part B1: ")
data += r.recv_until(b"\n")
text = data.decode(errors="ignore")
part_a = parse_list("Key Part A", text)
b0 = parse_list("Key Part B0", text)
b1 = parse_list("Key Part B1", text)
if len(part_a) != N_PAIRS - 1:
raise ValueError(f"unexpected Key Part A length: {len(part_a)}")
if len(b0) != N_PAIRS - 1 or len(b1) != N_PAIRS - 1:
raise ValueError("unexpected B0/B1 length")
return part_a, b0, b1, text
finally:
r.close()
return with_retries(_do, retries, retry_delay, "fetch_parts")
def remaining_from_state(shuffled: List[int], ordered: List[int]) -> List[int]:
rem = shuffled[:]
for v in ordered:
rem.remove(v)
return rem
def test_candidate_once(host: str, port: int, timeout: float, oracle_timeout: float, known_prefix: List[int], k: int, cand: int) -> OracleResult:
r = Remote(host, port, timeout)
try:
r.recv_until(b"option > ")
r.sendline("2")
for idx, val in enumerate(known_prefix, start=1):
r.recv_until(f"{idx}th number: ".encode())
r.sendline(str(val))
r.recv_until(f"{k}th number: ".encode())
r.sendline(str(cand ^ get_limit(k) ^ 1))
next_prompt = f"{k + 1}th number: ".encode() if k < (N_PAIRS - 1) else b"Let's get the flag"
deadline = time.time() + oracle_timeout
buf = b""
while time.time() < deadline:
try:
chunk = r.recv_nonblock(timeout=0.2)
buf += chunk
low = buf.lower()
if next_prompt in buf or b"flag:" in low:
return OracleResult(False, buf.decode(errors="ignore"), False)
if b"valueerror" in low or b"n must be greater" in low or b"traceback" in low:
return OracleResult(True, buf.decode(errors="ignore"), True)
except socket.timeout:
continue
except EOFError as e:
msg = buf.decode(errors="ignore") + str(e)
return OracleResult(False, msg, False)
return OracleResult(False, buf.decode(errors="ignore"), False)
finally:
r.close()
def test_candidate(host: str, port: int, timeout: float, oracle_timeout: float, known_prefix: List[int], k: int, cand: int, retries: int, retry_delay: float) -> OracleResult:
return with_retries(
lambda: test_candidate_once(host, port, timeout, oracle_timeout, known_prefix, k, cand),
retries,
retry_delay,
f"test_candidate(k={k})",
)
def solve_position_parallel(host: str, port: int, timeout: float, oracle_timeout: float, retries: int, retry_delay: float,
ordered: List[int], k: int, remaining: List[int], workers: int) -> int:
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as ex:
fut_to_idx = {
ex.submit(test_candidate, host, port, timeout, oracle_timeout, ordered, k, cand, retries, retry_delay): idx
for idx, cand in enumerate(remaining)
}
for fut in concurrent.futures.as_completed(fut_to_idx):
idx = fut_to_idx[fut]
try:
res = fut.result()
except Exception:
continue
if res.correct:
return idx
raise RuntimeError(f"failed to determine value at position {k}")
def ordered_values_to_outputs(vals: List[int]) -> Tuple[List[int], List[Optional[int]]]:
outs: List[int] = []
partial: List[Optional[int]] = []
for v in vals:
for i in range(30):
outs.append((v >> (32 * i)) & 0xFFFFFFFF)
partial.append(None)
outs.append((v >> 960) & ((1 << 28) - 1))
partial.append(28)
return outs, partial
def temper_z3(y):
y = y ^ LShR(y, 11)
y = y ^ ((y << 7) & BitVecVal(0x9D2C5680, 32))
y = y ^ ((y << 15) & BitVecVal(0xEFC60000, 32))
y = y ^ LShR(y, 18)
return y
def twist_inplace_z3(state):
mt = state[:]
for kk in range(MT_N - MT_M):
y = (mt[kk] & BitVecVal(UPPER_MASK, 32)) | (mt[kk + 1] & BitVecVal(LOWER_MASK, 32))
mt[kk] = mt[kk + MT_M] ^ LShR(y, 1) ^ If((y & BitVecVal(1, 32)) == BitVecVal(1, 32), BitVecVal(MATRIX_A, 32), BitVecVal(0, 32))
for kk in range(MT_N - MT_M, MT_N - 1):
y = (mt[kk] & BitVecVal(UPPER_MASK, 32)) | (mt[kk + 1] & BitVecVal(LOWER_MASK, 32))
mt[kk] = mt[kk + (MT_M - MT_N)] ^ LShR(y, 1) ^ If((y & BitVecVal(1, 32)) == BitVecVal(1, 32), BitVecVal(MATRIX_A, 32), BitVecVal(0, 32))
y = (mt[MT_N - 1] & BitVecVal(UPPER_MASK, 32)) | (mt[0] & BitVecVal(LOWER_MASK, 32))
mt[MT_N - 1] = mt[MT_M - 1] ^ LShR(y, 1) ^ If((y & BitVecVal(1, 32)) == BitVecVal(1, 32), BitVecVal(MATRIX_A, 32), BitVecVal(0, 32))
return mt
def twist_inplace_py(state: List[int]) -> List[int]:
mt = state[:]
for kk in range(MT_N - MT_M):
y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK)
mt[kk] = (mt[kk + MT_M] ^ (y >> 1) ^ (MATRIX_A if (y & 1) else 0)) & 0xFFFFFFFF
for kk in range(MT_N - MT_M, MT_N - 1):
y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK)
mt[kk] = (mt[kk + (MT_M - MT_N)] ^ (y >> 1) ^ (MATRIX_A if (y & 1) else 0)) & 0xFFFFFFFF
y = (mt[MT_N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK)
mt[MT_N - 1] = (mt[MT_M - 1] ^ (y >> 1) ^ (MATRIX_A if (y & 1) else 0)) & 0xFFFFFFFF
return mt
def output_expr(blocks, idx):
arr = blocks[idx // MT_N]
return temper_z3(arr[idx % MT_N])
def build_observations(ordered: List[int], b0: List[int], b1: List[int], extra10: int):
obs = []
pos = 0
for i, v in enumerate(ordered, start=1):
for j in range(30):
obs.append((pos, "full32", (v >> (32 * j)) & 0xFFFFFFFF))
pos += 1
obs.append((pos, "top28", (v >> 960) & ((1 << 28) - 1)))
pos += 1
gap = b1[i - 1]
if i == 10:
gap += extra10
obs.append((pos + gap - 1, "top31", b0[i - 1]))
pos += gap
return obs, pos
def recover_next_256(ordered: List[int], b0: List[int], b1: List[int]) -> Tuple[int, int, int]:
for extra10 in range(0, 8):
obs, total = build_observations(ordered, b0, b1, extra10)
nblocks = total // MT_N + 2
blocks = [[BitVec(f"s_{b}_{i}", 32) for i in range(MT_N)] for b in range(nblocks)]
for b in range(1, nblocks):
tw = twist_inplace_z3(blocks[b - 1])
for i in range(MT_N):
blocks[b][i] = tw[i]
s = Solver()
for pos, kind, val in obs:
t = output_expr(blocks, pos)
if kind == "full32":
s.add(t == BitVecVal(val, 32))
elif kind == "top28":
s.add(LShR(t, 4) == BitVecVal(val, 32))
elif kind == "top31":
s.add(LShR(t, 1) == BitVecVal(val, 32))
else:
raise RuntimeError(kind)
if s.check() != sat:
continue
m = s.model()
concrete = []
for block in blocks:
concrete.append([m.eval(x).as_long() & 0xFFFFFFFF for x in block])
block_idx = total // MT_N
inner_idx = total % MT_N
import random
rr = random.Random()
rr.setstate((3, tuple(concrete[block_idx] + [inner_idx]), None))
nxt = rr.getrandbits(256)
return nxt, extra10, total
raise RuntimeError("failed to recover MT19937 state with B0/B1 constraints")
def fetch_ciphertext_once(host: str, port: int, timeout: float, ordered_vals: List[int]) -> bytes:
r = Remote(host, port, timeout)
try:
r.recv_until(b"option > ")
r.sendline("2")
for idx, val in enumerate(ordered_vals, start=1):
r.recv_until(f"{idx}th number: ".encode())
r.sendline(str(val))
data = r.recv_until(b"Flag: ")
data += r.recv_until(b"\n")
s = data.decode(errors="ignore")
m = re.search(r"Flag:\s*(b[\"'].*[\"'])", s)
if not m:
raise ValueError(f"failed to parse ciphertext from:\n{s}")
return ast.literal_eval(m.group(1))
finally:
r.close()
def fetch_ciphertext(host: str, port: int, timeout: float, ordered_vals: List[int], retries: int, retry_delay: float) -> bytes:
return with_retries(
lambda: fetch_ciphertext_once(host, port, timeout, ordered_vals),
retries,
retry_delay,
"fetch_ciphertext",
)
def solve_online(host: str, port: int, timeout: float, oracle_timeout: float, retries: int, retry_delay: float,
state_path: Path, raw_path: Path, fresh: bool, workers: int) -> FullState:
if state_path.exists() and not fresh:
st = FullState.load(state_path)
print(f"[+] resumed from {state_path} with {len(st.ordered)} solved positions")
else:
shuffled, b0, b1, raw_text = fetch_parts(host, port, timeout, retries, retry_delay)
raw_path.write_text(raw_text, encoding="utf-8")
st = FullState(host=host, port=port, shuffled=shuffled, ordered=[], b0=b0, b1=b1, timestamp=time.time())
st.dump(state_path)
print(f"[+] fetched option 1 data")
remaining = remaining_from_state(st.shuffled, st.ordered)
for k in range(len(st.ordered) + 1, N_PAIRS):
print(f"[+] resolving position {k}/{N_PAIRS - 1} from {len(remaining)} candidates")
found_idx = solve_position_parallel(host, port, timeout, oracle_timeout, retries, retry_delay, st.ordered, k, remaining, workers)
candidate = remaining[found_idx]
confirm = test_candidate(host, port, timeout, oracle_timeout, st.ordered, k, candidate, retries, retry_delay)
if not confirm.correct:
raise RuntimeError(f"candidate for position {k} failed confirmation")
st.ordered.append(candidate)
st.timestamp = time.time()
st.dump(state_path)
print(f" [*] found position {k}")
remaining.pop(found_idx)
return st
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--host", required=True)
ap.add_argument("--port", type=int, required=True)
ap.add_argument("--timeout", type=float, default=8.0)
ap.add_argument("--oracle-timeout", type=float, default=1.2)
ap.add_argument("--retries", type=int, default=3)
ap.add_argument("--retry-delay", type=float, default=1.0)
ap.add_argument("--workers", type=int, default=2)
ap.add_argument("--state-file", default="ez_random_state.json")
ap.add_argument("--raw-file", default="ez_random_fetch.log")
ap.add_argument("--next-file", default="ez_random_next256.txt")
ap.add_argument("--result-file", default="ez_random_result.json")
ap.add_argument("--fresh", action="store_true")
args = ap.parse_args()
state_path = Path(args.state_file)
raw_path = Path(args.raw_file)
next_path = Path(args.next_file)
result_path = Path(args.result_file)
st = solve_online(
args.host,
args.port,
args.timeout,
args.oracle_timeout,
args.retries,
args.retry_delay,
state_path,
raw_path,
args.fresh,
args.workers,
)
print("[+] recovering MT19937 with B0/B1 constraints")
next256, extra10, total_outputs = recover_next_256(st.ordered, st.b0, st.b1)
next_path.write_text(str(next256), encoding="utf-8")
print(f"[+] extra10 = {extra10}")
print(f"[+] total_outputs = {total_outputs}")
print(f"[+] next256 = {next256}")
print("[+] fetching ciphertext")
ct = fetch_ciphertext(args.host, args.port, args.timeout, st.ordered, args.retries, args.retry_delay)
key = sha256(str(next256).encode()).digest()
pt = unpad(AES.new(key, AES.MODE_ECB).decrypt(ct), AES.block_size)
result = {
"host": args.host,
"port": args.port,
"ordered": st.ordered,
"b0": st.b0,
"b1": st.b1,
"extra10": extra10,
"total_outputs": total_outputs,
"next256": str(next256),
"ciphertext_hex": ct.hex(),
"plaintext_hex": pt.hex(),
"plaintext": pt.decode(errors="replace"),
}
result_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"[+] ciphertext = {ct!r}")
try:
print(f"[+] flag = {pt.decode()}")
except Exception:
print(f"[+] plaintext = {pt!r}")
if __name__ == "__main__":
main()运行方式(复现版)
python3 ez_random_full_exp.py --host nc1.ctfplus.cn --port 30217 --workers 2 --retries 3 --retry -delay 1.0 --timeout 8.0 --oracle-timeout 1.2示例回显(复现版)
$ python3 ez_random_full_exp.py --host nc1.ctfplus.cn --port 30217 --workers 2 --retries 3 --retry
-delay 1.0 --timeout 8.0 --oracle-timeout 1.2
[!] fetch_parts failed on attempt 1/3: timed out
[+] fetched option 1 data
[+] resolving position 1/36 from 36 candidates
[*] found position 1
[+] resolving position 2/36 from 35 candidates
[*] found position 2
[+] resolving position 3/36 from 34 candidates
[*] found position 3
[+] resolving position 4/36 from 33 candidates
[*] found position 4
[+] resolving position 5/36 from 32 candidates
[*] found position 5
[+] resolving position 6/36 from 31 candidates
[*] found position 6
[+] resolving position 7/36 from 30 candidates
[*] found position 7
[+] resolving position 8/36 from 29 candidates
[*] found position 8
[+] resolving position 9/36 from 28 candidates
[*] found position 9
[+] resolving position 10/36 from 27 candidates
[*] found position 10
[+] resolving position 11/36 from 26 candidates
[*] found position 11
[+] resolving position 12/36 from 25 candidates
[*] found position 12
[+] resolving position 13/36 from 24 candidates
[*] found position 13
[+] resolving position 14/36 from 23 candidates
[*] found position 14
[+] resolving position 15/36 from 22 candidates
[*] found position 15
[+] resolving position 16/36 from 21 candidates
[*] found position 16
[+] resolving position 17/36 from 20 candidates
[*] found position 17
[+] resolving position 18/36 from 19 candidates
[*] found position 18
[+] resolving position 19/36 from 18 candidates
[*] found position 19
[+] resolving position 20/36 from 17 candidates
[*] found position 20
[+] resolving position 21/36 from 16 candidates
[*] found position 21
[+] resolving position 22/36 from 15 candidates
[*] found position 22
[+] resolving position 23/36 from 14 candidates
[*] found position 23
[+] resolving position 24/36 from 13 candidates
[*] found position 24
[+] resolving position 25/36 from 12 candidates
[*] found position 25
[+] resolving position 26/36 from 11 candidates
[*] found position 26
[+] resolving position 27/36 from 10 candidates
[*] found position 27
[+] resolving position 28/36 from 9 candidates
[*] found position 28
[+] resolving position 29/36 from 8 candidates
[*] found position 29
[+] resolving position 30/36 from 7 candidates
[*] found position 30
[+] resolving position 31/36 from 6 candidates
[*] found position 31
[+] resolving position 32/36 from 5 candidates
[*] found position 32
[+] resolving position 33/36 from 4 candidates
[*] found position 33
[+] resolving position 34/36 from 3 candidates
[*] found position 34
[+] resolving position 35/36 from 2 candidates
[*] found position 35
[+] resolving position 36/36 from 1 candidates
[*] found position 36
[+] recovering MT19937 with B0/B1 constraints
[+] extra10 = 1
[+] total_outputs = 1956
[+] next256 = 10008324236482032701298949755825802170892553192271055426143845860770670696738
[+] fetching ciphertext
[+] ciphertext = b'\xb8\xa4\xa6Iw`\xd5^\x807\xee\n4<\xc4J\x856\xaa\xf8\x03\xf3R\xd6\xc5\x86\xfc\xa5\n\x84,u\xfa}\xaf\xecF\xb5\x9b\x92\xdcq\xea\xd5\x90b\xca\xca'
[+] flag = XMCTF{844539b0-ce00-41eb-a2f8-4832512009e9}ocean
从源码当中可以读取到以下信息:
seed、mask1、mask2都是 64 位,且seed = getRandomNBitInteger(64),因此seed最高位恒为 1,这一点可以在后续作为正确 seed 的筛选条件之一,因为这种筛选速度显著快于 AES 验证lfsr1是一个普通 LFSR,而lfsr2不是每轮都更新,只有在lfsr1()返回 1 时才更新- 最终输出的是 64 位
output,另外给了enc = AES_ECB(md5(str(seed)), secret)
接下来展开解题思路的探讨:
最直观的想法是把两个寄存器 64 轮完整展开,作为 64 个约束方程,交给 Z3 或 SAT 求解器来解。这个方向理论上能做,但工程上不可行,因为条件更新会引入大量 if/ite,直接展开状态树会非常重,不可能在限定的 60s 内完成
而最后真正有效的切入点在于 lfsr1 的每一轮输出 c_t 都是 seed 的 GF(2) 线性函数。如果把 lfsr2 单独看成一个普通 LFSR,那么“更新了 j 次之后最后一位的值”也同样是 seed 的 GF(2) 线性函数,于是,题目可以改写成: c_t = A_t(seed) z_j = B_j(seed) ,其中 z_j 表示 lfsr2 被更新 j 次后的输出位。因此,第 t 轮真实输出满足 output[t] = z_{sum(c_0...c_t)}
也就是说,非线性只剩下了“前缀和选择哪一个 z_j”
完整思路:
最终我采用的是思路是把问题写成 GF(2) 线性关系+前缀和 one-hot 计数器,再用 pycryptosat 增量求解
第一步:预计算线性行
对 mask1 预计算 64 个 c_t 对应的线性表达式,对 mask2 预计算 65 个 z_j 对应的线性表达式(z_0 到 z_64)
第二步:约束 seed
用 64 个 SAT 变量表示 seed ,然后再加上前面说过的 seed 最高位为 1 的约束
第三步:约束 c_t 和 z_j
每个 c_t 或 z_j 都用一个 XOR 约束表示成 seed 的线性函数
第五步:用 one-hot 计数器表示“更新了几次”
令 cnt[t][j] 表示“第 t 轮结束后,lfsr2 一共更新了 j 次”。
然后把 output[t] = z_j 写成如果 cnt[t][j] = 1,那么 z_j 必须等于 output[t]
关键优化1:翻转约束
由题目代码可知:
if self.lfsr():
self.update()
return self.state[-1]这意味着:
如果某一轮输出位发生了翻转,那么这一轮
lfsr2一定发生了更新也就是如果
output[t] != output[t-1],则必有c_t = 1
这条约束对随机输出,通常能直接固定一大批控制位
关键优化2:求解器选择(增量求解)
最终选择 pycryptosat 而不是命令行 CMS
因为本题当中最后解出的 seed 不一定是能够解出 fakeflag 的正确 seed,即本题的 seed 存在满足约束条件的多解。所以最后必须枚举多个 candidate,而不是只取一个模型
命令行 cryptominisat5 每拿一个 candidate 都要重新读文件、重新预处理、重新求解,开销太大。而 pycryptosat 可以通过一次建模后通过 solve() 拿一个候选,再 AES 检查失败后,还可以再加一个 blocking clause 继续进行 solve() 求下一个解
最终的运行策略
即使单实例能解,也未必稳定压进 60 秒。因为不同实例解出正确 seed 所经过的 candidate 数差异很大
所以最终实战脚本还做了两层策略,第一是只枚举前若干个 candidate ,本题中只枚举了前 120 个,这也是结合设备性能考虑的,我的轻薄本通常在枚举完 120 个之前运行时间就超过题目的 60s 阈值了。第二是多次重连,只选择好解的实例,通过 output 的相邻翻转次数来抉择,翻转多的约束更强,通常更有机会解出。这里设置的阈值是 min_flips = 26 ,通常几百次就能刷出来符合条件的,而对于不符合条件,翻转数太低的实例直接跳过即可
exp
#!/usr/bin/env python3
import argparse
import hashlib
import re
import socket
import sys
import time
from typing import List, Optional, Tuple
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from pycryptosat import Solver
N = 64
SECRET_RE = re.compile(r"^fakeflag\{[0-9a-f]{32}\}$")
def bits_of_int(x: int, n: int = N) -> List[int]:
return [int(b) for b in f"{x:0{n}b}"]
def output_flip_count(output_val: int, n: int = N) -> int:
bits = bits_of_int(output_val, n)
return sum(bits[i] != bits[i - 1] for i in range(1, n))
class VarPool:
def __init__(self):
self.cnt = 0
def new(self) -> int:
self.cnt += 1
return self.cnt
class Builder:
def __init__(self, solver: Solver):
self.solver = solver
self.vp = VarPool()
self.clauses = 0
self.xors = 0
def new_var(self) -> int:
return self.vp.new()
def add_clause(self, lits: List[int]) -> None:
self.solver.add_clause(lits)
self.clauses += 1
def add_xor(self, lits: List[int], rhs: bool) -> None:
self.solver.add_xor_clause(lits, rhs)
self.xors += 1
def eq_const(self, v: int, bit: int) -> None:
self.add_clause([v] if bit else [-v])
def eq_var(self, a: int, b: int) -> None:
self.add_clause([-a, b])
self.add_clause([a, -b])
def ite_eq(self, x: int, c: int, a: int, b: int) -> None:
self.add_clause([-c, -a, x])
self.add_clause([-c, a, -x])
self.add_clause([c, -b, x])
self.add_clause([c, b, -x])
def and_eq(self, x: int, a: int, b: int) -> None:
self.add_clause([-x, a])
self.add_clause([-x, b])
self.add_clause([x, -a, -b])
def add_linear_eq(builder: Builder, row_mask: int, seed_vars: List[int], out_var: int) -> None:
vars_ = []
for i in range(N):
if (row_mask >> (N - 1 - i)) & 1:
vars_.append(seed_vars[i])
if not vars_:
builder.eq_const(out_var, 0)
else:
builder.add_xor(vars_ + [out_var], False)
def precompute_rows(mask: int, n: int = N) -> Tuple[List[int], List[int]]:
mask_bits = bits_of_int(mask, n)
state = [1 << (n - 1 - i) for i in range(n)]
# c_t = output of LFSR1 after t-th update
c_rows = []
st = state[:]
for _ in range(n):
fb = 0
for i, b in enumerate(mask_bits):
if b:
fb ^= st[i]
st = st[1:] + [fb]
c_rows.append(st[-1])
# z_j = output bit of a normal LFSR2 after exactly j updates, z_0 = initial last bit
z_rows = [state[-1]]
st = state[:]
for _ in range(n):
fb = 0
for i, b in enumerate(mask_bits):
if b:
fb ^= st[i]
st = st[1:] + [fb]
z_rows.append(st[-1])
return c_rows, z_rows
def build_formula(mask1: int, mask2: int, output_val: int, solver: Solver):
out_bits = bits_of_int(output_val, N)
c_rows, _ = precompute_rows(mask1)
_, z_rows = precompute_rows(mask2)
b = Builder(solver)
# 64-bit seed, MSB must be 1 because getRandomNBitInteger(64)
seed_vars = [b.new_var() for _ in range(N)]
b.eq_const(seed_vars[0], 1)
# c_t variables
c_vars = [b.new_var() for _ in range(N)]
for t in range(N):
add_linear_eq(b, c_rows[t], seed_vars, c_vars[t])
# if output flips at round t, LFSR2 must have clocked at round t => c_t = 1
forced_controls = 0
for t in range(1, N):
if out_bits[t] != out_bits[t - 1]:
b.eq_const(c_vars[t], 1)
forced_controls += 1
# z_j variables
z_vars = [b.new_var() for _ in range(N + 1)]
for j in range(N + 1):
add_linear_eq(b, z_rows[j], seed_vars, z_vars[j])
# cnt[t][j] = after round t, LFSR2 has updated exactly j times
cnt: List[List[int]] = []
row0 = [b.new_var() for _ in range(2)]
cnt.append(row0)
b.eq_var(row0[1], c_vars[0])
b.add_clause([-row0[0], -c_vars[0]])
b.add_clause([row0[0], c_vars[0]])
for t in range(1, N):
prev = cnt[t - 1]
cur = [b.new_var() for _ in range(t + 2)]
cnt.append(cur)
# cur[0] = prev[0] & ~c_t
b.add_clause([-cur[0], prev[0]])
b.add_clause([-cur[0], -c_vars[t]])
b.add_clause([cur[0], -prev[0], c_vars[t]])
for j in range(1, t + 1):
# cur[j] = c_t ? prev[j-1] : prev[j]
b.ite_eq(cur[j], c_vars[t], prev[j - 1], prev[j])
# cur[t+1] = prev[t] & c_t
b.and_eq(cur[t + 1], prev[t], c_vars[t])
# output[t] = z_{number of updates after round t}
for t in range(N):
bit = out_bits[t]
for j, u in enumerate(cnt[t]):
b.add_clause([-u, z_vars[j] if bit else -z_vars[j]])
return b, seed_vars, forced_controls
def simulate(mask1: int, mask2: int, seed: int, n: int = N) -> int:
s1 = bits_of_int(seed, n)
s2 = bits_of_int(seed, n)
m1 = bits_of_int(mask1, n)
m2 = bits_of_int(mask2, n)
def upd(st, mk):
fb = 0
for a, b in zip(st, mk):
fb ^= a & b
return st[1:] + [fb]
out = 0
for _ in range(n):
s1 = upd(s1, m1)
c = s1[-1]
if c:
s2 = upd(s2, m2)
out = (out << 1) | s2[-1]
return out
def seed_from_model(seed_vars: List[int], model) -> int:
out = 0
for i, var in enumerate(seed_vars):
if model[var]:
out |= 1 << (N - 1 - i)
return out
def blocking_clause_for_seed(seed_vars: List[int], seed: int) -> List[int]:
bits = bits_of_int(seed, N)
return [(-seed_vars[i] if b else seed_vars[i]) for i, b in enumerate(bits)]
def try_decrypt(seed: int, enc: bytes) -> Optional[bytes]:
try:
key = hashlib.md5(str(seed).encode()).digest()
pt = unpad(AES.new(key, AES.MODE_ECB).decrypt(enc), 16)
except Exception:
return None
txt = pt.decode(errors="replace")
return pt if SECRET_RE.fullmatch(txt) else None
class Tube:
def __init__(self, sock: socket.socket) -> None:
self.f = sock.makefile("rwb", buffering=0)
def recvuntil(self, token: bytes) -> bytes:
buf = bytearray()
while not buf.endswith(token):
ch = self.f.read(1)
if not ch:
raise EOFError("connection closed")
buf += ch
return bytes(buf)
def recvline(self) -> bytes:
line = self.f.readline()
if not line:
raise EOFError("connection closed")
return line
def sendline(self, data: bytes) -> None:
self.f.write(data + b"\n")
def recvall(self) -> bytes:
return self.f.read()
def read_remote(t: Tube):
t.recvuntil(b"mask1 = ")
mask1 = int(t.recvline().strip())
t.recvuntil(b"mask2 = ")
mask2 = int(t.recvline().strip())
t.recvuntil(b"output = ")
output = int(t.recvline().strip())
t.recvuntil(b"enc = ")
enc = bytes.fromhex(t.recvline().strip().decode())
return mask1, mask2, output, enc
def solve_instance(mask1: int, mask2: int, output: int, enc: bytes,
threads: int, max_models: int, log_every: int = 10):
t0 = time.time()
solver = Solver(threads=threads)
builder, seed_vars, forced_controls = build_formula(mask1, mask2, output, solver)
flips = output_flip_count(output)
print(
f"[*] formula: vars={builder.vp.cnt} clauses={builder.clauses} "
f"xors={builder.xors} flips={flips} forced_controls={forced_controls}"
)
for idx in range(1, max_models + 1):
sat, model = solver.solve()
if sat is None:
raise RuntimeError("solver resource limit")
if not sat:
raise RuntimeError(f"UNSAT after blocking {idx-1} candidate(s)")
seed = seed_from_model(seed_vars, model)
if simulate(mask1, mask2, seed) != output:
raise RuntimeError(f"candidate {idx} does not reproduce output")
pt = try_decrypt(seed, enc)
if idx == 1 or idx % log_every == 0 or pt is not None:
rate = idx / max(1e-9, (time.time() - t0))
print(
f"[*] candidate {idx}: seed = {seed} "
f"{'(valid secret)' if pt else '(AES mismatch)'} "
f"elapsed={time.time()-t0:.2f}s rate={rate:.2f}/s"
)
if pt is not None:
return seed, pt, idx
solver.add_clause(blocking_clause_for_seed(seed_vars, seed))
raise RuntimeError(f"no valid seed found in first {max_models} candidate(s)")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--host", default="nc1.ctfplus.cn")
ap.add_argument("--port", type=int, default=16215)
ap.add_argument("--threads", type=int, default=1)
ap.add_argument("--attempts", type=int, default=20)
ap.add_argument("--max-models", type=int, default=120)
ap.add_argument("--min-flips", type=int, default=26)
args = ap.parse_args()
for attempt in range(1, args.attempts + 1):
print(f"\n================ attempt {attempt}/{args.attempts} ================")
try:
with socket.create_connection((args.host, args.port), timeout=10) as sock:
sock.settimeout(None)
t = Tube(sock)
mask1, mask2, output, enc = read_remote(t)
flips = output_flip_count(output)
print(f"[*] mask1 = {mask1}")
print(f"[*] mask2 = {mask2}")
print(f"[*] output = {output}")
print(f"[*] enc = {enc.hex()}")
print(f"[*] output flips = {flips}")
if flips < args.min_flips:
print(f"[*] skip instance: flips {flips} < min_flips {args.min_flips}")
continue
seed, pt, used = solve_instance(mask1, mask2, output, enc, args.threads, args.max_models)
print(f"[+] seed = {seed}")
print(f"[+] secret = {pt.decode(errors='replace')}")
print(f"[+] models tried = {used}")
try:
t.recvuntil(b"> ")
t.sendline(pt)
print(t.recvall().decode(errors="replace"))
except Exception as e:
print(f"[*] auto-submit failed: {e}")
return 0
except Exception as e:
print(f"[-] attempt {attempt} failed: {e}")
print("[-] exhausted attempts without success")
return 1
if __name__ == "__main__":
raise SystemExit(main())运行方式:
python3 final_exp_mlfsr.py --host nc1.ctfplus.cn --port 16215 --threads 1 --attempts 2000 --max-models 120 --min-flips 26回显示例(复现版):
================ attempt 368/2000 ================
[*] mask1 = 10221747515257854604
[*] mask2 = 17877858789034724851
[*] output = 16559309633878980725
[*] enc = b0ae24e3dec3e7a751ea091d26c60e34f412258d5007bb356db040d5c9bb8477facda8b1f1881cafc882536b876d2db3
[*] output flips = 26
[*] formula: vars=2337 clauses=10617 xors=129 flips=26 forced_controls=26
[*] candidate 1: seed = 9582451577998823576 (valid secret) elapsed=4.81s rate=0.21/s
[+] seed = 9582451577998823576
[+] secret = fakeflag{997ab6dca75a1892802d61f43f6a0c9c}
[+] models tried = 1
🤭: xmctf{f7157984-0cc1-49fe-a152-042f960a33bb}