HIGH regex dosexpress

Regex Dos in Express

How Regex Dos Manifests in Express

Regular expression denial of service (ReDoS) attacks exploit catastrophic backtracking in regex patterns, causing exponential time complexity that can freeze or crash your Node.js server. In Express applications, this vulnerability commonly appears in route parameter validation, input sanitization middleware, and custom validation logic.

The most dangerous patterns involve nested quantifiers like (a+)+ or overlapping alternatives that create exponential backtracking. When an attacker crafts input matching these patterns, the regex engine can spend seconds or minutes processing a single request instead of milliseconds.

Consider this Express route that validates email addresses:

app.post('/api/register', (req, res) => {
  const emailRegex = /^([a-z]+)+([a-z0-9._%+-]+)@[a-z0-9.-]+\.[a-z]{2,}$/i;
  if (!emailRegex.test(req.body.email)) {
    return res.status(400).json({ error: 'Invalid email' });
  }
  // Process registration
});

This seemingly innocent pattern contains nested quantifiers. An attacker can submit an email like 'aaaaaaa!bbbbbbb@domain.com' that triggers catastrophic backtracking, causing the regex engine to explore millions of possible matches before failing.

Route parameter validation is another common attack vector. Express automatically parses URL parameters, but if you validate them with vulnerable regex patterns, you create a denial of service opportunity:

app.get('/api/users/:id', (req, res) => {
  const idRegex = /^\d+$/; // Simple digit check
  if (!idRegex.test(req.params.id)) {
    return res.status(400).json({ error: 'Invalid ID' });
  }
  // Query database
});

While this pattern is safe, more complex validation like checking UUIDs or custom formats often introduces vulnerabilities. Body parsing middleware also creates risks when processing JSON or URL-encoded data containing regex-vulnerable fields.

The impact extends beyond the single endpoint. Express runs on a single-threaded event loop in Node.js. When one request gets stuck in regex processing, it blocks the entire server, preventing it from handling other legitimate requests until the timeout occurs.

Express-Specific Detection

Detecting ReDoS vulnerabilities in Express requires analyzing both your route handlers and middleware stack. The middleBrick API security scanner specifically tests for regex denial of service by sending crafted payloads to your endpoints and measuring response times.

middleBrick's Input Validation check includes ReDoS detection. It submits payloads designed to trigger catastrophic backtracking and flags endpoints where response times exceed normal thresholds. For Express applications, it particularly focuses on:

  • Route parameter validation patterns
  • Body parsing middleware that validates content
  • Custom middleware performing input sanitization
  • Query parameter validation
  • Header validation logic

The scanner doesn't require access to your source code. It works by observing the runtime behavior of your API endpoints, making it ideal for testing production or staging environments without code changes.

Manual detection involves reviewing your regex patterns for red flags. Use tools like regexploit or safe-regex to analyze patterns before deployment. For existing Express applications, add timing checks to identify slow regex operations:

const vulnerableRoutes = new Set();

function checkRegexPerformance(regex, input, maxTime = 100) {
  const start = process.hrtime.bigint();
  regex.test(input);
  const elapsed = Number(process.hrtime.bigint() - start) / 1e6;
  return elapsed > maxTime;
}

app.use((req, res, next) => {
  const startTime = Date.now();
  const originalSend = res.send;
  res.send = function(data) {
    const duration = Date.now() - startTime;
    if (duration > 500) {
      console.warn(`Slow endpoint: ${req.originalUrl} (${duration}ms)`);
      vulnerableRoutes.add(req.originalUrl);
    }
    return originalSend.call(this, ...arguments);
  };
  next();
});

This middleware tracks slow endpoints that might indicate regex vulnerabilities. Combine this with logging middleware to capture the actual regex patterns being used and the inputs that trigger them.

Express-Specific Remediation

Fixing ReDoS vulnerabilities in Express applications requires both immediate patching and architectural changes. The most effective approach is replacing vulnerable regex patterns with safer alternatives or validation libraries.

For simple patterns, use non-capturing groups and avoid nested quantifiers. Instead of:

const badPattern = /^([a-z]+)+([a-z0-9._%+-]+)@[a-z0-9.-]+\.[a-z]{2,}$/i;

Use:

const safeEmailPattern = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i;

The key is eliminating nested quantifiers like (a+)+ or (a*)* that create exponential backtracking.

For complex validation, use dedicated libraries that implement safe parsing:

const { validate: validateEmail } = require('email-validator');
const { isUUID } = require('uuid');

app.post('/api/register', (req, res) => {
  if (!validateEmail(req.body.email)) {
    return res.status(400).json({ error: 'Invalid email' });
  }
  if (!isUUID(req.body.userId)) {
    return res.status(400).json({ error: 'Invalid user ID' });
  }
  // Process registration
});

These libraries use optimized algorithms that don't suffer from catastrophic backtracking.

Implement timeout protection for regex operations using worker threads or external validation services:

const { Worker } = require('worker_threads');

function safeRegexTest(pattern, input, timeout = 100) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(`
      const pattern = ${JSON.stringify(pattern)};
      const input = ${JSON.stringify(input)};
      const regex = new RegExp(pattern);
      parentPort.postMessage(regex.test(input));
    `);
    
    const timer = setTimeout(() => {
      worker.terminate();
      reject(new Error('Regex timeout'));
    }, timeout);
    
    worker.on('message', (result) => {
      clearTimeout(timer);
      resolve(result);
    });
    
    worker.on('error', (err) => {
      clearTimeout(timer);
      reject(err);
    });
  });
}

app.post('/api/validate', async (req, res) => {
  try {
    const isValid = await safeRegexTest(req.body.pattern, req.body.input);
    res.json({ valid: isValid });
  } catch (err) {
    res.status(500).json({ error: 'Validation failed' });
  }
});

This approach isolates regex operations in separate threads with timeouts, preventing them from blocking the main event loop.

Add rate limiting to endpoints that perform regex validation to limit the impact of any remaining vulnerabilities:

const rateLimit = require('express-rate-limit');

const validationLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests
  message: 'Too many validation requests'
});

app.use('/api/validate', validationLimiter);

Finally, integrate middleBrick's continuous monitoring into your CI/CD pipeline to catch new regex vulnerabilities before deployment. The Pro plan's GitHub Action can automatically scan your staging API and fail builds if ReDoS vulnerabilities are detected.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

How can I tell if my Express regex patterns are vulnerable to ReDoS?
Look for nested quantifiers like (a+)+ or (a*)* in your patterns. Test suspicious patterns using tools like regexploit or safe-regex. In Express, monitor endpoint response times—if validation suddenly takes hundreds of milliseconds for simple inputs, you likely have a ReDoS vulnerability. middleBrick's Input Validation check automatically tests for these issues by sending crafted payloads and measuring response times.
Does middleBrick detect ReDoS vulnerabilities in Express applications?
Yes, middleBrick's Input Validation check specifically tests for regex denial of service by sending payloads designed to trigger catastrophic backtracking. It measures response times and flags endpoints where processing exceeds normal thresholds. The scanner works without requiring source code access, making it perfect for testing production or staging APIs. middleBrick also provides remediation guidance and maps findings to OWASP API Top 10 categories.