Course contentsShow
← Security
Lesson 1051 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

JavaScript Prototype Chain Security

Learn prototype pollution vulnerabilities, how attackers manipulate Object.prototype, and defense techniques.

JavaScript Prototype Chain Security

What you'll learn: How attackers exploit JavaScript's prototype chain through pollution attacks and how to defend your applications against them.

The Prototype Chain Vulnerability

JavaScript objects inherit properties from their prototypes—a chain that eventually reaches Object.prototype, the root ancestor of nearly all objects. Prototype pollution occurs when attackers modify properties on Object.prototype or other prototypes, affecting all objects that inherit from them.

Think of it like poisoning a water supply upstream—every consumer downstream gets contaminated water without knowing it.

How Prototype Pollution Works

Attackers target functions that merge or copy properties without validation, especially those handling user input:

// Vulnerable code
function merge(target, source) {
  for (let key in source) {
    target[key] = source[key];  // Dangerous!
  }
}

// Attacker's malicious input
const malicious = JSON.parse('{"__proto__": {"isAdmin": true}}');
merge({}, malicious);

// Now ALL objects are poisoned
const newUser = {};
console.log(newUser.isAdmin);  // true (!!)

The attacker used __proto__ to climb up to Object.prototype, injecting properties into every object in your application.

Defense Techniques

  1. Use Object.create(null) for objects that won't need prototype inheritance
  2. Validate property names before assignment—block __proto__, constructor, and prototype
  3. Use Object.freeze(Object.prototype) to prevent modifications (if feasible)
  4. Prefer Object.assign() with safeguards or libraries like lodash with merge depth limits
  5. Validate JSON schemas before parsing untrusted data
// Safer merge
function safeMerge(target, source) {
  for (let key in source) {
    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
      continue;  // Skip dangerous keys
    }
    target[key] = source[key];
  }
}

Key Takeaway: Prototype pollution lets attackers modify inherited properties globally by manipulating the prototype chain—always validate and sanitize property names from untrusted sources, and consider freezing critical prototypes.