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.
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');
}
...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.