What is prototype pollution and how it can be exploited?

Prototype pollution is a type of vulnerability that occurs when an attacker is able to modify the prototype of an object in JavaScript. This can occur when user-controlled input is used to set properties on an object’s prototype, allowing an attacker to add, modify, or delete properties on the object’s prototype.

For example, consider the following JavaScript code:

function User(name, age) {
    this.name = name;
    this.age = age;
}

const user = new User("John", 25);
console.log(user.name); // "John"
console.log(user.age); // 25

In the above code, a User constructor function is defined, which takes a name and age as arguments. An instance of the User object is then created, and the name and age properties are set to “John” and 25, respectively.

An attacker could exploit prototype pollution by modifying the User object’s prototype:

User.prototype.password = "mypassword";
console.log(user.password); // "mypassword"

In the above code, the attacker is able to add a new property called password to the User object’s prototype, and set its value to “mypassword”. Now, this property is accessible on all instances of the User object.

The vulnerability can be exploited in various ways, for example an attacker can use it for:

  1. Hijacking an object’s methods to execute malicious code
  2. Bypassing access controls
  3. Leaking sensitive data
  4. Creating a denial of service (DoS) attack
  5. Exfiltrating data

To prevent prototype pollution, it is important to validate and sanitize user input before using it to set properties on an object’s prototype. Additionally, it is also a good practice to use libraries that have been specifically designed to prevent prototype pollution, such as the Object.freeze() method in JavaScript, which makes an object immutable and prevents properties from being added, modified, or deleted.

In summary, Prototype pollution is a type of vulnerability that occurs when an attacker is able to modify the prototype of an object in JavaScript, it can be exploited in various ways, to prevent it, it is important to validate and sanitize user input before using it to set properties on an object’s prototype and use libraries that have been specifically designed to prevent prototype pollution.