JAVASCRIPT
Safely Validate Input with ReDoS-Resistant Regular Expressions
Protect your web applications from Regular Expression Denial of Service (ReDoS) attacks by crafting efficient and non-vulnerable regex patterns for input validation.
// BAD EXAMPLE: Vulnerable to ReDoS (super-linear time complexity)
// const vulnerableEmailRegex = /^([a-zA-Z0-9]+)*@([a-zA-Z0-9]+)*\.([a-zA-Z]{2,5})+$/;
// GOOD EXAMPLE: ReDoS-resistant email validation
// Uses atomic groups or simpler alternatives, avoids excessive backtracking
const safeEmailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
function validateEmail(email) {
// A common pattern to avoid excessive backtracking is to prefer
// character classes and quantifiers that don't allow overlapping matches
// and avoid nested quantifiers or alternation with similar sub-patterns.
if (!email || typeof email !== 'string') {
return false;
}
return safeEmailRegex.test(email);
}
console.log("Valid email:", validateEmail("[email protected]"));
console.log("Invalid email:", validateEmail("invalid-email"));
// Example of a vulnerable pattern that can be exploited by long strings
// const vulnerableExample = /^(a+)+$/;
// console.time("Vulnerable Regex");
// vulnerableExample.test("aaaaaaaaaaaaaaaaaaaaaaaaaX"); // This would take long
// console.timeEnd("Vulnerable Regex");
// A safer alternative to the vulnerable example
const safeRepeatedA = /^a+$/;
console.log("Safe repeated A:", safeRepeatedA.test("aaaaa"));
How it works: This snippet illustrates how to prevent Regular Expression Denial of Service (ReDoS) attacks in JavaScript. ReDoS occurs when a poorly constructed regex causes excessive backtracking for certain inputs, leading to exponential time complexity and potentially crashing the server. The `safeEmailRegex` demonstrates a more robust pattern, avoiding problematic constructs like nested quantifiers or overlapping alternatives. It's crucial to test regex patterns with various inputs, especially long and complex ones, to ensure they perform efficiently and don't introduce a denial-of-service vulnerability.