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.
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...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.