All posts
Concept ~11 min read

Prototype pollution: the fuse and the gadget

Polluting Object.prototype does nothing on its own. It becomes a vulnerability only when some other code reads a property it never set (a gadget), and that split decides whether you get XSS, RCE, auth bypass, DoS, or nothing, and how to fix it.

Prototype pollution reports split opinion more than most JavaScript bug classes. One person sees a library that lets ?__proto__[isAdmin]=1 put isAdmin on every object in the process and calls it critical. Another tries to exploit it, gets nothing, and calls it informational. Each of them is looking at half the bug.

Prototype pollution comes in two parts. The fuse is the code that writes to Object.prototype. The gadget is the code that later reads a property it never set and does something dangerous with it. A fuse with nothing to light does nothing. A gadget with no fuse is ordinary code. You need both before anything happens, and seeing the bug as two parts tells you how to rate a report, how to hunt for one, and how to fix it.

A little theory: why one write reaches every object

Almost every object in JavaScript has a prototype, and most of them share the same one: Object.prototype. When you read obj.foo and obj has no own property foo, the engine walks up the chain and returns Object.prototype.foo if it exists. That fallback is how ({}).toString works.

Two property names let you reach that shared object through normal property access:

  • obj.__proto__ is an accessor on Object.prototype that returns the object’s prototype. For a plain object, obj.__proto__ is Object.prototype.
  • obj.constructor.prototype gets there too: ({}).constructor is Object, and Object.prototype is the prototype.

So if code ever runs target[a][b] = value with a and b chosen by an attacker, setting a = "__proto__" writes b onto the prototype of every plain object in the realm. In Node.js that means every request handled by that process from then on, until it restarts.

Where the fuse comes from

Pollution almost always comes from code that walks a path of keys chosen by the input. There are three common shapes.

Recursive merge / deep extend / defaults. A function that copies source into target, recursing into nested objects:

A naive deep merge (a typical fuse)JavaScript
const isObject = (v) => v !== null && typeof v === "object";

