一、题目信息
meta 内容:
afterburn/v1|vendor=BurnLabs (TM)|product=BAR-404|batch=T1P-2026|note=warranty void if read twice二、解题思路
reader.npz里的firmware不是二进制,而是"一次性看图器"的完整 Python 源码。这题的核心不是逆向,而是把"被烧掉的钥匙"补回来。读源码得到完整算法:
# 密钥基的"指纹"——整张图的位置都由它派生
def fingerprint(basis):
h = hashlib.sha256(b"afterburn/v1|")
for row in basis:
h.update(struct.pack(">64q", *[int(round(float(v) * 1024)) for v in row]))
return h.digest()
def positions(seed, total, count): # sha256(seed + >Q(i)) 前 8 字节 % total,去重
def read_payload(rgb, basis):
seed = fingerprint(basis)
bit = 1 if (rgb[p] % 8) >= 4 else 0 # 只取"像素字节 % 8 >= 4"
# 数据 = magic("BURN", 4B) + len(4B) + payload + crc32(payload)(4B)burn()会把 basis 的某一行置 0,main()用basis.T @ basis == I做完整性检查,失败就直接退出——所以第一遍读完,钥匙就废了,符合"阅后即焚"。于是思路很明确:把被烧掉的那一行精确还原 → fingerprint 对了 → 图里的 payload 就出来了。
题面最后一句"烧归烧,别把基烧歪"是关键提示:
basis本来是正交矩阵。本题的 basis 有个坑——64 行范数全是 1(所以"找全零行"会一无所获),但去掉第 63 行后其余 63 行严格正交(残差8.9e-16)。被烧的第 63 行就是其余 63 行的零空间方向,在 R^64 里唯一(差一个符号)。
三、关键步骤
1. 定位被烧的行
对每一行 i,去掉它后计算 max|B_rest · B_rest^T − I|:
remove row 63: residual orthonormality error = 8.882e-16 ← 就是它
remove 其他行: 2.5e-1 ~ 3.7e-12. 用零空间还原这一行
u, s, vt = np.linalg.svd(B[:63])
q = vt[-1] / np.linalg.norm(vt[-1]) # 63 行的正交补(1 维),单位化还原后 B[63] = ±q 时,max|B·B^T − I| = 8.9e-16,基恢复正交。
3. 处理符号歧义
真基是正交矩阵,所以真行只可能是 ±q。分别代入算 fingerprint、读 64 bit 头部、验 magic:
sign +1: magic=4255524e len=31 ← "BURN"
sign -1: magic=c70df6e7 len=10116717924. 读 payload 并校验
payload = b'PCTF{is_yangyangyang_buzhunkan}'
文件内末尾 32 bit 校验 = 24a9e771
crc32(payload) = 24a9e771 ✔5. 交叉验证:跑厂商原版固件
把 basis[63] 换回 q 存成新的 npz,直接执行 firmware.py(改名为 viewer.py,同目录放 stego.bmp):
[reader] BurnLabs (TM), firmware v0.4
[reader] meta: afterburn/v1|vendor=BurnLabs (TM)|product=BAR-404|...
[reader] burn module: skipped (model looks suspiciously intact)
[reader] payload: PCTF{is_yangyangyang_buzhunkan}厂商自己都认了:"这块模型看起来可疑地完整"。
四、易踩的坑
burn不是清零。 本题把第 63 行换成了一个诱饵单位向量:det(B) = q·v = 0.104,也就是诱饵几乎与真行正交。正因如此行范数仍全是 1,"找零行"的直觉会完全失效,必须用整体正交性去定位。不要把行"量化还原"。 basis 的 float64 并不落在
1/1024网格上(最大偏差 ≈ 0.5);round(v*1024)只是 fingerprint 的量化,用 SVD 还原到1e-15精度就足以让round稳定。符号不能靠
q·v猜(0.104 太小),必须+q / −q都试,用 magic(0x4255524E)+crc32判定。BMP 细节别搞错:24bpp、自下而上存储、行 stride 有 2 字节对齐填充(974×3=2922 → 2924),并且是 BGR 顺序。必须严格按 firmware 里
read_bmp的语义还原成rgb[y*w*3 + x*3 + c],否则位置全错,magic 永远对不上。取 bit 的规则是
rgb[p] % 8 >= 4(不是最低位% 2),这是个容易看漏的点。
五、拿到 Flag
PCTF{is_yangyangyang_buzhunkan}六、Exp
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PCTF · Misc - 阅后即焚 (257 pts)
附件: attachments.zip -> stego.bmp (974x974 24bpp) + reader.npz (basis/firmware/meta)
思路:
reader.npz 里 firmware 就是"一次性看图器"的完整源码, 它说明:
seed = sha256("afterburn/v1|" + 每行 round(v*1024) 打包成 >64q)
位置 = sha256(seed + >Q(i)) 前 8 字节 % total (去重)
bit = 1 if rgb[p] % 8 >= 4 else 0
数据 = magic("BURN",4B) + len(4B) + payload + crc32(payload)(4B)
而 burn() 会把 basis 的某一行清零 -> 完整性检查 (basis^T basis == I) 失败。
本题实际是把第 63 行换成了一个诱饵单位向量(所以行范数都还是 1, 找"全零行"找不到)。
但 basis 本应是正交矩阵: 去掉被烧的那行后, 其余 63 行严格正交, 于是被烧的行
= 其余 63 行的零空间方向(1 维), 用 SVD 取最后一个右奇异向量即可还原(差一个符号)。
用法:
python "Misc - 阅后即焚 - exp.py" attachments.zip
python "Misc - 阅后即焚 - exp.py" <含 reader.npz 与 stego.bmp 的目录>
依赖: numpy (标准库以外仅此一个)
"""
import hashlib
import os
import struct
import sys
import tempfile
import zipfile
import zlib
import numpy as np
MAGIC = 0x4255524E # b"BURN"
DELTA = 8
SCALE = 1024
# ------------------------------------------------------------ BMP
def read_rgb(path):
"""按 firmware 的 read_bmp 语义读出 RGB 三通道扁平数组(y*w*3 + x*3 + c)."""
data = open(path, "rb").read()
assert data[:2] == b"BM", "not a bmp"
off = struct.unpack_from("<I", data, 10)[0]
w = struct.unpack_from("<i", data, 18)[0]
h = struct.unpack_from("<i", data, 22)[0]
bpp = struct.unpack_from("<H", data, 28)[0]
assert bpp == 24, "expect 24bpp bmp"
bottom_up = h > 0
h = abs(h)
stride = (w * 3 + 3) // 4 * 4
pix = np.frombuffer(data, dtype=np.uint8, offset=off, count=stride * h).reshape(h, stride)
rows_bgr = pix[:, :w * 3].reshape(h, w, 3) # 文件顺序(可能自下而上)
rgb = rows_bgr[::-1, :, ::-1] if bottom_up else rows_bgr[:, :, ::-1]
return w, h, rgb.reshape(-1)
# ------------------------------------------------------------ firmware 逻辑
def fingerprint(basis):
h = hashlib.sha256(b"afterburn/v1|")
for row in basis:
h.update(struct.pack(">64q", *[int(round(float(v) * SCALE)) for v in row]))
return h.digest()
def positions(seed, total, count):
out, seen, i = [], set(), 0
while len(out) < count:
d = hashlib.sha256(seed + struct.pack(">Q", i)).digest()
p = int.from_bytes(d[:8], "big") % total
if p not in seen:
seen.add(p)
out.append(p)
i += 1
return out
def bits_to_bytes(bits):
out = bytearray()
for i in range(0, len(bits), 8):
v = 0
for b in bits[i:i + 8]:
v = (v << 1) | b
out.append(v)
return bytes(out)
def read_payload(rgb, basis):
seed = fingerprint(basis)
total = len(rgb)
def getbits(n):
return [1 if (rgb[p] % DELTA) >= DELTA // 2 else 0
for p in positions(seed, total, n)]
blob64 = bits_to_bytes(getbits(64))
magic, ln = struct.unpack(">II", blob64)
if magic != MAGIC:
return None
n = 64 + 8 * ln + 32
blob = bits_to_bytes(getbits(n))
return blob[8:8 + ln], struct.unpack(">I", blob[8 + ln:12 + ln])[0]
# ------------------------------------------------------------ 修复被烧的行
def find_burnt_row(B):
"""找出被烧掉的那一行: 去掉它之后其余行最接近标准正交."""
n = B.shape[0]
eye = np.eye(n - 1)
best, best_err = None, None
for i in range(n):
mask = np.ones(n, dtype=bool)
mask[i] = False
sub = B[mask]
err = np.abs(sub @ sub.T - eye).max()
if best_err is None or err < best_err:
best, best_err = i, err
return best, best_err
def reconstruct_row(B, idx):
"""其余行张成的正交补(1 维), 返回单位向量."""
n = B.shape[0]
mask = np.ones(n, dtype=bool)
mask[idx] = False
u, s, vt = np.linalg.svd(B[mask])
q = vt[-1]
return q / np.linalg.norm(q)
# ------------------------------------------------------------ main
def load_inputs(path):
d = path
if os.path.isfile(path) and zipfile.is_zipfile(path):
d = tempfile.mkdtemp(prefix="burn_")
with zipfile.ZipFile(path) as z:
z.extractall(d)
npz = os.path.join(d, "reader.npz")
bmp = os.path.join(d, "stego.bmp")
if not (os.path.exists(npz) and os.path.exists(bmp)):
sys.exit("[!] 需要 reader.npz 与 stego.bmp")
return npz, bmp
def main():
if len(sys.argv) < 2:
sys.exit('用法: python "Misc - 阅后即焚 - exp.py" <attachments.zip | 目录>')
npz_path, bmp_path = load_inputs(sys.argv[1])
z = np.load(npz_path, allow_pickle=True)
B = z["basis"].astype(np.float64)
print("[*] basis %s firmware %d B meta: %s"
% (B.shape, z["firmware"].size,
bytes(z["meta"].tolist()).decode("utf-8", "replace")))
print("[*] 完整性: max|B B^T - I| = %.3f (应为 0, 说明被烧过)"
% np.abs(B @ B.T - np.eye(B.shape[0])).max())
idx, err = find_burnt_row(B)
print("[*] 被烧的行 = %d, 去掉它后 max|B B^T - I| = %.3e" % (idx, err))
q = reconstruct_row(B, idx)
print("[*] 与文件里残留行的夹角 det = %.6f (说明烧成了近似正交的诱饵)"
% abs(float(q @ B[idx])))
w, h, rgb = read_rgb(bmp_path)
print("[*] bmp %dx%d, rgb 字节数 %d" % (w, h, len(rgb)))
for sgn in (1, -1):
cand = B.copy()
cand[idx] = sgn * q
if np.abs(cand @ cand.T - np.eye(B.shape[0])).max() > 1e-6:
continue
res = read_payload(rgb, cand)
if res is None:
continue
payload, chk = res
ok = (zlib.crc32(payload) & 0xFFFFFFFF) == chk
print("[*] 符号 %+d: payload=%r 文件内校验=%08x crc32=%08x %s"
% (sgn, payload, chk, zlib.crc32(payload) & 0xFFFFFFFF,
"OK" if ok else "MISMATCH"))
if ok:
print()
print("FLAG: %s" % payload.decode("utf-8", "replace"))
return
sys.exit("[!] 两种符号都没通过校验")
if __name__ == "__main__":
main()