Peng.ly Security

Regular expression denial of service medium

Quadratic-time ReDoS in toNumber() for decimals with a long internal zero-run

A number with a long run of zeros in the middle takes seconds to parse, enough for one small XML body to freeze a Node app using fast-xml-parser.

strnum
Affected <= 2.4.1 Patched 2.4.2

Published · 2 min read

Summary

toNumber() takes O(n^2) time on a decimal string that has a long run of zeros somewhere before a later non-zero digit, for example "0." + "0".repeat(n) + "1". The cost is a single line in trimZeros():

numStr = numStr.replace(/0+$/, "");

When numStr doesn't end in 0 (here it ends in 1), the greedy /0+$/ matches a maximal run of zeros, tests the $ anchor, fails, backtracks, and retries from the next zero. That's one scan per zero, so n zeros cost O(n^2). trimZeros() runs unconditionally after the number regex matches, so the leadingZeros option doesn't gate it, and the sign doesn't matter.

Proof of concept

import toNumber from "strnum";
for (const n of [8000, 16000, 32000, 64000]) {
  const s = "0." + "0".repeat(n) + "1";
  const t = process.hrtime.bigint();
  toNumber(s);
  console.log(s.length, Number(process.hrtime.bigint() - t) / 1e6 + "ms");
}
// 8003  56ms | 16003 217ms | 32003 919ms | 64003 3597ms   (~4x per 2x = quadratic)

I instrumented the module to be sure: for the 64k input, trimZeros accounts for 3877ms of the 3878ms total. Number() and the regexes are all sub-millisecond.

The same input reaches this through fast-xml-parser on its default options, since it calls toNumber on every tag value:

import { XMLParser } from "fast-xml-parser";
new XMLParser().parse("<r>0." + "0".repeat(64000) + "1</r>"); // ~3.5s, event loop blocked
// a benign 64KB number in the same position parses in ~4ms

Impact

Anything that runs toNumber() on attacker-controlled strings can be stalled by one small input. Through fast-xml-parser (default config) a single ~100KB request body blocks the Node event loop for several seconds, and it scales quadratically from there, so it's a cheap unauthenticated denial of service. I'd suggest high severity, but I'll leave the CVSS vector to you.

A regex-free trailing-zero trim keeps the same output and removes the blowup:

let end = numStr.length;
while (end > 0 && numStr.charCodeAt(end - 1) === 48) end--;
numStr = numStr.slice(0, end);

That takes the 64k case from ~3.6s to under a millisecond, with identical results across the inputs I tried.

Caveat

I've reproduced the quadratic timing on 1.1.2, 2.0.0, 2.3.0 and 2.4.1, and the line is present back to 1.0.5, but I've not tested every release in between. I haven't checked whether any downstream cap (a max input length somewhere upstream) already limits this in a given deployment.