logo

Database

Typescript Regex From Untrusted Input

Description

Detects when untrusted user input is used to create regular expressions dynamically using the RegExp constructor. This can lead to Regular Expression Denial of Service (ReDoS) attacks where maliciously crafted input causes excessive CPU consumption.

Weakness:

211 - Asymmetric denial of service - ReDoS

Category: Functionality Abuse

Detection Strategy

    Identifies calls to the RegExp constructor in JavaScript/TypeScript code

    Checks if the RegExp constructor's input parameters originate from untrusted sources like user input

    Reports a vulnerability when untrusted data flows into RegExp creation without proper validation or sanitization

    Considers parameters from HTTP requests, URL parameters, form inputs, and other user-controlled data sources as untrusted

Vulnerable code example

function validateUserInput(userPattern: string, testString: string): boolean {
  // Vulnerable: Creates RegExp directly from user input without validation
  const pattern = new RegExp(userPattern);
  
  // Testing against pattern can cause ReDOS if userPattern is malicious
  return pattern.test(testString);
}
...

✅ Secure code example

import safeRegex from 'safe-regex';

function validateUserInput(userPattern: string, testString: string): boolean {
  // Validate pattern complexity before creating RegExp
  if (!safeRegex(userPattern)) {
    throw new Error('Invalid regex pattern: too complex');
  }
  ...