
Challenge: Common Core
⚠️ この記事を読む前に
この記事は教育目的で作成された「暗号技術の学習用記事」です。技術の仕組みを学び、セキュリティへの理解を深めるために活用してください。
問題概要
ある暗号化サービスが、最新のセキュリティ対策を採用したと謳っています。
彼らの主張は「全ての通信で共通の強固なパラメータを使っているため、管理が完璧である」というものです。
しかし、セキュリティエンジニアであるあなたは、その設計に致命的な欠陥があることに気づきました。
提供されたソースコードを解析し、隠されたフラグ `COMMON_CORE{...}` を取得してください。
配布ファイル (`server.py`)
#!/usr/bin/env python3
import time
from Crypto.Util.number import bytes_to_long, long_to_bytes
import random
# Common Core Challenge Server
FLAG = b'COMMON_CORE{sH4r3d_f4ct0rs_4r3_d4ng3r0us}'
FLAG_INT = bytes_to_long(FLAG)
# A constant factor that makes moduli share a common divisor
COMMON_FACTOR = 1337
class VulnerableOracle:
def __init__(self):
self.nonce = int(time.time())
self.counter = 0
self.k = COMMON_FACTOR
def get_key(self):
# The core vulnerability:
# The key is derived directly from FLAG modulo a composite number
# modulus = (nonce + counter) * COMMON_FACTOR
# This means all moduli share COMMON_FACTOR
modulus = (self.nonce + self.counter) * self.k
self.counter += 1
# Leaking the key residue directly for educational purposes
return FLAG_INT % modulus
def encrypt(self, msg: str):
key = self.get_key()
msg_int = bytes_to_long(msg.encode())
# Stream cipher encryption (XOR)
encrypted_int = msg_int ^ key
return long_to_bytes(encrypted_int).hex()
def main():
oracle = VulnerableOracle()
print(f"--- Practice Oracle Running ---")
print(f"Nonce (simulated time): {oracle.nonce}")
print(f"Common Factor (k): {oracle.k}")
print("-------------------------------")
while True:
try:
msg = input("Enter message to encrypt: ")
encrypted = oracle.encrypt(msg)
print(f"Encrypted: {encrypted}")
except KeyboardInterrupt:
break
except Exception as e:
print(f"Error: {e}")
break
if __name__ == "__main__":
main()Writeup (解法)
脆弱性の特定
サーバーのコードを見ると、鍵生成の際に使われる法(modulus)が以下のようになっています。
`modulus = (nonce + counter) * COMMON_FACTOR`
ここで `COMMON_FACTOR` は定数 `1337` です。
つまり、全ての法が `1337` を共通の約数として持っています。
これは、通常の中国剰余定理(CRT)が適用できない条件ですが、逆に言えば Generalised CRT(一般化中国剰余定理) の絶好の標的となります。
攻撃コード (`solve.py`)
以下のスクリプトを実行することで、数学的にフラグを一意に特定できます。
#!/usr/bin/env python3
# ==============================================================================
# Common Core - 解説付き Exploit
# ==============================================================================
# このスクリプトは、"Generalized Chinese Remainder Theorem" (一般化CRT) を用いて
# 致命的な脆弱性を持つサーバーからFlagを奪取する方法を解説します。
#
# 実行方法:
# python3 solve.py
# ------------------------------------------------------------------------------
import time
from Crypto.Util.number import long_to_bytes
from math import gcd
from functools import reduce
import sys
import server
# ==============================================================================
# [解説] 数学ユーティリティ
# ==============================================================================
def generalized_crt(moduli, residues):
"""
【一般化中国剰余定理 (Generalized CRT)】
互いに素とは限らない法 (moduli) の連立合同方程式を解く関数です。
"""
if not moduli:
return 0, 1
M = moduli[0]
A = residues[0]
for i in range(1, len(moduli)):
m = moduli[i]
a = residues[i]
g = gcd(M, m)
if (a - A) % g != 0:
raise ValueError(f"【エラー】解なし: {A} mod {M} と {a} mod {m} は矛盾しています。")
target = (a - A) // g
m_prime = m // g
M_prime = M // g
inv = pow(M_prime, -1, m_prime)
k = (target * inv) % m_prime
new_mod = M * m_prime
A = (A + k * M) % new_mod
M = new_mod
return A, M
# ==============================================================================
# [解説] メイン攻撃ロジック
# ==============================================================================
def solve():
print("[*] 攻撃シミュレーションを開始します...")
oracle = server.VulnerableOracle()
print(f"[*] ターゲット情報:")
print(f" Nonce (サーバー時刻): {oracle.nonce}")
print(f" 共通因子 k (Common Factor): {oracle.k}")
# STEP 1: データの収集
samples = []
num_samples = 20
k = oracle.k
nonce = oracle.nonce
print(f"[*] STEP 1: {num_samples} 個のサンプル(余り)を収集中...")
for i in range(num_samples):
# 空文字を送って暗号鍵(余り)を直接取得
enc_hex = oracle.encrypt("")
leaked_key = int(enc_hex, 16)
samples.append(leaked_key)
# STEP 2: 変数変換 (FLAG = Y * k + R)
print(f"[*] STEP 2: 変数変換 (FLAG = Y * k + R)")
R = samples[0] % k
# 一貫性チェック
for i, s in enumerate(samples):
if s % k != R:
print("[-] エラー: サンプル間で矛盾があります!")
return
# 新しい合同式を作成
y_residues = []
y_moduli = []
for i in range(num_samples):
mod_i = nonce + i
res_i = (samples[i] - R) // k
y_moduli.append(mod_i)
y_residues.append(res_i)
# STEP 3: 一般化CRT で Y を解く
print(f"[*] STEP 3: 一般化CRTを実行して Y を特定...")
try:
Y, LCM = generalized_crt(y_moduli, y_residues)
print(f"[+] Y が見つかりました: {Y}")
except ValueError as e:
print(f"[-] CRT 失敗: {e}")
return
# STEP 4: フラグの復元
print(f"[*] STEP 4: フラグの計算 (FLAG = Y * k + R)")
flag_int = Y * k + R
try:
flag_bytes = long_to_bytes(flag_int)
print(f"\n[SUCCESS] フラグ奪取成功!")
print(f"Flag: {flag_bytes.decode()}")
except:
print(f"[-] 変換失敗: {flag_int}")
if __name__ == "__main__":
solve()