菜单

Aleer
Aleer
发布于 2026-11-24 / 0 阅读
0
0

CRYPTO - 线性余波

一、题目概览

题目给出一个基于三个 LFSR 的 Geffe 组合器,并在每 64 位输出后追加一层线性混合:

SAMPLE_BITS = 4096
BLOCK_BITS  = 64
ROTATIONS   = (7, 19)
​
LFSR_A = (15, 0x4E71)
LFSR_B = (17, 0x1C44D)
LFSR_C = (19, 0x2CEAF)
​
def geffe_bit(a, b, c):
    return (a & b) ^ ((a ^ 1) & c)
​
def linear_postprocess(value):
    mixed = value
    for shift in ROTATIONS:
        mixed ^= rotl64(value, shift)
    return mixed

输出文件 output.json 给出:

  • 64 个混合后的 64 位字 mixed_blocks(共 4096 位);

  • 加密用的 nonce、flag 密文 flag_ciphertext、认证标签 flag_tag。

密钥由三个 LFSR 的初态直接派生:

material = struct.pack(">HII", states[0], states[1], states[2])
key = hashlib.sha256(b"PCTF-LFSR-2026\x00" + material).digest()

因此目标很明确:从混合后的 4096 位中恢复三个 LFSR 初态。


二、漏洞分析

题目作者试图用线性后处理"改善统计特征",但这恰好暴露了两个致命问题:

  1. 后处理仍然是 GF(2) 上的线性变换。x ^ rol(x,7) ^ rol(x,19) 只做异或和循环位移,没有引入任何非线性,因此存在可逆矩阵,可逐块无损还原 Geffe 原始输出。

  2. Geffe 组合器存在相关性缺陷。其输出以 3/4 的概率等于 LFSR B 的输出,也以 3/4 的概率等于 LFSR C 的输出;而与 LFSR A 的输出完全不相关。这是经典的 correlation attack(相关攻击)。


三、第一步:逆线性后处理,还原 Geffe 原始输出

设 64 位输入为 x,输出为 y:

y = x ^ rol64(x, 7) ^ rol64(x, 19)

由于 rol64(x, s) 的第 i 位是 x[(i-s) mod 64],因此该变换可写成 GF(2) 上的 64×64 矩阵 M:

M[i][j] = 1  当且仅当  j == i  或  j == (i-7) mod 64  或  j == (i-19) mod 64
y = M · x

M 是否可逆取决于多项式 1 + z^7 + z^19 与 z^64 + 1 在 GF(2) 上是否互素。实测高斯消元得到 64 个主元,矩阵满秩,可逆。

对增广矩阵 [M | I] 做 GF(2) 高斯-约旦消元,右侧即得到 M^-1:

def gf2_inverse_matrix():
    rows = []
    for i in range(64):
        r = 1 << i
        for s in (7, 19):
            r ^= 1 << ((i - s) % 64)
        rows.append(r)
​
    n = 64
    aug = [(rows[i] << n) | (1 << i) for i in range(n)]
    pivot_row = 0
    for col in range(n):
        sel = next((rr for rr in range(pivot_row, n)
                    if (aug[rr] >> (n + col)) & 1), None)
        if sel is None:
            continue
        aug[pivot_row], aug[sel] = aug[sel], aug[pivot_row]
        for rr in range(n):
            if rr != pivot_row and ((aug[rr] >> (n + col)) & 1):
                aug[rr] ^= aug[pivot_row]
        pivot_row += 1
    assert pivot_row == n
    return [aug[i] & ((1 << 64) - 1) for i in range(n)]
​
def undo_postprocess(word, inv):
    x = 0
    for i in range(64):
        if (inv[i] & word).bit_count() & 1:
            x |= 1 << i
    return x

用随机向量验证 undo(y) == x 后,对 64 个混合字逐一求逆,并按 bits_to_words 的小端位序展开,就得到 4096 位原始 Geffe 输出 obs[0..4095]。

注意:bits_to_words 中 word |= bit << index,即字内第 i 位对应全局第 offset+i 个输出位,展开时方向不能搞反。


四、第二步:相关攻击恢复 LFSR B、C

把 Geffe 函数展开:

z = a·b ⊕ (1⊕a)·c = c ⊕ a·(b ⊕ c)

于是:

  • 当 a = 1 时,z = b;

  • 当 a = 0 时,z = c。

若 a、b、c 近似均匀独立,则

P(z = b) = P(a=1) + P(a=0)·P(c=b) = 1/2 + 1/2·1/2 = 3/4
P(z = c) = 1/2 + 1/2·1/2 = 3/4
P(z = a) = 1/2       (枚举 8 种输入可得 4 种相等)

因此可以对 B(17 位)和 C(19 位)的所有非零初态穷举:用该初态产生序列,与观测序列逐位比较,计数"相同位减不同位"作为得分。正确初态的期望得分为 4096×(3/4-1/4) = 2048;错误初态期望为 0,标准差约 √4096 = 64。区分度极大。

