| name | redos-anti-pattern |
| description | Security anti-pattern for Regular Expression Denial of Service (CWE-1333). Use when generating or reviewing code that uses regex for input validation, parsing, or pattern matching. Detects catastrophic backtracking patterns with nested quantifiers. |
ReDoS (Regular Expression Denial of Service) Anti-Pattern
Severity: High
Summary
Poorly written regex patterns take extremely long to evaluate malicious input, causing applications to hang and consume 100% CPU from a single request. Caused by catastrophic backtracking in patterns with nested quantifiers ((a+)+) or overlapping alternations.
The Anti-Pattern
The anti-pattern is regex with exponential-time complexity for input validation. Small input length increases cause exponential computation time growth.
BAD Code Example
const VULNERABLE_REGEX = /^(a+)+b$/;
function validateString(input) {
console.time('Regex Execution');
const result = VULNERABLE_REGEX.test(input);
console.timeEnd('Regex Execution');
return result;
}
const malicious_input = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaab";
validateString(malicious_input);
GOOD Code Example
const SAFE_REGEX = /^a+b$/;
function validateStringSafe(input) {
console.time('Regex Execution');
const result = SAFE_REGEX.test(input);
console.timeEnd('Regex Execution');
return result;
}
const MAX_LENGTH = 50;
function validateStringWithLimit(input) {
if (input.length > MAX_LENGTH) {
throw new Error("Input exceeds maximum length.");
}
return VULNERABLE_REGEX.test(input);
}
Detection
- Scan for "evil" regex patterns: The most common red flags are nested quantifiers. Look for patterns like:
- Look for alternations with overlapping patterns:
(a|b)* is safe, but (a|ab)* is not, because ab can be matched in two different ways.
- Use static analysis tools: There are many linters and security scanners that are specifically designed to detect vulnerable regular expressions in your code (e.g.,
safe-regex for Node.js).
- Test with "almost matching" strings: To test a regex, create a long string that matches the repeating part of the pattern but fails at the very end. If the execution time increases dramatically with the length of the string, it is likely vulnerable.
Prevention
Related Security Patterns & Anti-Patterns
References