Skip to main content
MediumCodeOWASP A03:2021CWE-89

How to fix: MongoDB $regex from user input

Building a MongoDB query with { field: { $regex: userInput } } or new RegExp(userInput) lets attackers supply patterns that match every document (.*) or trigger catastrophic backtracking, leaking data or causing DoS.

Why it matters

Wildcard or pathological regex patterns expose every document or stall the server.

The `code-sqli-mongodb-regex` check verifies that the server does not expose the `sqli-mongodb-regex` weakness in the code category. The detection runs against the response headers, body, or auxiliary probes (DNS, TLS, async fetch) as appropriate.

How to fix it

  1. 1Escape regex metacharacters before compiling user input with RegExp.
  2. 2Anchor patterns with ^ and bound their length; reject unbounded inputs.
  3. 3Prefer $text indexes over $regex for user-driven search.

Code examples

Escape or validate regex patterns from user input

TypeScript
// BAD: user controls the regex pattern, ReDoS possible
collection.find({ email: new RegExp(userInput) });

// GOOD: escape the user input before using as regex
function escapeRegex(s: string) { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
collection.find({ email: new RegExp("^" + escapeRegex(userInput) + "$") });
// Or use a plain equality match instead of regex

References

Detected automatically by VulnRadar. The check id is code-sqli-mongodb-regex, stable across every scan so you can filter or diff on it.

See every code check

Questions

How severe is MongoDB $regex from user input?
VulnRadar rates this medium severity in the code category. The severity is fixed per check, not scored per site, so the same finding is the same severity on every scan.
Does VulnRadar check for this automatically?
Yes. It runs as part of every scan under the check id code-sqli-mongodb-regex, which stays the same between runs so you can filter, diff, or gate CI on it.
Which standards does MongoDB $regex from user input map to?
It maps to CWE-89. In the OWASP Top 10 it falls under A03:2021.

Missing a check?

The detection set is open. If you know a misconfiguration this does not catch, propose it: the issue template asks for the threat model, how to detect it, the false-positive risk, and a test fixture, which is the same thing a maintainer would have to work out anyway.

Propose a checkHow a check is built

Scan your own site for mongodb $regex from user input

VulnRadar runs this check and hundreds more against a URL in seconds. No agent to install, just paste a URL.

Or scan this site as a demoRead the docs

How to fix: MongoDB $regex from user input | VulnRadar