实际只需前 1024 位即可搜索:正确得分约 +512,错误得分均值 0、标准差 32,即使在 2^19 个候选中取最大值也远低于正确值。

用 NumPy 对整个状态空间做位并行搜索:

def correlation_search(obs, bits, mask, search_bits=1024):
    obs = np.asarray(obs[:search_bits], dtype=np.int8)
    states = np.arange(1, 1 << bits, dtype=np.uint32)
    score = np.zeros(len(states), dtype=np.int16)
    m = np.uint32(mask)
    for i in range(search_bits):
        out = (states & np.uint32(1)).astype(np.int8)
        fb = (np.bitwise_count(states & m) & np.uint32(1)).astype(np.uint32)
        states = (states >> np.uint32(1)) | (fb << np.uint32(bits - 1))
        score += np.where(out == obs[i], 1, -1)
    idx = int(np.argmax(score))
    return idx + 1, int(score[idx])

结果:

LFSR

位数

恢复初态

1024 位得分

4096 位匹配数

B

17

0xd0fb

506

3052 / 4096

C

19

0x53ecf

506

3044 / 4096

理论期望匹配数 3072,实测 3052、3044,符合 3/4 偏置(标准差约 27.7)。


五、第三步:由 B、C 直接反推 LFSR A

由 z = c ⊕ a·(b ⊕ c) 可知:

  • 当 b = c 时,b ⊕ c = 0,故 z = c,与 a 无关;

  • 当 b ≠ c 时,b ⊕ c = 1,故 z ⊕ c = a,输出直接泄露 A 的当前位。

在 4096 个时钟中共有 2096 个 b ≠ c 的位置,这些位置给出 2096 个确定的 A 输出位。此时对 A 的 2^15 个初态穷举,要求在这些位置上逐位完全吻合:

target = [(obs[i] ^ c_seq[i]) if b_seq[i] != c_seq[i] else -1
          for i in range(SAMPLE_BITS)]
st_a, sc_a = correlation_search_a(target, *LFSR_A)   # -1 表示不参与计分

得到:

LFSR A = 0x0630d,2096 个已知位全部匹配(得分 2096)

将三个初态重新送入原生成器,生成的 4096 位 Geffe 序列与 obs 逐位完全一致,确认恢复正确。

说明:不能直接用相关性攻击找 A,因为 P(z=a)=1/2,得分在噪声中。必须先固定 B、C,再利用条件关系把 A 暴露出来。


六、第四步:派生密钥、解密与认证

states = (0x0630d, 0xd0fb, 0x53ecf)
key = hashlib.sha256(b"PCTF-LFSR-2026\x00" + struct.pack(">HII", *states)).digest()

tag = hmac.new(key, nonce + ciphertext, hashlib.sha256).digest()[:16]
# 与 output.json 中的 flag_tag 一致

