这次的PCTF有幸的能够参与出题,出的题目还是比较难的,我自己感觉,对于初学者来说还是有点困难的,我尽可能的将这个题解写详细一点,希望能够给大家将明白,这次出题主要是围绕现代密码的考点,希望大家从中有所收获,下面是第一二周的我出的题的wp,如有问题及时指出。

来签个到吧

拿到题目查看主要的泄漏点在哪,有这样的一段代码

e1 = 65537
e2 = 17
m = bytes_to_long(flag)

n = p * q
c1 = pow(m, e1, n)
c2 = pow(m * r % n, e2, n)   # r 是与 n 互素的随机掩码
c3 = pow(r, e2, n)

输出 n, e1, e2, c1, c2, c3。

同一条消息,一次用大指数,一次先乘随机掩码再用小指数。但教科书 RSA 是乘法同态的:

E(x·y) = E(x)·E(y) mod n

于是 c2 可以拆开:

c2 = (m·r)^e2 = m^e2 · r^e2 = m^e2 · c3  (mod n)

c3 恰好就是 r^e2,掩码被完全抵消:

cm = c2 · c3^(-1) mod n = m^e2 mod n

此时手上有同一个 n、同一条 m 在两个互素指数下的密文:

c1 = m^e1 mod n
cm = m^e2 mod n
gcd(e1, e2) = gcd(65537, 17) = 1

这是其实就是一个标准的共模攻击(common modulus attack)了。用扩展欧几里得求 a·e1 + b·e2 = 1,则

m = m^(a·e1 + b·e2) = c1^a · cm^b mod n

其中 a、b 必有一负,负指数用模逆元处理。

exp

from pathlib import Path
from Crypto.Util.number import *
output_path = Path(__file__).resolve().parent.parent / "output.txt"
values = {}
for line in output_path.read_text(encoding="utf-8").splitlines():
    name, value = line.split(" = ")
    values[name] = int(value)

n = values["n"]
e1 = values["e1"]
e2 = values["e2"]
c1 = values["c1"]
c2 = values["c2"]
c3 = values["c3"]