function merge(target, source) {
  for (const key in source) {
    if (isObject(source[key])) {
      if (!isObject(target[key])) target[key] = {};
      merge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

merge({}, JSON.parse('{"__proto__": {"polluted": true}}'));
({}).polluted; // true

JSON.parse creates __proto__ as an ordinary own key, so for...in hands it to the loop. Then target["__proto__"] resolves through the accessor to Object.prototype, and the recursion writes into it.

Set-by-path. Helpers like set(obj, "a.b.c", value) split a string into keys and walk them, creating objects as they go. If the path is "__proto__.polluted" or "constructor.prototype.polluted", the walk ends up on the prototype. lodash.set is the best-known example, but any setPath / unflatten / objectPath.set helper that accepts an attacker-controlled key string has the same shape.

Query-string and body parsers that expand keys. Parsers that turn a[b][c]=1 into {a:{b:{c:1}}} are set-by-path helpers fed straight from the request. The bracket syntax (qs, the classic Express body parser) and the dotted syntax (--a.b=1 in CLI parsers, some form libraries) both split a flat key into a path and walk it, so ?__proto__[polluted]=1 or a __proto__.polluted form field reaches the prototype without any merge in your own code. Whether nested expansion is enabled at all is a per-parser setting worth checking.

Every fuse above can be driven by two key names, and a fix that blocks one often misses the other:

  • __proto__ names the prototype accessor directly. It is the obvious payload, and the one most filters remember.
  • constructor.prototype takes two steps: obj.constructor is the Object function, whose .prototype is the same shared object. This path reaches Object.prototype without ever writing the string __proto__. The lodash and minimist histories (below) both turned on this: the first fix blocked __proto__, and a constructor payload walked past it.

The public track record

The bug class got its name from a run of findings in widely used utility libraries:

  • lodash, CVE-2019-10744. In versions below 4.17.12, defaultsDeep could be made to modify Object.prototype with a constructor payload rather than __proto__, which shows that a filter on one key name is not enough.
  • lodash, CVE-2020-8203. A later prototype pollution report against zipObjectDeep, a set-by-path helper with the same root cause in a different function.
  • jQuery, CVE-2019-11358. jQuery.extend(true, {}, untrusted) (the deep-extend form) would copy an attacker’s __proto__ key into Object.prototype. The fix was released in jQuery 3.4.0.
  • minimist, CVE-2020-7598 and CVE-2021-44906. The argument parser behind a large share of Node CLIs could be made to set keys on Object.prototype with __proto__ or constructor payloads in crafted arguments. The second CVE covered a path the first fix (1.2.2) missed, so the first fix was incomplete.
  • qs, CVE-2022-24999. The query-string parser used by Express (before 4.17.3) accepted a __proto__ key in the bracket syntax. Here the gadget was built in: the pollution made the process hang, so an unauthenticated query string was a denial of service on its own, with no second component needed. Sometimes the gadget is the runtime itself.

Look at how these advisories were rated: mostly as library bugs with conditional impact, because for most of them the dangerous effect waits on a gadget elsewhere. That is the right call, except where (as in qs) the pollution immediately breaks a property the runtime itself reads.

Why pollution alone does nothing

After Object.prototype.polluted = true, nothing has changed except that ({}).polluted now reads true. No code runs and no file is touched. For it to matter, some code later in the process has to:

  1. read a property from an object that does not have that property as its own, and
  2. do something security-relevant with what it gets back.

That code is the gadget. It is usually not buggy taken alone. It assumes, reasonably, that a property it never set is undefined.

What a gadget looks like

The pattern to look for is code that reads an optional property from an object built as {}. Some typical families:

Options objects with defaults by omission. In code like this, any key the caller left out falls through to the prototype:

An options bag is a gadget surfaceJavaScript
function render(view, options = {}) {
  const opts = { cache: true, ...options };
  if (opts.allowUnsafeHtml) {         // never set by the caller...
    return rawHtml(view);             // ...but now `true` for everyone
  }
  return escaped(view);
}

Authorization by absence. if (user.isAdmin) or if (!req.session.restricted) on an object that never had the flag set. Polluting isAdmin grants it to every user object that lacks an own property.

Template engines resolving names through the prototype chain. A template asks for {{ something }} or compiles with an options object. If the engine looks names up with ordinary property access instead of an own-property check, a polluted key can appear as a variable, a helper, or a compile option. Compile options are the dangerous ones, because some of them change the generated code, so any engine that takes an options object is worth checking.

Process-spawning options. child_process functions take an options object with fields such as shell, env, cwd and argv0. If a library builds that object as {} and the field it reads is missing, a polluted field changes how the child process starts, which turns a harmless-looking spawn("git", [...]) into command execution. Polluting shell makes the arguments run through /bin/sh; polluting env can inject NODE_OPTIONS (e.g. --require a file, or --inspect) so the next spawned Node process loads attacker-chosen code before it runs anything else. Exposure depends on the runtime version and on how the library builds its options, so test it on the real version.

HTTP client options. fetch-style and request-library options (headers, agent, proxy, redirect settings, base URLs) are often assembled by merging defaults into {}. A polluted header or proxy setting applies to every outbound request the process makes.

A catalogue of the gadget families worth checking, and what each one turns into:

Gadget category Where it lives Polluted key reaches Typical impact
Authorization-by-absence Server isAdmin, role, restricted on user/session objects Privilege escalation, auth bypass
Options bag with defaults Both any opts.* the caller omitted Depends on the option, from a feature toggle to the ones below
Template compile options Server an option read off the prototype when compiling Can change generated code, RCE in the worst case
Process-spawn options Server shell, env, cwd, argv0, NODE_OPTIONS Command / code execution
Outbound HTTP options Server headers, proxy, agent, base URL Request tampering, SSRF-adjacent redirection
Hot / commonly-read property Both a key the runtime or framework reads constantly Denial of service
DOM sink config Client sanitizer allow-lists, innerHTML/src options, widget config DOM XSS

The high-impact cases are RCE (spawn and template-compile gadgets) and DOM XSS (client-side sink gadgets); the quieter, common ones are auth-by-absence and DoS. All of them share one precondition: an object built as {} whose missing key is read without an own-property check.

Severity: a fuse needs a gadget, a gadget needs a fuse

This is where the two camps from the introduction meet:

  • A fuse with no reachable gadget is a real bug that is latent. It deserves a fix, and it is usually rated moderate because its impact depends on what else is loaded. Do not call it remote code execution until you have shown a gadget firing in a realistic setup.
  • A gadget with no fuse is not a vulnerability. Reading an unset property is how JavaScript normally works. Reporting “this library reads options.shell from the prototype” with no way to pollute it is a hardening note at best.
  • A fuse and a gadget in the same process, reachable from input, is the full bug. Its severity is the gadget’s impact (XSS, auth bypass, RCE) limited by how reachable the fuse is (unauthenticated query string versus an admin-only import).

When you write the report, show the whole chain on a test install: the request that pollutes, then the ordinary request that triggers the gadget, then the effect. If you only have half of it, say which half.

Server side vs client side

Server-side (Node.js) pollution affects the whole process. One request pollutes and every later request sees it, including other users’ requests. That makes gadgets in shared code (template rendering, spawning, outbound HTTP) valuable to an attacker. It also makes the bug noisy: pollution often breaks unrelated code, and crashes give away exploitation attempts.

Denial of service by polluting a hot property. Even with no classic gadget, pollution is a cheap availability attack. Write a value of the wrong type onto a property the runtime or a hot code path reads on every request (a then that confuses promise resolution, a key the router or serializer touches constantly, or, as in qs CVE-2022-24999, a property whose pollution sends the parser into a loop) and every subsequent request throws or hangs until the process restarts. That is prototype pollution acting as an algorithmic or state-based DoS: one small input breaks the process until it restarts.

Client-side pollution lives in one browser tab. The usual fuse is a URL parser reading location.search or location.hash into nested objects. The gadgets live in the libraries that write to the DOM: a sanitizer whose allow-list option is read off the prototype (so a polluted key re-enables a tag the page meant to strip), a templating or widget library that reads an HTML-insertion flag or a src from an options object, or a snippet that injects a script whose URL it pulled from config. The chain: a crafted link pollutes a key the sink library reads, the page runs as normal, and the sink emits attacker markup. The impact is DOM XSS in the victim’s session, delivered with a link and with no server bug required. (For how the sink’s context decides what executes, see XSS is an output-context bug.)

How to find it in your own code

Hunt for each half separately, then try to join them.

Fuses:

  • grep for recursive merge, extend, assign, defaults, deepCopy, set(, setPath, unflatten, and any loop that does obj = obj[key] over keys that came from input;
  • check which parser handles your query string and request body, and whether nested syntax is turned on;
  • test directly: send {"__proto__":{"pp_probe":1}}, {"constructor":{"prototype":{"pp_probe":1}}} and ?__proto__[pp_probe]=1 to every endpoint that accepts structured input, then check ({}).pp_probe in a debugger or a test harness.

Gadgets:

  • look for options objects built as {} or by spreading defaults, where the consumer reads optional keys;
  • in Node, check every call to spawn, exec, fork and every outbound HTTP client, and find out where its options object comes from;
  • in the browser, look at config objects passed to sanitizers, renderers and anything that writes to the DOM;
  • prototype pollution fuzzers and dynamic taint tools can find gadgets automatically by polluting candidate keys and watching which sinks behave differently.

The fix

Fix both halves. Defence in depth matters here because you rarely control every dependency.

Stop the fuse:

  • reject the dangerous keys __proto__, constructor and prototype in any merge or set-by-path helper (all three, since lodash’s history shows that blocking only __proto__ is not enough, and a fix that covers one spelling of a bug tends to get bypassed by the next);
  • build containers for untrusted keys with Object.create(null), so there is no prototype to reach, or use a Map, whose entries are not properties and are never read through the prototype chain;
  • strip the dangerous keys at the parse boundary with a JSON.parse reviver that drops __proto__ and constructor before they reach any merge or set-by-path call;
  • validate request bodies against a strict schema that rejects unknown keys, so the payload never reaches the merge in the first place.

Defuse the gadgets:

  • read optional settings with Object.hasOwn(opts, "shell") (or Object.prototype.hasOwnProperty.call), not a plain truthiness check;
  • create options and defaults objects with a null prototype, or copy only a known list of keys out of them.

Harden the whole process:

  • Object.freeze(Object.prototype) at startup makes pollution fail silently (or throw in strict mode). Test it first, because some older libraries extend built-in prototypes on purpose;
  • Node’s --disable-proto=throw (or =delete) removes the __proto__ accessor. That kills the most common path, but not constructor.prototype, so combine it with key filtering rather than relying on it alone.

Takeaway

Prototype pollution only becomes a vulnerability when a polluting write meets code that trusts a property it never set.

Rate it by the whole chain you can show, and fix both halves: block the polluting keys and read options with own-property checks.