stream = b"".join(
    hashlib.sha256(key + nonce + struct.pack(">I", i)).digest()
    for i in range((len(ct) + 31) // 32)
)
flag = bytes(x ^ y for x, y in zip(ct, stream))

HMAC 校验通过,解密得到:

PCTF{ou0T2hxuyPDpI0UOOrIXumhIAF6HExQd}

七、完整Exp

import hashlib
import hmac
import json
import struct
import time

import numpy as np

SAMPLE_BITS = 4096
BLOCK_BITS = 64
ROTATIONS = (7, 19)
LFSR_A = (15, 0x4E71)
LFSR_B = (17, 0x1C44D)
LFSR_C = (19, 0x2CEAF)

MASK64 = (1 << 64) - 1


def rotl64(v, s):
    return ((v << s) | (v >> (64 - s))) & MASK64


def gf2_inverse_matrix():
    """Rows are 64-bit ints: bit j set means coefficient on input bit j."""
    rows = []
    for i in range(64):
        r = 1 << i
        for s in ROTATIONS:
            r ^= 1 << ((i - s) % 64)
        rows.append(r)
    n = 64
    aug = [(rows[i] << n) | (1 << i) for i in range(n)]
    pivot_row = 0
    pivots = []
    for col in range(n):
        sel = None
        for rr in range(pivot_row, n):
            if (aug[rr] >> (n + col)) & 1:
                sel = rr
                break
        if sel is None:
            continue
        aug[pivot_row], aug[sel] = aug[sel], aug[pivot_row]
        for rr in range(n):
            if rr != pivot_row and ((aug[rr] >> (n + col)) & 1):
                aug[rr] ^= aug[pivot_row]
        pivots.append(col)
        pivot_row += 1
    assert pivot_row == n, "postprocess map is not invertible"
    inv = [aug[i] & MASK64 for i in range(n)]
    return inv, pivots  # inv[i] gives which output bits feed recovered input bit i


def undo_postprocess(word, inv):
    x = 0
    for i in range(64):
        if (inv[i] & word).bit_count() & 1:
            x |= 1 << i
    return x


def lfsr_bits(state, bits, mask, count):
    out = []
    for _ in range(count):
        out.append(state & 1)
        fb = (state & mask).bit_count() & 1
        state = (state >> 1) | (fb << (bits - 1))
    return out


def correlation_search(obs, bits, mask, search_bits=1024):
    """Vectorized maximum-likelihood search over all non-zero states."""
    obs = np.asarray(obs[:search_bits], dtype=np.int8)
    states = np.arange(1, 1 << bits, dtype=np.uint32)
    score = np.zeros(len(states), dtype=np.int16)
    m = np.uint32(mask)
    for i in range(search_bits):
        out = (states & np.uint32(1)).astype(np.int8)
        fb = (np.bitwise_count(states & m) & np.uint32(1)).astype(np.uint32)
        states = (states >> np.uint32(1)) | (fb << np.uint32(bits - 1))
        score += np.where(out == obs[i], 1, -1)
    idx = int(np.argmax(score))
    return idx + 1, int(score[idx])


def correlation_search_a(target, bits, mask):
    """target[i] = true LFSR-A output bit where b != c, else -1 (skip scoring)."""
    states = np.arange(1, 1 << bits, dtype=np.uint32)
    score = np.zeros(len(states), dtype=np.int16)
    m = np.uint32(mask)
    for t in target:
        out = (states & np.uint32(1)).astype(np.int8)
        fb = (np.bitwise_count(states & m) & np.uint32(1)).astype(np.uint32)
        states = (states >> np.uint32(1)) | (fb << np.uint32(bits - 1))
        if t >= 0:
            score += np.where(out == t, 1, -1)
    idx = int(np.argmax(score))
    return idx + 1, int(score[idx])


def main():
    data = json.load(open(r"E:\WorkBuddy_Home\线性余波_extracted\output.json"))
    inv, _ = gf2_inverse_matrix()

    # sanity check the inverse
    for _ in range(5):
        x = int.from_bytes(hashlib.sha256(str(np.random.random()).encode()).digest()[:8], "little")
        y = x ^ rotl64(x, 7) ^ rotl64(x, 19)
        assert undo_postprocess(y, inv) == x
    print("[+] GF(2) inverse verified")

    raw_words = [undo_postprocess(int(w, 16), inv) for w in data["mixed_blocks"]]
    obs = []
    for w in raw_words:
        for i in range(64):
            obs.append((w >> i) & 1)
    assert len(obs) == SAMPLE_BITS
    print(f"[+] recovered {len(obs)} raw Geffe bits")

    states = []
    for name, (bits, mask) in (("B", LFSR_B), ("C", LFSR_C)):
        t0 = time.time()
        st, sc = correlation_search(obs, bits, mask, search_bits=1024)
        full = lfsr_bits(st, bits, mask, SAMPLE_BITS)
        full_score = sum(1 for a, b in zip(full, obs) if a == b)
        print(f"[+] LFSR {name}: state={st:#0{bits // 4 + 2}x} score1024={sc} score4096={full_score} ({time.time() - t0:.1f}s)")
        states.append(st)

    b_seq = lfsr_bits(states[0], *LFSR_B, SAMPLE_BITS)
    c_seq = lfsr_bits(states[1], *LFSR_C, SAMPLE_BITS)
    # geffe = c ^ a*(b ^ c); whenever b != c the output directly reveals a
    target = [(obs[i] ^ c_seq[i]) if b_seq[i] != c_seq[i] else -1
              for i in range(SAMPLE_BITS)]
    print(f"[+] {sum(t >= 0 for t in target)} positions directly reveal LFSR A")
    t0 = time.time()
    st_a, sc_a = correlation_search_a(target, *LFSR_A)
    print(f"[+] LFSR A: state={st_a:#07x} score={sc_a} ({time.time() - t0:.1f}s)")
    states.insert(0, st_a)

    # regenerate complete Geffe stream and require exact match
    a_seq = lfsr_bits(states[0], *LFSR_A, SAMPLE_BITS)
    geffe = [(a & b) ^ ((a ^ 1) & c) for a, b, c in zip(a_seq, b_seq, c_seq)]
    assert geffe == obs, "recovered states do not reproduce the stream"
    print("[+] LFSR states reproduce all 4096 bits exactly")

    material = struct.pack(">HII", *states)
    key = hashlib.sha256(b"PCTF-LFSR-2026\x00" + material).digest()
    nonce = bytes.fromhex(data["nonce"])
    ct = bytes.fromhex(data["flag_ciphertext"])
    tag = bytes.fromhex(data["flag_tag"])
    calc_tag = hmac.new(key, nonce + ct, hashlib.sha256).digest()[:16]
    print(f"[+] HMAC tag {'OK' if calc_tag == tag else 'MISMATCH'}")

    stream = b""
    for counter in range((len(ct) + 31) // 32):
        stream += hashlib.sha256(key + nonce + struct.pack(">I", counter)).digest()
    flag = bytes(x ^ y for x, y in zip(ct, stream))
    print("[+] FLAG:", flag.decode("ascii", errors="replace"))


if __name__ == "__main__":
    main()


评论