def extended_gcd(a, b):
    if b == 0:
        return a, 1, 0
    g, x1, y1 = extended_gcd(b, a % b)
    return g, y1, x1 - (a // b) * y1


def signed_pow(value, exponent, modulus):
    if exponent < 0:
        value = pow(value, -1, modulus)
        exponent = -exponent
    return pow(value, exponent, modulus)

masked_removed = c2 * pow(c3, -1, n) % n    

g, a, b = extended_gcd(e1, e2)
assert g == 1

m = signed_pow(c1, a, n) * signed_pow(masked_removed, b, n) % n
print(long_to_bytes(m))

运行结果:

PCTF{aDypQ7XuDNoGYH4p1tGU7lBuS0Ju}

少了六轮

查看题目发现chall.py 是一份"完整但被剪枝"的 AES-128 实现,里面的状态布局、S-box(用 GF(2^8) 逆元 + 循环移位仿射变换现场生成)、ShiftRows、MixColumns、密钥扩展都是标准写法,唯一区别是

ROUNDS = 4      # 正常 AES-128 是 10 轮

轮结构为:

AddRoundKey(K0)
Round 1..3 : SubBytes -> ShiftRows -> MixColumns -> AddRoundKey
Round 4    : SubBytes -> ShiftRows -> AddRoundKey      (没有 MixColumns)

generate() 的产出:

随机选 4 个活动字节位置(本题实例为 0, 5, 6, 7);

每个位置造一个 delta set:其余 15 字节固定,该字节遍历 0..255,共 256 条 (pt, ct);

4 组共 1024 条,全局打乱后才写进 output.json;

另给 flag_iv 与 flag_ciphertext,是用同一把密钥做的 4 轮 AES-CBC 加密。

于是攻击链是:重建 delta set → 积分攻击拿第 4 轮轮密钥 → 逆密钥扩展拿主密钥 → 解密 flag。

数据里没有分组标签,但 delta set 有一个无法隐藏的指纹:去掉活动字节后,剩下 15 个字节完全相同。

对每一条明文、每一个假设的活动位置 j,计算

fingerprint = plaintext[:j] + plaintext[j + 1:]

用 (j, fingerprint)做 key 分桶。若某个桶恰好 256 条、且被删位置取值集合正好是0..255、16 条明文两两不同,那它就是一组 delta set。4 组互不相交且覆盖全部 1024 条,重建即完成。

一个 delta set 只有 1 个活动字节,关键性质是经过 3 轮完整加密后,状态每个字节的异或和都为 0。推导分三步:

  1. 第 1 轮后:活动字节 a 遍历 0..255,S-box 是双射,输出仍遍历 0..255;经 ShiftRows 扩散到 4 个不同列、再经 MixColumns(对单字节就是乘以常数,可逆线性变换)后,这 4 个字节各自仍是 a的置换,异或和 = 0⊕1⊕…⊕255 = 0。

  2. 第 2 轮后:每个字节都是某一个"置换字节"经可逆线性变换 + 常量的结果,因此 16 个字节全都重新变成 a 的置换(又回到 Λ-set 形态)。

  3. 第 3 轮:MixColumns 是线性的,每个输出字节 = 4 个置换字节的线性组合,而"异或和为 0"在线性组合下保持,故第 3 轮输出 16 个字节全部平衡。

注意第 3 轮之后这些字节不再是置换(S-box 作用在非置换集合上会破坏 Λ-set 性质),但"平衡"这一点刚好够用。

第 4 轮没有 MixColumns,所以密文字节 ct[pos] 只由第 3 轮状态的某个字节 x 经 SubBytes 与 AddRoundKey 得到:

ct[pos] = S(x) xor k          →      x = InvSbox(ct[pos] xor k)

对正确的末轮密钥字节 k,InvSbox(ct[pos] xor k) 就是那 256 个平衡值之一,因此

xor_{i=0..255} InvSbox(ct_i[pos] xor k) == 0

枚举 k = 0..255,把满足平衡性的候选留下,四组取交集后全部唯一。

AES-128 把 16 字节主密钥切成 w[0..3],之后

w[i] = w[i-4] xor SubWord(RotWord(w[i-1])) xor Rcon(i/4)   (i % 4 == 0)
w[i] = w[i-4] xor w[i-1]                                   (i % 4 != 0)

已知第 4 轮轮密钥就是 w[16..19],把上式反过来:

w[i-4] = w[i] xor transform(w[i-1])

从 i = 19 一路回推到 w[0],即得主密钥。本题实例结果:

末轮密钥 : 4f593793a6e544f3f55ff911e23483db
主密钥   : 272c2ae9dd3e9cb8b843b9fa95eef72b

用主密钥重新 expand_key 出 5 组轮密钥,直接调用题目自己的 cbc_decrypt(4 轮逆变换 + PKCS#7),得到 flag。

exp

import argparse
import importlib.util
import json
from pathlib import Path


def load_challenge(path):
    specification = importlib.util.spec_from_file_location("reduced_aes_challenge", path)
    module = importlib.util.module_from_spec(specification)
    specification.loader.exec_module(module)
    return module


def inspect_batch(batch):
    if len(batch) != 256:
        raise ValueError("Each delta set must contain 256 pairs")
    plaintexts = [bytes.fromhex(pair["pt"]) for pair in batch]
    ciphertexts = [bytes.fromhex(pair["ct"]) for pair in batch]
    if any(len(block) != 16 for block in plaintexts + ciphertexts):
        raise ValueError("Invalid block length")
    varying = []
    for index in range(16):
        values = {plaintext[index] for plaintext in plaintexts}
        if len(values) > 1:
            varying.append(index)
        elif len(values) != 1:
            raise ValueError("Invalid plaintext set")
    if len(varying) != 1:
        raise ValueError("Batch is not a one-byte delta set")
    active = varying[0]
    if {plaintext[active] for plaintext in plaintexts} != set(range(256)):
        raise ValueError("Active byte does not cover all values")
    if len(set(plaintexts)) != 256:
        raise ValueError("Duplicate plaintext in delta set")
    return active, ciphertexts


def reconstruct_batches(samples):
    """按 (活动字节位置, 其余 15 字节指纹) 分桶,重建 4 个 delta set。"""
    if not isinstance(samples, list) or len(samples) != 4 * 256:
        raise ValueError("Expected 1024 shuffled samples")
    buckets = {}
    for sample_index, pair in enumerate(samples):
        plaintext = bytes.fromhex(pair["pt"])
        ciphertext = bytes.fromhex(pair["ct"])
        if len(plaintext) != 16 or len(ciphertext) != 16:
            raise ValueError("Invalid sample block length")
        for active in range(16):
            fingerprint = plaintext[:active] + plaintext[active + 1:]
            buckets.setdefault((active, fingerprint), []).append(sample_index)
    reconstructed = []
    memberships = set()
    for (active, _), indices in buckets.items():
        if len(indices) != 256:
            continue
        batch = [samples[index] for index in indices]
        detected, _ = inspect_batch(batch)
        if detected != active:
            continue
        reconstructed.append(batch)
        memberships.update(indices)
    if len(reconstructed) != 4 or len(memberships) != len(samples):
        raise ValueError("Could not reconstruct four disjoint delta sets")
    reconstructed.sort(key=lambda batch: inspect_batch(batch)[0])
    return reconstructed


def candidates_for_byte(ciphertexts, position, inverse_sbox):
    """积分平衡:正确末轮密钥字节满足 xor InvSbox(ct[pos]^k) == 0。"""
    candidates = set()
    for key_byte in range(256):
        balanced = 0
        for ciphertext in ciphertexts:
            balanced ^= inverse_sbox[ciphertext[position] ^ key_byte]
        if balanced == 0:
            candidates.add(key_byte)
    return candidates


def recover_last_round_key(batches, challenge):
    candidates = [set(range(256)) for _ in range(16)]
    active_positions = []
    candidate_history = []
    for batch in batches:
        active, ciphertexts = inspect_batch(batch)
        active_positions.append(active)
        sizes = []
        for position in range(16):
            candidates[position] &= candidates_for_byte(ciphertexts, position, challenge.INV_SBOX)
            sizes.append(len(candidates[position]))
        candidate_history.append(sizes)
    unresolved = {index: sorted(values) for index, values in enumerate(candidates) if len(values) != 1}
    if unresolved:
        raise ValueError(f"Last round key is not unique: {unresolved}")
    return bytes(next(iter(values)) for values in candidates), active_positions, candidate_history


def reverse_key_schedule(last_round_key, last_round, challenge):
    """已知 w[16..19],从 i=19 反推到 w[0..3]。"""
    if len(last_round_key) != 16 or last_round < 1:
        raise ValueError("Invalid round key")
    words = {
        4 * last_round + offset: last_round_key[4 * offset:4 * offset + 4]
        for offset in range(4)
    }
    for index in range(4 * last_round + 3, 3, -1):
        temporary = words[index - 1]
        if index % 4 == 0:
            temporary = bytearray(challenge.sub_word(challenge.rot_word(temporary)))
            temporary[0] ^= challenge.rcon(index // 4)
            temporary = bytes(temporary)
        words[index - 4] = challenge.xor_bytes(words[index], temporary)
    return b"".join(words[index] for index in range(4))


def solve(document, challenge):
    if document.get("cipher") != "AES-128" or document.get("rounds") != challenge.ROUNDS:
        raise ValueError("Unexpected cipher configuration")
    batches = reconstruct_batches(document.get("samples"))
    last_round_key, active_positions, candidate_history = recover_last_round_key(batches, challenge)
    master_key = reverse_key_schedule(last_round_key, document["rounds"], challenge)
    round_keys = challenge.expand_key(master_key, document["rounds"])
    if round_keys[-1] != last_round_key:
        raise ValueError("Reversed key schedule does not match")
    # 全量重放校验
    for batch in batches:
        for pair in batch:
            plaintext = bytes.fromhex(pair["pt"])
            ciphertext = bytes.fromhex(pair["ct"])
            if challenge.encrypt_block(plaintext, round_keys) != ciphertext:
                raise ValueError("Recovered key does not reproduce samples")
    plaintext = challenge.cbc_decrypt(
        bytes.fromhex(document["flag_ciphertext"]),
        round_keys,
        bytes.fromhex(document["flag_iv"]),
    )
    return {
        "master_key": master_key,
        "last_round_key": last_round_key,
        "active_positions": active_positions,
        "candidate_history": candidate_history,
        "plaintext": plaintext,
    }


parser = argparse.ArgumentParser(description="Square attack against the four-round AES challenge")
parser.add_argument("attachment", nargs="?", type=Path, default=Path(__file__).resolve().parent.parent)
attachment = parser.parse_args().attachment.resolve()
challenge = load_challenge(attachment / "chall.py")
document = json.loads((attachment / "output.json").read_text(encoding="utf-8-sig"))
result = solve(document, challenge)
for index, sizes in enumerate(result["candidate_history"], 1):
    print(f"  batch {index}: {sizes}")
print("Round 4 key:", result["last_round_key"].hex())
print("Master key:", result["master_key"].hex())
print("Flag:", result["plaintext"].decode("ascii"))

实测输出:

  batch 1: [1, 2, 2, 2, 1, 2, 2, 1, 3, 1, 1, 2, 2, 2, 1, 3]
  batch 2: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
  batch 3: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
  batch 4: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Round 4 key: 4f593793a6e544f3f55ff911e23483db
Master key: 272c2ae9dd3e9cb8b843b9fa95eef72b
Flag: PCTF{o8ZIbudgwdjwS47v8zAqvKbz2tHqg5zv}

格雷噪影

题目里面256 bit 的 p、q,公开 n、e = 65537、c,以及一条带噪声的泄露:

def gray(x): return x ^ (x >> 1)
leak = gray(p) ^ reverse_bits(gray(q), 256)
leak ^= 1 << noise_position          # 恰好一位翻转,位置不公开
noise_position = 32 + randbelow(192)  # 只落在内部,不会碰端点

目标是恢复 p, q 并正常 RSA 解密。

把 256 bit 整数的位从最高位(MSB)开始编号为 p[0..255],Gray Code 的逐位关系(等价于 x ^ (x >> 1) 的整数位形式)为

gray(p) 的第 k 位(MSB 编号 k,1 ≤ k ≤ 254) = p[k-1] xor p[k]

而 reverse_bits 把 q 的位序颠倒,于是

leak[k] = p[k-1] xor p[k] xor q[254-k] xor q[255-k]

也就是说:每一条泄露方程同时牵住 p 的高位相邻两位和 q 的低位相邻两位(镜像位置)。这是本题能"边搜边剪"的根本原因——它不是一条位独立泄露,而是一组链式关系。

端点(k = 0、k = 255)另算。p、q 都是定长 256 bit 奇素数,所以 p[0] = q[0] = 1(MSB)且 p[255] = q[255] = 1(LSB)。代入可得:

leak[0]   = q[254]      # 给出 q 的次低位
leak[255] = 0           # 因两端最低位都是 1,恒为 0

所以起点是:p、q 的最高 1 位、最低 1 位已知,q 的次低位由 leak[0] 给出,p 的次低位在本题实例中(p ≡ 1 mod 4)为 0。求解器为了通用性仍然把这两个端点位各枚举 0/1。

从两端同时向中间推,状态为:

ph, qh : 已恢复的高位前缀
pl, ql : 已恢复的低位后缀
high_len, low_len : 两侧已确定的位数(不变式 low_len = high_len + 1)
errors : 当前路径与 leak 不一致的位数

每层同时扩展 4 个比特(p 的一个高位 + q 的一个低位,p 的一个低位 + q 的一个高位),而不是 2 个:

  • 处理 leak[high_len] 时枚举 p[high_len] 与 q[254-high_len],异或约束把 4 种组合压成每对 2 种可行;

  • 处理 leak[255-high_len] 时枚举 p[254-high_len] 与 q[high_len];

  • 两组组合再乘起来,每层通常只剩 4 个有效分支。

这样每一层消耗 2 条泄露方程,递归深度约 127,搜索树被压得极小。

不能要求每条方程都成立(leak 里恰好有 1 位是错的)。做法是把错误计数当成状态:

new_errors = errors + high_mismatch + low_mismatch
if new_errors > EXPECTED_ERRORS:     # EXPECTED_ERRORS = 1
    continue

搜索结束时要求 errors == 1,并顺便记录错误位置(= 噪声位置)。这样不需要另外枚举 256 个可能的噪声位置,噪声位置会随正确路径自然浮现。这是一位噪声容错在剪枝搜索里的标准写法,代价只是每层多几个分支。

(1)低位同余剪枝。 当 p、q 的低 k = low_len 位确定后,乘积的低 k 位就被完全钉死,与未知高位无关:

(p_low * q_low) mod 2^k == n mod 2^k

这一条在搜索早期极强,实测贡献了 41 万次剪枝。

(2)乘积区间剪枝。 把尚未确定的中间位分别全填 0 和全填 1,得到 p_min/p_max、q_min/q_max;正确路径必须满足

p_min * q_min <= n <= p_max * q_max

不满足即说明当前高低位组合不可能拼出 n 的两个因子。实测剪掉 20.8 万次。

256 是偶数,双向搜索最后会剩 p、q 各一个中间位,枚举 4 种组合、检查两条剩余泄露方程与 p * q == n,即得唯一解。

exp

from pathlib import Path
from time import perf_counter

from Crypto.Util.number import inverse, long_to_bytes


BITS = 256
EXPECTED_ERRORS = 1


def load_output():
    values = {}
    output_path = Path(__file__).resolve().parents[1] / "output.txt"
    for line in output_path.read_text(encoding="utf-8").splitlines():
        if " = " in line:
            key, value = line.split(" = ", 1)
            values[key] = int(value)
    return values["n"], values["e"], values["c"], values["leak"]


def recover_factors(n: int, leak: int):
    answers = []
    nodes = 0
    interval_prunes = 0
    modular_prunes = 0

    def leak_bit(index):
        # index 为 MSB 编号
        return (leak >> (BITS - 1 - index)) & 1

    def product_interval_ok(ph, qh, pl, ql, high_len, low_len):
        nonlocal interval_prunes
        middle_len = BITS - high_len - low_len
        fill = ((1 << middle_len) - 1) << low_len if middle_len else 0

        p_min = (ph << (middle_len + low_len)) | pl
        q_min = (qh << (middle_len + low_len)) | ql
        p_max = p_min | fill
        q_max = q_min | fill

        if p_min * q_min <= n <= p_max * q_max:
            return True

        interval_prunes += 1
        return False

    def finish(ph, qh, pl, ql, high_len, low_len, errors, error_index):
        nonlocal nodes
        high_index = high_len
        low_index = BITS - 1 - high_len

        p_high_neighbor = ph & 1
        q_high_neighbor = qh & 1
        p_low_neighbor = (pl >> (low_len - 1)) & 1
        q_low_neighbor = (ql >> (low_len - 1)) & 1

        for p_middle in (0, 1):
            for q_middle in (0, 1):
                nodes += 1
                high_mismatch = (
                    p_high_neighbor ^ p_middle ^ q_middle ^ q_low_neighbor
                ) != leak_bit(high_index)
                low_mismatch = (
                    p_middle ^ p_low_neighbor ^ q_high_neighbor ^ q_middle
                ) != leak_bit(low_index)

                total_errors = errors + high_mismatch + low_mismatch
                if total_errors != EXPECTED_ERRORS:
                    continue

                final_error = error_index
                if high_mismatch:
                    final_error = high_index
                if low_mismatch:
                    final_error = low_index

                p = (ph << (low_len + 1)) | (p_middle << low_len) | pl
                q = (qh << (low_len + 1)) | (q_middle << low_len) | ql

                if p * q == n:
                    answers.append((p, q, final_error))

    def dfs(ph, qh, pl, ql, high_len, low_len, errors, error_index):
        nonlocal nodes, modular_prunes
        nodes += 1

        if high_len + low_len == BITS - 1:
            finish(ph, qh, pl, ql, high_len, low_len, errors, error_index)
            return

        high_index = high_len
        low_index = BITS - 1 - high_len

        p_high_neighbor = ph & 1
        q_high_neighbor = qh & 1
        p_low_neighbor = (pl >> (low_len - 1)) & 1
        q_low_neighbor = (ql >> (low_len - 1)) & 1

        for p_high in (0, 1):
            for q_low in (0, 1):
                high_mismatch = (
                    p_high_neighbor ^ p_high ^ q_low ^ q_low_neighbor
                ) != leak_bit(high_index)
                if errors + high_mismatch > EXPECTED_ERRORS:
                    continue

                for p_low in (0, 1):
                    for q_high in (0, 1):
                        low_mismatch = (
                            p_low ^ p_low_neighbor ^ q_high_neighbor ^ q_high
                        ) != leak_bit(low_index)
                        new_errors = errors + high_mismatch + low_mismatch
                        if new_errors > EXPECTED_ERRORS:
                            continue

                        new_error_index = error_index
                        if high_mismatch:
                            new_error_index = high_index
                        if low_mismatch:
                            new_error_index = low_index

                        new_high_len = high_len + 1
                        new_low_len = low_len + 1
                        new_ph = (ph << 1) | p_high
                        new_qh = (qh << 1) | q_high
                        new_pl = pl | (p_low << low_len)
                        new_ql = ql | (q_low << low_len)

                        # 剪枝 1:低位同余
                        low_mask = (1 << new_low_len) - 1
                        if ((new_pl * new_ql) & low_mask) != (n & low_mask):
                            modular_prunes += 1
                            continue

                        # 剪枝 2:乘积区间
                        if not product_interval_ok(
                            new_ph, new_qh, new_pl, new_ql, new_high_len, new_low_len,
                        ):
                            continue

                        dfs(
                            new_ph, new_qh, new_pl, new_ql,
                            new_high_len, new_low_len, new_errors, new_error_index,
                        )

    # p、q 为定长 256 bit 奇素数:最高位、最低位均为 1
    for q_second_low in (0, 1):
        first_mismatch = q_second_low != leak_bit(0)
        if first_mismatch > EXPECTED_ERRORS:
            continue

        for p_second_low in (0, 1):
            last_mismatch = p_second_low != leak_bit(BITS - 1)
            errors = first_mismatch + last_mismatch
            if errors > EXPECTED_ERRORS:
                continue

            error_index = None
            if first_mismatch:
                error_index = 0
            if last_mismatch:
                error_index = BITS - 1

            ph = qh = 1
            pl = (p_second_low << 1) | 1
            ql = (q_second_low << 1) | 1

            if ((pl * ql) & 3) != (n & 3):
                continue

            if product_interval_ok(ph, qh, pl, ql, 1, 2):
                dfs(ph, qh, pl, ql, 1, 2, errors, error_index)

    stats = {
        "nodes": nodes,
        "interval_prunes": interval_prunes,
        "modular_prunes": modular_prunes,
    }
    return answers, stats



n, e, c, leak = load_output()
started = perf_counter()
answers, stats = recover_factors(n, leak)
elapsed = perf_counter() - started
assert len(answers) == 1
p, q, error_index_from_msb = answers[0]
phi = (p - 1) * (q - 1)
d = inverse(e, phi)
message = long_to_bytes(pow(c, d, n))
print(p)
print(q)
print(message)

实测输出:

72323431730176883482722461756719255476297880847395631122656391377626147530661
104196316157675496685505698594042770691145421592417373298335576865833633653339
b'PCTF{TSEkPvmL66vGOTdc0mONxZbFJXwgYQh7}'

无声阶梯

这个是我出的最难的题了,这个考点是侧信道攻击的手法,本来想做成动态题目了,感觉不太好实现,所以说将这个直接做成了静态题目,因为是侧信道攻击,所给的数据量很大,文件很大,在解题的时候可能比较乱和杂,如何找到突破口也是一大难点,这也成了PCTF密码方向解最少的一道密码题。

traces.bin:C-order 排列的 little-endian int16,trace_shape = [112, 2, 548864] 即 112 条 × 2 通道 × 548864 采样点(无文件头,可直接 np.memmap)。固件在 secp256k1 上跑固定 264 位 Montgomery ladder(恒定路径,无分支泄漏),目标轨迹的真实标量是

k = d + r·n        d 为 256 bit 私钥,n 为曲线阶,r 为 8 bit 非零盲化值

只要恢复完整 k,就能算 d = k mod n,再用 public.json 里的公钥验证、用 d 派生 AES-256-GCM 密钥解密 flag。

轨迹布局(由生成器和数据可以完全还原):

[ 4096 前缀 ][ 0..1024 随机偏移 ][ 1024 点同步序列 ][ 264 个 slot × 2048 点 ][ 2048 尾 ]
                                          每个 slot = 8 个微操作块 × 256 点

固件每个 slot 内部重新生成独立的随机符号 m ∈ {-1, +1},四个关键微操作块的(简化)泄漏模型是:

L_A = α·m                 (掩码泄漏,不含标量位)
L_B = β·m·(2b-1)·gain     (标量位泄漏,b 为当前 bit)
L_T = τ·m·transition      (相邻位是否翻转)
L_D = δ·m·decoy           (干扰)

由于 m 每个 slot 独立随机,L_B 与 b 的一阶相关性被随机符号彻底破坏:E[L_B | b=1] = E[L_B | b=0] = 0。任何"单窗口均值 / 单窗口模板 / 固定位置 CPA"都拿不到信息。出题人给出的统计审计也印证了这一点:

bank 0: max first-order |rho| = 0.0388,  max second-order |rho| = 0.7783
bank 1: max first-order |rho| = 0.0237,  max second-order |rho| = 0.7654
bank 2: max first-order |rho| = 0.0256,  max second-order |rho| = 0.7753
bank 3: max first-order |rho| = 0.0419,  max second-order |rho| = 0.7691

但 A与 B共享同一个m,于是把两个窗口的泄漏相乘:

L_A · L_B = αβ·m²·(2b-1) = αβ·(2b-1)

随机符号被平方消掉,只剩与标量位同号的分量。这就是本题的核心:单轨迹、slot 内部的二阶(水平)泄漏,而不是传统的跨轨迹 CPA。

接下来进行同步操作

  1. 粗同步:trigger_hint 只精确到约 ±96 点,先在 hint ± 128 的窗口内把通道 0 与 sync_pattern.f32(1024 点、Hamming 窗调制的 ±1 序列)做互相关,取 |corr| 最大处为真实起点。

  2. 定位 slot:sync_start + 1024 之后紧接 264 个 slot,每个 2048 点。

  3. 分块:每个 slot 拆成 8 个 256 点微操作块,取每块中心 [66:190] 的均值(泄漏窗在 center_start≈74 起、宽 108,留了 ±8 的抖动余量)。

  4. 标准化:对同一条轨迹、同一通道、同一物理块,跨 264 个 slot 做 median/MAD 标准化:

median = np.median(raw, axis=1, keepdims=True)
mad = np.median(np.abs(raw - median), axis=1, keepdims=True) * 1.4826 + 1.0
normalized = (raw - median) / mad

这一步同时消掉通道增益、块偏置和慢漂移——生成器里每个块确实注入了 N(0,17) 的偏置和 N(0,14) 的通道级偏置。

之后固件按会话 nonce 选择执行配置:

bank = CRC16-CCITT(nonce || 0x53) & 3     # 初值 0xFFFF,多项式 0x1021

firmware.bin 只有 64 字节,结构是:魔数 NLFW + (version=3, blocks=8, poly=0x1021) + FF FF 53 03 + 4 张各 8 字节的表(XOR 0xA7 混淆)+ 16 字节 SHA-256 截断校验。直接反解:

import struct
b = open("firmware.bin", "rb").read()
print(b[:4], struct.unpack("<HHI", b[4:12]))   # b'NLFW' (3, 8, 4129)
off = 16
for bank in range(4):
    table = bytes(x ^ 0xA7 for x in b[off:off + 8])
    print("bank", bank, "logical order (A,B,T,D) + 剩余块 =", list(table))
    off += 8

输出:

bank 0 [1, 5, 6, 3, 0, 2, 4, 7]      → A=1, B=5, T=6, D=3
bank 1 [6, 2, 4, 0, 1, 3, 5, 7]      → A=6, B=2, T=4, D=0
bank 2 [3, 7, 1, 5, 0, 2, 4, 6]      → A=3, B=7, T=1, D=5
bank 3 [5, 0, 7, 2, 1, 3, 4, 6]      → A=5, B=0, T=7, D=2

manifest["captures"][i]["session_nonce"] 是公开的,所以每条轨迹的 bank 都能算出来。目标 FIELD-017 的 nonce 是 4840c8e055a5e7b3f87ac9477d83d1c6,crc16_ccitt(nonce + b"\x53") & 3 == 0,即 bank 0,关键块对是 (A, B) = (1, 5)。

另外 firmware_revision == "B" 的记录会把逻辑块整体 +2 mod 8(干扰轨迹里有 8 条是 B 版),所以逆向固件后还要处理这个偏移。

这里我们选择了更稳的路线:不手工指定关键块,而是对所有 C(8,2) = 28 个块对 × 2 个通道做乘积,得到 56 维二阶特征,再让统计量自己挑出该 bank 真正有效的块对。这样既不用信任固件映射,也顺带兼容了 revision B。

对每个 bank:

  1. 把该 bank 所有校准 slot 的 56 维特征纵向拼接,标签来自 calibration.json 里 264 bit 标量展开的位序列(校准标量的最高位固定为 1,就是 ladder 的起始位)。

  2. 对每个特征算 bit=0 / bit=1 两类的均值差与合并方差,得到效应量 |Δμ| / sqrt(pooled)。

  3. 取效应量最大的 6 个特征,做对角协方差 LDA:

w = (μ1 - μ0) / pooled
score = orientation · ((x[sel] - center) · w - threshold) / spread
  1. 训练准确率约 97.7% ~ 98.1%(bank 0: 98.05%,bank 1: 97.67%,bank 2: 97.87%,bank 3: 97.77%)。

注意的是高准确率不等于能直接恢复目标,目标轨迹里有 10 个被刻意衰减到 gain ∈ [0.04, 0.16] 的 slot(target_difficult_positions_msb0),还有随机脉冲干扰(9 个 slot 注入 N(0,720) 的 32 点尖峰)。所以关键是保留 LDA 的 margin 作为置信度,而不是只取硬判决。

恢复目标标量:软判决 + ECC 纠错

  1. 对 FIELD-017 做同样的同步 / 分块 / 标准化 / 特征提取;

  2. 用其 bank(0)的模型得到 264 个带符号分数;

  3. 符号作硬判决,|score| 作置信度;

  4. 取置信度最低的 16 个位置,枚举其翻转组合(最多 2^16 = 65536 次);

  5. 每个候选算 d = k mod n,用 d·G 与 public.json 的公钥比对;

  6. 唯一命中的就是私钥。

公钥约束把"信噪比不够、个别位判错"变成了一次可穷举的纠错,也让未知盲化值 r 不再重要——因为 k mod n = d,无论 r 是多少。

解密 flag

key = SHA256("PCTF-NOISY-LADDER-FLAG\x00" || d.to_bytes(32, "big"))
AES-256-GCM(key, nonce=public.nonce, aad="Noisy Ladder / PCTF").decrypt(ct, tag)

exp

from __future__ import annotations
import argparse
import hashlib
import itertools
import json
from pathlib import Path

import numpy as np
from Crypto.Cipher import AES
from cryptography.hazmat.primitives.asymmetric import ec


N_BITS = 264
BLOCKS = 8
BLOCK_LEN = 256
SLOT_LEN = BLOCKS * BLOCK_LEN
SYNC_LEN = 1024
N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141


def crc16_ccitt(data: bytes) -> int:
    crc = 0xFFFF
    for byte in data:
        crc ^= byte << 8
        for _ in range(8):
            crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
    return crc


def bank_for(record: dict) -> int:
    nonce = bytes.fromhex(record["session_nonce"])
    return crc16_ccitt(nonce + b"\x53") & 3


def find_sync(trace: np.ndarray, hint: int, sync: np.ndarray) -> int:
    """在 trigger_hint ± 128 内做互相关,抵消极性/增益,取绝对相关最大处。"""
    left = max(0, hint - 128)
    right = min(trace.size, hint + 128 + sync.size)
    window = trace[left:right].astype(np.float32)
    window -= float(window.mean())
    scores = np.correlate(window, sync, mode="valid")
    return left + int(np.argmax(np.abs(scores)))


PAIR_INDEX = list(itertools.combinations(range(BLOCKS), 2))   # C(8,2) = 28


def extract_features(trace: np.ndarray, sync_start: int) -> np.ndarray:
    """8 块 × 2 通道,块内中心窗均值 -> median/MAD 标准化 -> 28 个块对乘积。"""
    slot_start = sync_start + SYNC_LEN
    slots = trace[:, slot_start : slot_start + N_BITS * SLOT_LEN].reshape(
        2, N_BITS, BLOCKS, BLOCK_LEN
    )
    raw = slots[:, :, :, 66:190].astype(np.float32).mean(axis=3)
    median = np.median(raw, axis=1, keepdims=True)
    mad = np.median(np.abs(raw - median), axis=1, keepdims=True) * 1.4826 + 1.0
    normalized = (raw - median) / mad
    features = []
    for channel in range(2):
        for left, right in PAIR_INDEX:
            features.append(normalized[channel, :, left] * normalized[channel, :, right])
    return np.stack(features, axis=1)      # (N_BITS, 56)


def scalar_to_labels(value: int) -> np.ndarray:
    return np.fromiter(
        ((value >> shift) & 1 for shift in range(N_BITS - 1, -1, -1)),
        dtype=np.int8,
        count=N_BITS,
    )


def labels_to_scalar(labels: np.ndarray) -> int:
    value = 0
    for bit in labels:
        value = (value << 1) | int(bit)
    return value


def fit_bank_model(feature_sets: list[np.ndarray], labels: list[np.ndarray]) -> dict:
    x = np.concatenate(feature_sets, axis=0).astype(np.float64)
    y = np.concatenate(labels, axis=0)
    mean0 = x[y == 0].mean(axis=0)
    mean1 = x[y == 1].mean(axis=0)
    var0 = x[y == 0].var(axis=0)
    var1 = x[y == 1].var(axis=0)
    pooled = 0.5 * (var0 + var1) + 0.08
    effect = np.abs(mean1 - mean0) / np.sqrt(pooled)
    selected = np.argsort(effect)[-6:]                 # 效应量最大的 6 个乘积特征
    center = 0.5 * (mean0[selected] + mean1[selected])
    weights = (mean1[selected] - mean0[selected]) / pooled[selected]
    train_scores = (x[:, selected] - center) @ weights
    class0 = train_scores[y == 0]
    class1 = train_scores[y == 1]
    threshold = 0.5 * (np.median(class0) + np.median(class1))
    orientation = 1.0 if np.median(class1) > np.median(class0) else -1.0
    spread = 0.5 * (np.std(class0) + np.std(class1)) + 1e-6
    accuracy = float(np.mean(((orientation * (train_scores - threshold)) > 0) == y))
    return {
        "selected": selected,
        "center": center,
        "weights": weights,
        "threshold": threshold,
        "orientation": orientation,
        "spread": spread,
        "training_accuracy": accuracy,
        "effect": effect[selected],
    }


def score(model: dict, features: np.ndarray) -> np.ndarray:
    values = (features[:, model["selected"]] - model["center"]) @ model["weights"]
    return model["orientation"] * (values - model["threshold"]) / model["spread"]


def public_matches(private_key: int, expected_x: int, expected_y: int) -> bool:
    if not 1 <= private_key < N:
        return False
    numbers = ec.derive_private_key(private_key, ec.SECP256K1()).public_key().public_numbers()
    return numbers.x == expected_x and numbers.y == expected_y


def decrypt_flag(private_key: int, public: dict) -> str:
    encrypted = public["encrypted_flag"]
    key = hashlib.sha256(
        b"PCTF-NOISY-LADDER-FLAG\x00" + private_key.to_bytes(32, "big")
    ).digest()
    cipher = AES.new(key, AES.MODE_GCM, nonce=bytes.fromhex(encrypted["nonce"]))
    cipher.update(encrypted["aad"].encode("ascii"))
    plaintext = cipher.decrypt_and_verify(
        bytes.fromhex(encrypted["ciphertext"]), bytes.fromhex(encrypted["tag"])
    )
    return plaintext.decode("ascii")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("challenge", type=Path, help="extracted player_files directory")
    parser.add_argument("--uncertain", type=int, default=16)
    args = parser.parse_args()
    root = args.challenge.resolve()

    manifest = json.loads((root / "manifest.json").read_text("utf-8"))
    calibration = json.loads((root / "calibration.json").read_text("utf-8"))
    public = json.loads((root / "public.json").read_text("utf-8"))
    records = {item["capture_id"]: item for item in manifest["captures"]}
    sync = np.fromfile(root / "sync_pattern.f32", dtype="<f4")
    traces = np.memmap(
        root / "captures" / "traces.bin",
        mode="r",
        dtype=manifest["dtype"],
        shape=tuple(manifest["trace_shape"]),
    )

    # 1) 按 bank 收集校准特征与标签
    by_bank_x: dict[int, list[np.ndarray]] = {value: [] for value in range(4)}
    by_bank_y: dict[int, list[np.ndarray]] = {value: [] for value in range(4)}
    for offset, (capture_id, scalar_hex) in enumerate(calibration.items(), 1):
        record = records[capture_id]
        trace = traces[record["index"]]
        sync_start = find_sync(trace[0], record["trigger_hint"], sync)
        features = extract_features(trace, sync_start)
        bank = bank_for(record)
        by_bank_x[bank].append(features)
        by_bank_y[bank].append(scalar_to_labels(int(scalar_hex, 16)))
        if offset % 16 == 0:
            print(f"loaded {offset}/{len(calibration)} calibration traces")

    # 2) 每个 bank 训练一个二阶 LDA
    models = {}
    for bank in range(4):
        models[bank] = fit_bank_model(by_bank_x[bank], by_bank_y[bank])
        print(
            f"bank {bank}: train accuracy={models[bank]['training_accuracy']:.4f}, "
            f"features={models[bank]['selected'].tolist()}"
        )

    # 3) 目标轨迹打分
    target_id = manifest["target_id"]
    target_record = records[target_id]
    target_trace = traces[target_record["index"]]
    target_sync = find_sync(target_trace[0], target_record["trigger_hint"], sync)
    target_features = extract_features(target_trace, target_sync)
    target_scores = score(models[bank_for(target_record)], target_features)
    hard_bits = (target_scores > 0).astype(np.int8)
    uncertain = np.argsort(np.abs(target_scores))[: args.uncertain]
    base_scalar = labels_to_scalar(hard_bits)

    # 4) 枚举低置信位,用公钥闭环
    expected_x = int(public["public_key"]["x"], 16)
    expected_y = int(public["public_key"]["y"], 16)
    print(f"target sync={target_sync}, uncertain positions={uncertain.tolist()}")
    print(f"enumerating {1 << len(uncertain)} candidates")

    flip_masks = [1 << (N_BITS - 1 - int(position)) for position in uncertain]
    for subset in range(1 << len(flip_masks)):
        scalar = base_scalar
        work = subset
        index = 0
        while work:
            if work & 1:
                scalar ^= flip_masks[index]
            work >>= 1
            index += 1
        private_key = scalar % N
        if public_matches(private_key, expected_x, expected_y):
            print(f"private key = {private_key:064x}")
            print(f"flag = {decrypt_flag(private_key, public)}")
            return
    raise SystemExit("key not found; increase --uncertain or inspect alignment/model")


if __name__ == "__main__":
    main()
private key (d) = b2b7b74096681c9542b532732f79aa506c9215db354768bc14f3a210c27d92ee
flag = PCTF{mWSsnahCmlyX5shzdBVgbAybuSmoEncQJ2JD}

题目给定的目标标量是 beb2b7b74096681c9542b5322f79a95efa5a09114d2e55147315ce934ac2012c(264 bit),盲化值 r = 190,可验证 k mod n == d,且 d·G 与 public.json 的公钥完全一致——闭环成立。