Skip to curriculum
Jump to the editor

21.14. Block prototype pollution in nested writes

Medium
Topics
25–40 min

A settings endpoint receives a JSON body and merges it into the stored settings. It looks harmless, until someone sends {"__proto__": {"isAdmin": true}}. JSON.parse turns that into an object with an own key named __proto__, a naive deep merge walks into target["__proto__"], which is Object.prototype, and from then on every object in the program has isAdmin. This is prototype pollution, and nested writes (merge, set by path, unflatten) are where it happens. The same attack works through constructor.prototype, and through any inherited value the merge walks into.

Write safeMerge(target, patch) in safe-merge.js. It deep-merges an untrusted patch into target in place, refuses the keys that lead to prototypes, and returns the dotted paths of every key it refused, so the caller can log the attempt.

Signature

JAVASCRIPT
function safeMerge(target, patch) // returns an array of refused paths
  • target: the object to change (an object, possibly with a null prototype).
  • patch: a plain object, usually from JSON.parse. It is not changed.
  • Returns an array of strings: the path of each refused key, such as "settings.__proto__", in the order they were met.

Requirements

  1. When the patch has a plain object under a key and the target owns a plain object under the same key, the patch object is merged into the target's object, in place, at any depth.
  2. Otherwise the patch value is written to the target. Plain objects and arrays from the patch are copied through the same filter, never shared; other values (strings, numbers, null, false) are written as they are.
  3. The keys __proto__, constructor and prototype are refused at every depth, including inside objects in arrays, and even when the target already owns such a key. A refused key is not written; its path is added to the returned array.
  4. Paths join keys with .; array items use their index ("list.0.__proto__").
  5. Only values the target owns are merged into. An inherited value (such as toString) counts as missing, so the target gets its own property and the built-in is never touched.
  6. Only own keys of the patch are read: keys the patch inherits are ignored.
  7. A plain object is one whose prototype is Object.prototype or null. Only a plain object that is not protected (rule 10) is merged into: a Date, an array, a class instance or a protected object in the target is replaced by a filtered copy, not merged into.
  8. Keys such as hasOwnProperty are ordinary data, on either side, and a null-prototype target works.
  9. A patch that is not a plain object, or a target that is not an object or function, throws a TypeError. A protected target (rule 10) throws a TypeError. A patch that contains itself throws a TypeError.
  10. A protected object is never written to. The protected objects are: the global object; the standard globals Object, Function, Array, String, Number, Boolean, Symbol, BigInt, Date, RegExp, the error classes (Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError, AggregateError and SuppressedError, each where the browser has it), Map, Set, WeakMap, WeakSet, WeakRef, FinalizationRegistry, Promise, Proxy, Reflect, JSON, Math, Intl, Atomics, Iterator, ArrayBuffer, SharedArrayBuffer, DataView and the typed arrays (Int8Array through BigUint64Array, Float16Array included where the browser has it); the prototype of each of them; every object or function stored as a data property directly on one of those (such as Object.prototype.toString or Array.prototype.push); and any object that owns a constructor function whose prototype is that object (the prototype of a class). Owning a key does not make the object under it safe: in { alias: Object.prototype } the key is the target's own, but the object is shared by the whole program.

Examples

JAVASCRIPT
const settings = { theme: { color: "blue" }, lang: "en" };
safeMerge(settings, JSON.parse('{"theme": {"size": 14}}')); // []
// settings is { theme: { color: "blue", size: 14 }, lang: "en" }
JAVASCRIPT
const settings = {};
safeMerge(settings, JSON.parse('{"__proto__": {"isAdmin": true}, "lang": "fr"}'));
// ["__proto__"]
settings.lang;  // "fr"
({}).isAdmin;   // undefined
JAVASCRIPT
safeMerge({}, JSON.parse('{"profile": {"constructor": {"prototype": {"isAdmin": true}}}}'));
// ["profile.constructor"]
JAVASCRIPT
const settings = { alias: Object.prototype };
safeMerge(settings, JSON.parse('{"alias": {"isAdmin": true}}')); // []
settings.alias; // { isAdmin: true }, a new object
({}).isAdmin;   // undefined
safeMerge(Object.prototype, {}); // throws a TypeError

Environment

  • Plain JavaScript in a browser page; the tests call the global safeMerge from safe-merge.js, and check the built-in prototypes after every test.
  • Only string keys are merged (Object.keys). Getters, setters and symbol keys are out of scope.
  • Changes made before a TypeError for a cyclic patch may remain.

Hints

  1. On a fresh {}, what are target["__proto__"], target.constructor and target.constructor.prototype?
  2. Why is checking the key name not enough on its own? Think of {"toString": {"polluted": 1}}, and of a target that owns alias: Object.prototype.
  3. If a new key gets a patch object assigned directly, what happens to the dangerous keys nested inside it?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…