ReDoS Deep Dive

ReDoS (Regular Expression Denial of Service) is a vulnerability where a crafted input makes a backtracking regex engine - one that tries one way to match and, when it fails, goes back to its last choice to try the next - do exponential or high polynomial work before it gives up. In PHP, that work usually ends in a silent failure: preg_match() returns false once PCRE’s backtrack limit is exhausted.

Simple explanation

Take /(a+)+$/ and the input "aaaaaaaaaaaaaaaaaaa!". The ! means the pattern cannot match, but the engine only learns that after trying every way of splitting the as between the inner + and the outer +. Each extra a doubles the number of ways. With PHP’s default limits, 19 a and a ! are enough for preg_match() to fail with “Backtrack limit exhausted”.

How ReDoS happens

The problem: ambiguity under backtracking

PCRE tries the alternatives of a pattern in a fixed order: the left alternative first, a greedy quantifier’s next iteration before its exit, a lazy one the other way round. When an attempt fails, it backtracks to the last choice and tries the next one (How PCRE2 Matches shows that walk, step by step, in the engine’s own traces). That costs nothing when there is only one way to match each part of the input. It costs a lot when there are many:

Pattern: /(a+)+$/
Input:   "aaaa!"

The engine tries:
- (a+) takes "aaaa", the outer + stops, $ fails on "!"
- (a+) takes "aaa", the outer + repeats with "a", $ fails
- (a+) takes "aa", then "aa", $ fails
- (a+) takes "aa", then "a", then "a", $ fails
- ... every composition of 4: 2^3 ways, then 2^(n-1) for n characters

Two classes of cost

  • Exponential: a loop that can read the same text in two different ways, as (a+)+, (a|aa)* or (a|a)*. Each repetition of that text doubles the work: 2ⁿ steps.
  • Polynomial: two or more quantifiers in a row that can read the same text, as a*a* (n² steps) or a*a*a* (n³). The backtrack limit does not stop it in time: /a*a*$/ matches 200,000 a and a ! without an error, after 6.5 seconds.

Vulnerable shapes

Each pattern below was run through RedosAnalyzer and, for the vulnerable ones, its attack replayed on PCRE2:

pattern verdict
(a+)+$, (.*)*$, (\d+)+$ exponential: nested unbounded quantifiers
(a\|aa)+$, (a\|a)*$ exponential: alternatives that read the same text
(a*)*$ exponential: a repeated group that can match nothing and something
a+a+$, (\w+)(\w+)$, \d+\d+$ polynomial, degree 2: adjacent quantifiers over the same characters
a*a*a*$ polynomial, degree 3
(a\|b)+c, (a\|ab)+$, (a?)+$ linear: proven safe, though they look alike
(\w+)\1+$ outside the model (backreference): the heuristics decide

How PHPRegex detects ReDoS

PHPRegex reads the pattern, and runs it only to check a witness through a lookaround on a few short inputs (or in confirmed mode). A witness is the input built to drive the worst case: a prefix that reaches the risky part, a pump repeated as the input grows, and a suffix that makes the attempt fail. Step by step:

  1. The lexer and parser build a RegexNode AST.
  2. RedosAnalyzer builds from it a prioritized NFA: a machine - an automaton - that lists every way the pattern can be tried, each choice in the order PCRE tries it (NFA stands for nondeterministic finite automaton; prioritized because its ε-transitions, the moves that read no character, carry exactly PCRE’s order). Atomic groups, possessive quantifiers and atomic lookaround bodies are separate automata, analysed on their own and seen from outside as one step. A lookaround’s body runs again each time the attempt passes it, so a proof of a linear attempt also builds the pattern with its lookaheads read in place, and refuses the proof where a loop reads into a loop of a lookahead’s body: /^(?:(?=a+)a)+$/ reads the run again from each position, quadratic.
  3. It looks for ambiguity in that automaton, after the method of Weideman et al. (“Analyzing Matching Time Behavior of Backtracking Regular Expression Matchers by Using Ambiguous NFA”, 2016):
    • a state with two different loops reading the same word means exponential cost;
    • a chain of k states, each looping on a word and reaching the next on that same word, means polynomial cost of degree k.
  4. From the ambiguous loop it builds the witness: a prefix that reaches it, the word to pump, and the shortest suffix that makes the attempt fail. Characters are chosen deterministically: the smallest printable ASCII character of each set, then the other sets of the loop, before giving up. The model does not decide a lookaround: a witness through one is checked on the running PCRE2, its attempt pinned where it starts.
  5. The pattern’s class is the worst class over the pattern and its sub-searches.

