Regular expression denial of service
| Class | Availability and abuse |
|---|---|
| Also known as | ReDoS; catastrophic backtracking |
| CWE | CWE-1333: Inefficient Regular Expression Complexity |
| MITRE ATT&CK | T1499 Endpoint Denial of Service |
| Typical severity | High on a public route |
| Affects | Backtracking regex engines: JavaScript (V8), PCRE, Python, Java, .NET, Ruby, Perl; input validators, routers, parsers and firewall rules built on them |
Matched against ^(a+)+$, the string aaaaX can be split into 16 different paths through the pattern, and a backtracking engine tries each of them before it reports that there is no match. With sixteen a characters before the X the count is 65,536, and every extra a doubles it.1 Regular expression denial of service (ReDoS) is an attack that sends such input to a program on purpose, so that one regular expression keeps a processor busy for a long time and the program stops answering other work. It is a form of denial of service in which one short request is enough.
Backtracking
Most engines in common languages read a pattern as a set of choices. At each quantifier (+, *, ?) or alternation (|), the engine takes one option, continues, and if the rest of the pattern fails it returns to the last choice and tries the next option.12 A pattern such as (a+)+ can cover a run of letters in exponentially many ways: one long inner match, two shorter ones, three, and so on. When the input finally fails at the end, the engine cannot rule out that an earlier split was the wrong one, so it tries them all.1
The slow case needs three things together: a number of possible paths that grows exponentially with input length, input that can fail to match, and input long enough to matter.3 A failed match sets it off; on input that matches, a vulnerable pattern usually returns quickly.4
Growth slower than exponential can still stop a site. \s+$, meant to find trailing spaces, restarts at every space when a run of spaces is followed by another character. For 20,000 spaces that is about 200 million character checks: quadratic, not exponential.5
Patterns that backtrack
The risky shapes are a repeated group whose body is itself repeated, such as (a+)+ or ([a-zA-Z]+)*, and a repeated alternation whose branches can match the same text, such as (a|aa)+ or (a|a?)+.1 The trouble grows when the text matched by the outer part is a subset of what the inner part matches.6 Backreferences such as (a.*)\1 cannot be guaranteed to run in linear time by any engine.4 Two unbounded wildcards in a row before a required character, as in .*.*=.*, are enough: with 20 x characters and no =, that pattern takes 4,067 steps to fail.7
A second route is regex injection. When text from a user becomes part of the pattern, for example a username tested against a password to reject passwords that contain it, the attacker supplies the slow pattern as well as the input.1
Effect on a server
Node.js runs request handlers on one event loop. A handler stuck in a regular expression holds that thread, and every other client waits until the match ends.4 In an Express route that checks a file path with /(\/.+)+$/, a query of 100 slashes followed by a newline blocks the loop "effectively forever".4
The same flaw has appeared inside libraries. path-to-regexp, a package that turns route strings into regular expressions, generated a backtracking pattern for any route with two parameters in one path segment separated by something other than a dot, such as /:a-:b. A path of /a, then -a repeated 8,000 times, then /a exploits it. In a test with Express 4 and 10 concurrent connections, average latency rose from about 1 ms to about 600 ms. The advisory was published in September 2024, with fixes in versions 0.1.10, 1.9.0, 3.3.0, 6.3.0 and 8.0.0.8
Outages
On 2 July 2019, Cloudflare deployed a new web application firewall rule at 13:42 UTC. A part of its pattern that reduced to .*.*=.* backtracked heavily and exhausted every processor core that served HTTP and HTTPS traffic across its network, and visitors to Cloudflare sites saw 502 errors for 27 minutes. The rule was in simulate mode, which blocks nothing but still runs the pattern. The firewall used PCRE with no limit on a runaway expression; a protection against excessive regex processor use had been removed by mistake in a refactor weeks before, and the test suite did not measure processor time. Afterwards Cloudflare checked all 3,868 rules by hand and planned a move to the re2 or Rust regex engines, which both bound their running time.7
On 20 July 2016, Stack Overflow was down for 34 minutes. A post with about 20,000 consecutive whitespace characters appeared in the home page list, and a trimming expression, ^[\s\u200c]+|[\s\u200c]+$, ran on it at every home page view. The load balancer used the home page as its health check, so it took every web server out of rotation. The expression was replaced with a substring function.5
Prevention
Rewriting the pattern
Remove nested quantifiers and overlapping alternatives.3 For a fixed substring, a string search such as indexOf replaces the regular expression and runs in linear time.4 In .NET, an atomic group (?>...) stops the engine from returning into it.6
Linear-time engines
Engines built on Ken Thompson's 1968 algorithm track every possible state at once and read each character once.7 RE2 and the Rust regex crate work this way.2 .NET 7 added RegexOptions.NonBacktracking.6 V8 has shipped an experimental linear engine behind flags since version 8.8; it stays experimental because the default engine is orders of magnitude faster on most common patterns.2 The node-re2 package brings RE2 to Node.js but does not accept every V8 pattern, so a swap needs testing.4 The algorithm cannot handle backreferences, lookahead or lookbehind without losing its linear bound.2
Limits on input and time
A length limit, checked during input validation before any match runs, shrinks the worst case: for the path-to-regexp flaw, halving the attack string made the match four times faster.8 In .NET a match has no timeout unless one is set; with one, the engine throws RegexMatchTimeoutException:6
var rx = new Regex(pattern, RegexOptions.None, TimeSpan.FromMilliseconds(100));PHP limits backtracking with pcre.backtrack_limit.3 Microsoft describes the .NET timeout and the non-backtracking mode as protection against accidental slowness in patterns a developer wrote, not as a security boundary. When user text has to go inside a pattern, Regex.Escape turns it into literal characters first.6
Dependencies
Pattern checkers such as safe-regex miss some vulnerable expressions.4 A flaw inside a package, such as the path-to-regexp one, is published as an advisory and fixed by upgrading the package, which makes it a case of vulnerable dependencies.8
Find every regular expression in this project that runs on input from a request, a form, a file upload, a header or a database field users can write to. Flag patterns with a repeated group whose body is also repeated, alternatives that can match the same text, two unbounded wildcards in a row, or backreferences, and any pattern built from user text. Rewrite each flagged pattern so every character can be matched only one way, or replace it with a plain string function. Add a length check on the input before the match. List each file and line, the old and new pattern, and any pattern you could not make safe.
In SecFlash
SecFlash reports a regular expression that can hang under SF-SEC-711 on the Security page.
See also
- Denial-of-service attack
- Input validation
- Vulnerable dependencies
- Dependabot
- Category: Availability and abuse
References
- a b c d e Weidman, Adar, et al. "Regular expression Denial of Service - ReDoS". OWASP Community. OWASP Foundation.
- a b c d "An additional non-backtracking RegExp engine". V8 blog. Google.
- a b c "CWE-1333: Inefficient Regular Expression Complexity". Common Weakness Enumeration. MITRE.
- a b c d e f g "Don't Block the Event Loop (or the Worker Pool)". Node.js Learn. OpenJS Foundation.
- a b Stack Exchange (20 July 2016). "Outage Postmortem - July 20, 2016". Stack Exchange Network Status.
- a b c d e "Best practices for regular expressions in .NET". Microsoft Learn. Microsoft.
- a b c Graham-Cumming, John (July 2019). "Details of the Cloudflare outage on July 2, 2019". The Cloudflare Blog.
- a b c GitHub Advisory Database (9 September 2024). "path-to-regexp outputs backtracking regular expressions" (GHSA-9wv6-86v2-598j, CVE-2024-45296). GitHub.