logo

Database

Javascript Regex From Untrusted Input

Description

Detects JavaScript Regular Expression injection vulnerabilities where untrusted user input is used to construct RegExp objects. This can lead to Regular Expression Denial of Service (ReDoS) attacks where maliciously crafted input causes excessive CPU consumption and application unresponsiveness.

Weakness:

211 - Asymmetric denial of service - ReDoS

Category: Functionality Abuse

Detection Strategy

    Identifies JavaScript code that creates new RegExp objects using the RegExp constructor

    Checks if the RegExp constructor arguments contain or are derived from user-controlled input sources

    Reports a vulnerability when user input flows into RegExp object creation without proper validation or sanitization

    Example of vulnerable code: new RegExp(userInput) where userInput comes from an HTTP request or other untrusted source

Vulnerable code example

function validateUserInput(userPattern) {
  const regex = RegExp(userPattern);  // Vulnerable: Creates RegExp from unsanitized user input
  return regex.test('some text');
}

✅ Secure code example

const escapeStringRegexp = require('escape-string-regexp');
const safe = require('safe-regex');

function validateUserInput(userPattern) {
  const escapedPattern = escapeStringRegexp(userPattern); // Sanitize regex special chars
  const regex = RegExp(escapedPattern);
  
  // Validate pattern is not vulnerable to catastrophic backtracking...