A pattern is safe (proven) only when the automaton holds no ambiguity, but in a loop the engine never backs out of far, and no lookaround reads a run again at each step of a loop (abstractions then lists lookaround at offset N read again at each step of a loop). In /^(?:a|a)+./ whatever the loop reads on, the dot can read too: success is sure a character later, every run the engine abandons inside the loop is short, and the pattern is proven linear (see The guarantee). Any other ambiguity for which no witness can be built is not taken as safe: the heuristics decide, and abstractions lists ambiguity without witness at offset N.

The model covers characters and classes (exact sets under /u and /i, computed from the running PCRE2), alternation, groups, every quantifier, atomic groups, possessive quantifiers, atomic lookarounds, anchors and word boundaries. Inline options it reads exactly as PCRE does, rule by rule:

  • an option set inside one alternative also holds in the alternatives after it;
  • r (caseless restrict) and the ASCII options (a, aD, aS, aW, aP, aT) are read per scope;
  • (?^) clears i, m, n, s, x, xx and r, and keeps U and the ASCII options;
  • xx drops a class’s unescaped spaces and tabs ([a\ b] still matches a space);
  • \b under aW reads the ASCII \w.

Each rule, with worked patterns, sits in the ReDoS guide. A leading (*UCP) is read too, every class asked of the engine under it. Backreferences, conditionals, recursion and subroutine calls, backtracking control verbs, the other options a pattern opens with ((*UTF), (*CR), …, and (*UCP) beside one of them), callouts, \X, \R, non-atomic lookarounds such as (*napla:…), \b and \B under two different ASCII scopes in one pattern ((?aW:\b)…\b), and a bounded repeat whose body can match the empty string are outside it: there, as for a pattern over the analysis budget, the structural heuristics of RedosProfiler decide:

  • star height: nested unbounded quantifiers;
  • overlapping alternatives inside a repetition, through CharSetAnalyzer;
  • backreference loops inside a repetition;
  • quantifiers over sub-patterns that can match nothing;
  • adjacent quantifiers over overlapping character sets;
  • atomic groups and possessive quantifiers lowering the severity.

The result says which of the two decided: proof is proven, heuristic, budget_exceeded or not_analyzed. The ReDoS guide states what a proof guarantees, and its limits.

Installation

composer config minimum-stability dev
composer config prefer-stable true
composer require --dev php-regex/regex-cli:2.x-dev

The CLI commands live in the regex binary from php-regex/regex-cli; the PHP API lives in php-regex/regex-toolkit.

Using PHPRegex for ReDoS protection

The commands and the API live in the guide, kept there once: the ReDoS guide shows the three calls that matter — vendor/bin/regex analyze '/(a+)+$/' for a verdict, --redos-mode=confirmed to replay the attack on the running PCRE, and regex lint src/ --redos --no-lint --no-optimize over a code base — plus the PHP side, Regex::create()->redos() with its severity, witness and isProvenSafe().

Fixing vulnerable patterns

Every fix works the same way: it removes the ambiguity the automaton found, leaving one way to read each repetition instead of many. Possessive quantifiers and atomic groups commit to the first match and never revisit it; simplifying (a+)+ to a+ deletes the second way to split the same text; bounding a repeat caps the work even when overlap remains.

The rewrite cookbook - each repair proven safe (or not) by the analyzer, the quick-reference table of vulnerable vs safer pairs, and the defense-in-depth checklist - lives in the ReDoS guide:

Further reading

Edit on GitHub Feedback