ReDoS Guide
ReDoS (Regular Expression Denial of Service) happens when a regex takes exponential or high polynomial time to reject certain inputs. This guide explains what PHPRegex proves about a pattern, how to read its verdict and the attack it hands you, what confirmed mode adds, and how to fix a vulnerable pattern.
Nothing matches that filter — try a shorter fragment, or press Escape to see the whole page again.
PHPRegex proves a pattern safe, or hands you the input that kills it. Where it cannot do either, it says so, and its structural heuristics decide.
Installation
composer config minimum-stability dev
composer config prefer-stable true
composer require php-regex/regex-toolkit:2.x-devNote: ReDoS analysis is disabled by default in the linter and the integrations. Enable it explicitly:
- CLI:
vendor/bin/regex lint src/ --redos, orchecks.redos.enabled: trueinregex.json- PHPStan: include
rules.neon, or setphpRegex.checks.redos.enabled: true(see the PHPStan guide)- Symfony:
php_regex.redos.enabled: true; Laravel:redos.enabledinconfig/php-regex.php
Regex::redos(),vendor/bin/regex analyzeandvendor/bin/regex debugalways run it.
What Is ReDoS?
PCRE is a backtracking engine: it commits to one way to match and, when that way fails, goes back to its last choice and tries the next. When a pattern can match the same input in several ways, the engine tries them one after the other before it gives up, and the number of ways can grow exponentially with the length of the input.
Pattern: /(a+)+$/
Input: "aaaaaaaaaaaaaaaaaaa!"
(a+) can take 1 to n characters, and the outer + can repeat the group 1 to n times. The ! makes $ fail, and the engine tries every way of splitting the as between the two quantifiers before it reports no match.
How ReDoS shows up in PHP
In PHP, a vulnerable pattern rarely hangs: it fails silently. Measured with PHP 8.4 and PCRE2 10.49, the default pcre.backtrack_limit of 1,000,000 and the JIT (PCRE2’s just-in-time compiler, enabled by default since PHP 7.0 via pcre.jit=1) on:
/(a+)+$/,/(\w+\s?)+$/and/^(\d+)*$/makepreg_match()returnfalse(“Backtrack limit exhausted”) on 19 characters followed by!, after about 2 ms./(a|aa)*$/fails from 29 bytes,/a*a*a*$/from 1,412. Code that reads the result as a boolean lets through, or rejects, whatever it is given.- A polynomial pattern is a CPU problem the limit does not see.
/a*a*$/never trips it, but takes about 20 ms on 10,000 characters, 0.4 s on 50,000 and 6.5 s on 200,000. - PCRE’s optimizations defuse some ambiguity, never add any.
/(a+)+b/rejects 5,000as at once, because thebevery match needs is absent; with abafter a character the loop cannot take, asa…a!b, it fails from 21 bytes like/(a+)+$/. - Lookaround bodies backtrack too:
/(?=(a+)+b)/fails from 21 bytes ona…acb. - Atomic groups and possessive quantifiers do not backtrack:
/^(?>a+)+$/rejects 5,000aand a!in a few hundredths of a millisecond. - The functions that look for every match cost more than
preg_match():/a*b|a/takes no measurable time withpreg_match()on 80,000a, and about a second withpreg_match_all(). preg_match()called without$matchesdoes not stop at an empty match: it searches again for a non-empty one./a*|(b+)+$/returns1on 25band a!when$matchesis passed, andfalse(“Backtrack limit exhausted”) when it is not.
What the verdict means
For every pattern inside the subset of PCRE it models, RedosAnalyzer builds an automaton - a machine that lists every way the pattern can be tried - of PCRE’s backtracking, with the alternatives and quantifiers tried in PCRE’s order, and computes the complexity class of one match attempt:
| complexity | what it means | severity |
|---|---|---|
linear |
no input makes an attempt backtrack beyond a linear number of steps | safe |
polynomial, degree 2 |
an input makes an attempt cost n² steps | medium |
polynomial, degree 3 or more |
n³ steps or more | high |
exponential |
2ⁿ steps | critical |
proof says who decided:
| proof | meaning | severity |
|---|---|---|
proven |
the model proved the class | from the class, as above |
heuristic |
the pattern holds a construct outside the model: the structural heuristics decided | the heuristics’ severity |
budget_exceeded |
the model ran out of its budget: the heuristics decided | the heuristics’ severity |
not_analyzed |
no analysis ran: the mode was off, the pattern ignored, or the analysis failed | safe (off, ignored) or unknown (error) |
Every consumer prints the same headline, from RedosAnalysis::headline(). It never says a bare “safe”:
| headline | when |
|---|---|
safe (proven) |
proven linear |
Polynomial backtracking, degree 3 (proven) |
proven polynomial, with its degree |
Polynomial backtracking (proven) |
proven polynomial, degree not determined |
Exponential backtracking (proven) |
proven exponential |
Potential backtracking (heuristic) |
the heuristics found a risk, inside or over the budget |
no risk found (heuristic) |
the heuristics found nothing |
not analyzed |
the mode was off or the pattern was ignored |
not analyzed (budget exceeded) |
over the budget, and the heuristics found nothing |
not analyzed (analysis error) |
the analysis failed, or the pattern is invalid |
The guarantee
safe (proven) says, plainly: no input can be matched in two different ways by the model, but by a loop the engine never backs out of far, and no lookahead body is re-read at each step of a loop, so one match attempt stays proportional to the length of the input. Precisely: the model of the pattern holds no ambiguity, neither exponential nor polynomial, but in a loop every run abandoned inside of which is bounded (see below), and no lookaround reads a run again at each step of a loop. So in one match attempt at one start position, no input drives a backtracking engine that follows PCRE’s order beyond a linear number of steps, the work inside its lookarounds included, on the pattern as analysed. PCRE’s optimizations can only lower that cost.
A loop read in two ways that no suffix makes fail is linear all the same. In /^(?:a|a)+./ the loop reads every a, the dot fails at the end, the loop gives one a back and the dot reads it: whatever character the loop can go on with, success is sure a character later. The engine never backs out of a part of the attempt that holds a success, so every run it abandons inside the loop is short, and the two ways around the loop cost nothing: 35 then 67 steps on 16 then 32 a and a ! in the interpreter, the steps /^(?:a|b)+./ takes. The analysis proves it so: from what follows each state of the loop, it reads the sets of states an abandoned run may stand at, character after character, and the pattern is safe (proven) when none of them keeps the run inside the loop for ever, and the ways into the loop times the ways the run reads it over its longest stretch and leaves it, every path counted along the whole attempt, through the loops before and after it, stay within 1,024, the margin of the paths one attempt tries at once (see below). /^(?:a|aa)+./, /^(?:a|a)*./, /^(?:a|a)+.+/, /^(?:a|a)+.{3}/ and /(*NOTEMPTY)^(?:a\K|a)+/ are proven linear that way. /^(?:a|a)+$/ and /^(?:a|a)+.$/ are exponential, a suffix failing after every way out of the loop, and /^(?:a|a)+.{20}/ is not proven: its abandoned run is bounded, twenty characters, but read in some four million ways, and PHP exhausts its backtrack limit on 60 a and a newline. So is a loop reached by many empty routes: ten groups (?:|) before the a of /^(?:(?:|)…a)+./ give 1,024 ways to it, and one attempt on one a and a newline takes 1,049,601 steps. The check is not made where the model may count a success the engine refuses: a lookaround, an atomic group or possessive repeat the model keeps with every way through it (one that reads nothing included: /(*NOTEMPTY)^(?:a|a)+(?>\K|)/ commits to the empty match \K leaves, which the option refuses, and the interpreter doubles its steps with each a), a bounded repeat it reads as unbounded, $ or \Z before a final newline, ^ under m (which does not hold after a newline that ends the subject: /\A(?:\n|\n)+\n^(?:\z|.)/m takes 285 then 18,429 steps on 6 then 12 newlines); and it reads 64 sets of states at most, so /^(?:a|a|bc)+.{6}/, linear on the engine, is left to the heuristics. A run abandoned after the loop, in a loop of its own, is read as any other link, so /^(?:a|a|ab)+(?:[ab]*c|a)/, quadratic (160 then 454 steps on 6 then 12 ab and a !), is not proven linear. Such a pattern has no upperBoundDegree: the state with two paths back to itself is there.
Any other ambiguity the analysis finds but cannot turn into a working attack is never called linear: the verdict falls back to the heuristics, and abstractions says why:
vendor/bin/regex analyze '/(\w*a\w+)+\b/'
Status : Potential backtracking (heuristic)
Severity : CRITICAL (score 10)
Mode : THEORETICAL
Confidence : HIGH
Model: ambiguity without witness at offset 1
A proven degree is one its witness - the attack input, built as described under
The witness below - reaches: the loops of the chain read the
word the witness pumps. In /^[!a]*.*a*b$/ the three loops read a, so the
witness is "a" x n . "\nb", cubic (2.7, 13.3 and 149 ms on 250, 500 and
1,000 a without the JIT), where "!" x n . "\nb" would be quadratic. In
/^[!]*[!a]*a*b$/ the first link reads ! alone and the second a alone:
no pump drives the three loops, so degree 3 has no witness and the
heuristics decide, though "!" x n . "a" x n . "\nb" is cubic.
The limits of the guarantee, each one deliberate:
-
One match attempt. The verdict covers one match attempt, at one start position. When it fails,
preg_match()tries again at the next start position the search allows: a search is unanchored as long as it can start later. A^or\Ain one alternative only does not anchor it (/^z|a+$/matches at offset 1 of"baaa"), a^under/malso matches after a newline, and PCRE2 may skip positions it can rule out.preg_match_all(),preg_replace()andpreg_split()look for every match. Those retries can multiply the cost of an attempt by the length of the subject: a degree-k per-attempt verdict costs up to n^(k+1) steps over an unanchored search. When one attempt is proven linear, the analysis looks for the run that makes the search quadratic: see The cost of an unanchored search. A pattern that matches inside the run is not reported there:/a*b|a/issafe (proven), and thepreg_match_all()figure above is that multiplication. The second searchpreg_match()runs without$matchesafter an empty match is covered: for a pattern that can match empty, the analysis also models an attempt where an empty match at its start does not count, which is why/a*|(b+)+$/is exponential. Measured without the JIT,/a*a*$/, quadratic per attempt, takes:- 12 ms on 500
aand ab, - 87 ms on 1,000
aand ab, - 659 ms on 2,000
aand ab- eight times as long each time the length doubles.
- 12 ms on 500
- The paths an attempt tries at once are bounded. An attempt that fails tries every path through the pattern, and the analysis counts them all: each empty route, each way one input is read, each route that dies at a check, as
\bbetween two word characters, multiplied along the whole attempt, across its loops and into a lookaround’s body, which runs once for each path through it. Paths that leave a loop at different times and meet at one position add up, as do the paths of loops read side by side. Past 1,024 at once on one input, the cost of a character is out of the model, and a pattern otherwise linear is left to the heuristics: ten groups(?:b{0}|)before anxand ten after it, then\ba, take 1,048,577 steps onxawith no loop at all, every route after thexdying at\b; ten copies(?:a|[a])beforex+and ten groups after it, then a dot, 1,048,577 on tena, anxand a newline, each part within the margin;/^a+a{0,15}b+b{0,15}c+c{0,15}d+d{0,15}e+e{0,15}f/, 9,437,177 on sixteen of each letter and a newline, each loop giving the next sixteen ways at once. - The pattern as analysed. A bounded repeat
{m,n}whosenis above 16 is analysed as{m,}, and so is any bounded repeat whose copies can read the same input in two ways. An exact count{n}has no optional copy and is kept as written whatevern:/(?:a{17})+b/is proven linear, as/(?:a{16})+b/is. An atomic group or possessive quantifier whose body is more than one run over one set, than an alternation of one-character branches (read as one character of their union,(?>a|\d)), or than greedy unbounded repeats of such a run each taken at most once at least ((?:a+)++, read as the longest run it commits to), is kept as written: a body that splits a run into many copies,(?:a+){30,}+, tries every way to split it before it fails, atomic or not. Each repeat analysed as unbounded and each atomic body kept as written is listed inabstractions({3,20} at offset 1 analysed as {3,},atomic group at offset 1 over-approximated) and printed on aModel:line, so you can see what the proof is about; the two bodies read exactly, as(?>a|\d)and(?:a+)++, are not listed, as their model loses nothing. The class is the class of that model: a bounded repeat analysed as unbounded can be reported exponential where PCRE’s cost stays polynomial, and confirmed mode then says the attack was not reproduced. The widening never makes a success sure: an ambiguous loop is set aside only when what follows it succeeds on a path that takes one round at most of such a repeat and goes through no such body, so/^(?:a|a)+[^x]{0,20}(?:x|\z)/, which PHP fails on with 20aand 30b, is notsafe (proven), where/^(?:a|a)+[^x]*(?:x|\z)/is. A pump that goes round such repeats alone, and no loop of the pattern, holds up to their bound only: it is proven once PHP’s PCRE2, run under its default limits on the witness, its attempt pinned to the start, gives up at the backtrack limit./^(?:a|a){1,40}$/and/^(?:\d{1,3}\.?){1,30}$/are then exponential (proven), as/^(?:a+){1,30}$/is through its inner loop;/^(?:a|a){1,16}$/, which never reaches the limit, keeps the heuristics’ verdict. - Lookarounds may fail. The model does not evaluate what a lookahead or lookbehind requires: it counts every run through one as possibly failing, so that the engine may keep backtracking past it. A lookaround never turns a vulnerable pattern into
safe (proven)(/(a+)+(?=b)/is exponential, and PHP fails on it from 20 bytes). A witness of a pattern holding a lookaround is asked of the running PCRE2 before it proves anything, on a few pumps, its attempt pinned where it starts: the attempt must fail there, and, when the way to the loop crosses a lookaround, it must match once the suffix is replaced with one the pattern accepts, so the lookarounds on the way hold. A lookbehind at the start of the pattern leads the witness with what it asks for (/(?<=\[)…/gives"[" . "**" x n . "\n"). When no witness passes, a lookaround the attempt crosses before the loop, and never after it, is taken to hold, so that a success after it counts, and the witness is looked for again; when none passes still, the heuristics decide. So/(?<![a-z-])background-color\s*:\s*[^;]+;?/i, whose witness PHP matched at once, is no longer proven polynomial. The body of an atomic lookaround is analysed as its own search, and its class joins the pattern’s. -
The work inside a lookaround counts. A lookahead’s body runs again each time the attempt passes it. Inside a loop, or after one the attempt backtracks into, a body that reads a run re-reads it at every step: two linear parts can thus combine into a quadratic or cubic whole.
/^(?:(?=a+)a)+$/is the example - there the proof is refused and the heuristics decide:/^(?:(?=a+)a)+$/takes 1.1, 4.2, 16 and 74 ms on 2,000, 4,000, 8,000 and 16,000aand a!without the JIT, about four times as long each time the length doubles, though the loop and the lookahead are each linear. PCRE2 counts a run of one class as one step, so the backtrack limit never stops it, and confirmed mode cannot replay it.- The analysis builds the pattern again with each lookahead read where it stands, as a branch tried first, and a loop that reads, on the same characters, into a loop of a lookahead’s body refuses the proof:
abstractionssayslookaround at offset 4 read again at each step of a loop, andupperBoundDegreeadds the body’s loops to the attempt’s (2 here). - A lookahead whose body reads other characters than the loop (
/^\w+(?=\s*$)/), a bounded one ((?=a),(?=a{1,100})), one outside any loop, and one after a possessive run keep their proof. - A lookbehind reads a bounded number of characters back, a fixed length or at most 255 when its length varies (
(?<=a{1,256})does not compile), so its cost stays bounded, unless it holds a lookahead, which is read in place too. A lookahead that reads a run but stops at once ((?=a+?), or(?!a+)where the loop readsa) loses its proof all the same: the analysis does not tell when a body stops. - A negative lookahead whose body fails all over the witness holds at each step, and its body reads the rest of the run each time: the product is proven, so
/^(?:(?!a+b)a)+$/ispolynomial, degree 2 (1.1, 4.1 and 17 ms on 2,000, 4,000 and 8,000aand a!without the JIT), and so is the tempered token/^(?:(?!.*foo).)*$/. - A polynomial lookahead read again in a loop adds its degree to the loop’s: where a negative lookahead’s body fails all over the witness, the lookahead holds at each step and its body costs its own degree there, so
/^(?:(?!a*a*b)a)*$/, whose body alone is quadratic, is proven of degree 3 (1.0, 7.3 and 51 ms on 200, 400 and 800aand a!without the JIT). - A positive lookahead, a lookbehind, or a body that matches on the witness keeps the degree its own search proves.
- Word boundaries and anchors are exact.
\band\Bare modelled from the word class of the characters around them, at every attempt start and inside lookarounds;^,$,\A,\z,\Z,/mand/Das PCRE reads them,^under/mincluded. - Inline options as PCRE reads them. An option set inside one alternative also holds in the alternatives after it, up to the end of the group around it: in
/x(?s)|(?:.*\n.*\n)+x/the dots of the second alternative cross newlines, and the pattern is exponential.r(caseless restrict) and the ASCII optionsa,aD,aS,aW,aPandaTare read per scope, likeiands, so/^(?r)(?:k|\x{212A})*$/iuissafe (proven)(the Kelvin sign no longer matchesk) and/^(?^i)(?:k|\x{212A})*$/uris exponential.(?^)clearsi,m,n,s,x,xxandr, and keepsUand the ASCII options. Underxxa class skips its unescaped spaces and tabs, and a lonextakesxxoff:/^(?xx)(?:[a b]|\x20)*$/is proven linear,/^(?xx)(?x)(?:[ a]|\x20)*$/exponential.\band\BunderaWread the ASCII\w. - The options a pattern opens with. Each is read by what it changes.
(*UCP), without/u, makes\w,\d,\s, the POSIX classes,\band caseless matching follow the Unicode properties of the bytes past ASCII, and every class is read under it:/(*UCP)(?:\w|\xC9)+$/is exponential (Éis a word character there; PHP fails on 25 of them and a!),/(*UCP)^(?:\W|\xC9)+$/issafe (proven), where/^(?:\W|\xC9)+$/is exponential. A newline convention,(*CR),(*NUL),(*ANYCRLF)or(*ANY), changes what the dot and\Nleave out, and they are read under it:/(*CR)^(?:.|\r)+b/issafe (proven),/(*CR)^(?:.|\n)+b/exponential.(*CASELESS_RESTRICT)isr.(*NOTEMPTY)refuses a match\Kleaves empty, since\Ksets the start of the match where it stands, and is read where the pattern holds one:/(*NOTEMPTY)^(?:a|a)+\K/gives back every way through(?:a|a)+and is exponential (PHP exhausts its backtrack limit on 2,000awithout the JIT), where/^(?:a|a)+\K/issafe (proven); when the attempt succeeds once the loop gives a character back to read after\K, as in/(*NOTEMPTY)^(?:a|a)+\K.?/, it issafe (proven), as/^(?:a|a)+./is (see The guarantee). The others change no match one attempt makes, and the pattern keeps the verdict it has without them:(*NO_JIT),(*LIMIT_MATCH=…),(*LIMIT_DEPTH=…),(*LIMIT_HEAP=…),(*NOTEMPTY)where no\Kstands and(*NOTEMPTY_ATSTART)(the analysis already models an attempt that refuses an empty match),(*NO_AUTO_POSSESS),(*NO_START_OPT),(*NO_DOTSTAR_ANCHOR),(*BSR_ANYCRLF)and(*BSR_UNICODE),(*LF),(*UTF)under/u, and(*TURKISH_CASING)where nothing is caseless./(*NO_JIT)(?:a|ab)+c/issafe (proven), as/(?:a|ab)+c/is. A limit the pattern sets stops PCRE2 sooner, but the checks the proof asks of the engine run under PHP’s default limits:/(*LIMIT_MATCH=100)^(?:a|a){1,16}$/gets the verdict of/^(?:a|a){1,16}$/. Two of them move where attempts start, and the two that refuse an empty match change which attempts of a search may end on one: see The cost of an unanchored search. - One engine. Character classes under
/uand/iare computed by asking the running PCRE2, so(\p{L}|\d)+$is proven safe under/uand(\w|é)+$exponential (éis a word character there). Without/u, they are asked under the character tables of the target’s locale (see Which locale judges a pattern):/^(?:\w|\xE9)+$/issafe (proven)underCand exponential underfr_FR.ISO8859-1. A class the analysis can only over-approximate is listed inabstractions, and then never yieldssafe (proven). A verdict is deterministic for one PHPRegex analysis version and one PCRE2 release; the result carries both. The probes forrand the ASCII options need PCRE2 10.43: a running PCRE2 older than that, judging a pattern for a newer target, cannot compile them, so each such class is read as any character and listed inabstractions. The pattern is then neversafe (proven), and usually gets a heuristic verdict: two CI rows on different PCRE2 releases can disagree on it. A property is asked as the running PCRE2 spells what the target means: running on PHP 8.1 for PHP 8.4,/^(\p{sc=Grek}|a)+$/uis read through\p{Greek}and proven safe, while/^(\p{Greek}|\x{342})+$/u, whose bare script name means the script extensions from PHP 8.2 and has no name on PHP 8.1, is read as any character: neversafe (proven), where PHP 8.4 exhausts its backtrack limit on 30\x{342}and a!.
Outside the model, the heuristics decide and proof is heuristic: backreferences, conditionals, recursion and subroutine calls, backtracking control verbs, what a start option changes and the model does not read ((*UTF) without /u, under which PHP hands PCRE2 a subject it does not check; under a newline convention other than LF, $ but under /D alone, \Z, and ^ and $ under /m; the dot and \N under (*CRLF), which take a carriage return unless a line feed follows it; caseless matching under (*TURKISH_CASING)), callouts, \X and \R, non-atomic lookarounds ((?*…), (*napla:…), (?<*…), (*naplb:…)), \b and \B under two different ASCII scopes in one pattern ((?aW:\b)…\b), and a bounded repeat {m,n} (n above 1) whose body can match the empty string.
A proven vulnerable verdict certifies the class of the model. Its confidence is high only once the running PCRE has reproduced it (see Confirmed mode); until then it is medium. A proven safe verdict has high confidence.
The witness
Every proven vulnerable verdict carries a witness, the family of inputs that drives the worst case: a prefix, a pump repeated n times, and a suffix that makes the attempt fail.
vendor/bin/regex analyze '/(a|aa)*$/'
[3/4] ReDoS analysis
Status : Exponential backtracking (proven)
Severity : CRITICAL (score 10)
Mode : THEORETICAL
Confidence : MEDIUM
Attack: "aaa" x n . "!"
Hotspot: 1-5
Read "aaa" x n . "!" as PHP: str_repeat("aaa", $n) . "!". Each part is a PHP double-quoted literal, with everything outside printable ASCII escaped (\x00, \n, \t, \xFF without /u, \u{202E} under /u), so it pastes into PHP and gives the same bytes; an empty prefix or suffix is left out. RedosWitness builds the raw input:
use PHPRegex\Redos\RedosAnalyzer;
$analysis = (new RedosAnalyzer())->analyze('/(a+)+$/');
echo $analysis->headline(), "\n"; // Exponential backtracking (proven)
echo $analysis->witness->render(), "\n"; // "a" x n . "!"
var_dump(preg_match('/(a+)+$/', $analysis->witness->build(30))); // bool(false)
echo preg_last_error_msg(), "\n"; // Backtrack limit exhausted
toArray() gives the three parts, escaped and unquoted, as the JSON output carries them.
A short witness can look harmless on the engine and still be the attack. PCRE2 looks for the last code unit every match needs (; in /color\s*:\s*[^;]+;/) before it tries the pattern, and gives up at once on a subject without it, but only on a subject shorter than a cap: 5,000 code units for an anchored pattern, 5,000,000 for an unanchored one (PCRE2 10.49). Past it the search is skipped and the cost is paid. Measured without the JIT, /^color\s*:\s*[^;]+;/ on its witness "color:" . " " x n takes 0.00 ms at 4,996 bytes, 6.4 ms at 5,016 and 75 to 200 ms at 16,006; /color\s*:\s*[^;]+;/ 0.16 ms at 4,999,006 bytes, and was stopped after 8 seconds at 5,000,106. When no failing subject can hold that code unit (any ; lets [^;]+; match), the witness is still the attack: it needs a subject past the cap, which PHP’s default post_max_size of 8M lets in. The verdict stays proven.
Confirmed mode
ReDoS analysis defaults to theoretical mode: the pattern is read, never run. Confirmed mode runs the patterns at or above the threshold on the running PCRE, without the JIT, a pattern holding (*SKIP:NAME) aside, which is replayed under the JIT as PHP runs it by default, and under the limits of ConfirmationOptions (backtrack limit 100,000 by default):
- an exponential witness is replayed: built with one pump, then two, up to 64, until
preg_match()fails. PCRE gives up at once on a subject that lacks a literal every match needs, so the replay tries several suffixes (the bare one, the shortest one the loop cannot take, and that one followed by each required literal) and publishes the one that reproduced. Each is then tried once more at 5,000 bytes or just past, where PCRE2 stops looking for the code unit an anchored pattern requires (#^<iframe(?:"[^"]*"|'[^']*'|[^>])*>#ireproduces only there: its witness holds no>). When none reproduced, each is replayed again with a literal every match ends with written ahead of the attack: an unanchored pattern is looked for that code unit up to 5,000,000 bytes, and a suffix holding it may let the attempt match (/([\d\D]+)+!/reproduces only as"!" . "\"" x n). Only a failure on the backtrack limit counts as reproduced; the replay stops at a fixed amount of work, and then reportsreplayed: false; - a polynomial verdict is not replayed: the backtrack counter does not measure polynomial work, and a timing would depend on the machine. It is still reported, with
replayed: null; - a heuristic verdict is run on inputs of growing length: a run of a character the culprit starts with, then one it cannot take, then the last code unit every match requires when the pattern has one (
:in/^(x)?(?:\w+\s?)+:\1/), which PCRE2 looks for before it tries the pattern. A risk that needs another input, a backreference repeating what a group read or two alternatives sharing a prefix, is not reproduced on it: confirmed mode drops it where theoretical mode warns. Each length runsiterationstimes and stops when their average passestimeoutMs; a call already running is never cut, the PCRE limits bound it.
When the running PHP cannot set the limits of the replay (ini_set() in
disable_functions, or a limit fixed by php_admin_value), or cannot turn
on the JIT a pattern holding (*SKIP:NAME) is replayed under (pcre.jit
fixed by php_admin_flag), nothing is replayed: the verdict keeps its severity and
its proof, replayed is null, and the confirmation’s evidence reads
engine limits unavailable. A proven exponential pattern is still reported
at its severity, so it cannot slip under a threshold. A heuristic verdict
whose replay was skipped is reported by regex lint as a warning, its
message noting that it was not replayed and why.
vendor/bin/regex analyze '/(a+)+b/' --redos-mode=confirmed
[3/5] ReDoS analysis
Status : Exponential backtracking (proven)
Severity : CRITICAL (score 10)
Mode : CONFIRMED
Confidence : HIGH
Attack: "a" x n . "!b"
Replayed on PCRE2 10.49: preg_match fails from length 18 (backtrack_limit 100000, JIT off).
Hotspot: 1-3
The length counts the bytes of the replayed input, here 17 a, the ! and the b. The suffix !b is what makes PCRE run the loop: without the b it would give up at once, and without the ! the pattern would match.
The line names the call form the replay ran: preg_match fails when the
witness reproduces with $matches, and preg_match() without $matches fails
for the patterns that only blow up on PHP’s second try — an empty first match
makes preg_match() retry the offset with NOTEMPTY_ATSTART | ANCHORED when
no $matches was passed. The analysis models both forms; a verdict is only
replayed the way it was proven.
When the replay never fails, the verdict stays and its confidence stays medium:
vendor/bin/regex analyze '/^(-?[a-z]+){1,7}\.json$/i' --redos-mode=confirmed
Status : Exponential backtracking (proven)
Severity : CRITICAL (score 10)
Mode : CONFIRMED
Confidence : MEDIUM
Model: {1,7} at offset 1 analysed as {1,} (its copies read the same input in two ways)
Attack: "-AA" x n . "!.json"
Not reproduced on PCRE2 10.49 (PCRE's optimisations defuse it).
Here the model read {1,7} as {1,}; PCRE, held to seven copies, never reached the backtrack limit on the replayed inputs.
In PHP:
use PHPRegex\Redos\RedosAnalyzer;
use PHPRegex\Redos\RedosMode;
$analysis = (new RedosAnalyzer())->analyze('/(a+)+b/', mode: RedosMode::Confirmed);
echo $analysis->witness->render(), "\n"; // "a" x n . "!b"
var_dump($analysis->replayed); // bool(true)
echo $analysis->confidence->value, "\n"; // high
echo $analysis->confirmation->samples[0]->inputLength, "\n"; // 18
echo $analysis->confirmation->samples[0]->pregError, "\n"; // Backtrack limit exhausted
Only a verdict the engine reproduced, or a proven one it could not replay because ini_set() is disabled or refuses a limit, at high or above, is an error: it makes analyze, debug and lint exit with 1. A theoretical verdict is a warning, whatever its severity, so no build turns red from a theoretical verdict, nor from one the engine ran without reproducing it (a lint run still fails on a pattern that does not compile, or on a lint rule of error severity).
Severity and thresholds
Severities are ordered safe < low < unknown < medium < high < critical (RedosSeverity::rank()). A threshold is low, medium, high or critical; a pattern is reported at or above it. The default is high everywhere: the linter, Symfony, Laravel, PHPStan and the language server.
A proven quadratic pattern (/\d+\d+$/, /(\w+)(\w+)$/) is medium: below the default thresholds. Lower the threshold to medium to see them.
The cost of an unanchored search
The verdict is about one match attempt. An unanchored preg_match() may start a new attempt at each later position of the subject until one matches; PCRE2 skips the positions it can rule out. When the attempt is proven linear, the analysis also looks for a search-cost witness: a prefix, a run repeated n times, then a breaker, such that every attempt started inside the run reads to its end and then fails. The search then costs about n²/2 steps in PCRE2’s interpreter, and preg_match_all(), preg_replace() and preg_split() retry the same way. The prefix, often empty, is there when the first attempt would match the bare run: the trim regex /^\s+|\s+$/ matches " " x n at once, not "!" . " " x n . "!". The breaker holds the last code unit PCRE2 requires (> for /\s*=>/, b for /a+b|cb/, where every alternative ends with it): PCRE2 gives up at once on a subject without it. Measured with PHP 8.4.26 and PCRE2 10.49:
| pattern | attack | pcre.jit=0 |
pcre.jit=1 |
|---|---|---|---|
/\s+$/ |
" " x n . "x" |
123, 497, 1,992 ms for n = 5,000, 10,000, 20,000 | 1.9 ms for n = 800,000 |
/^\s+\|\s+$/ |
"!" . " " x n . "!" |
491, 1,963 ms for n = 10,000, 20,000 | 4.0 ms for n = 800,000 |
/a+b/ |
"a" x n . "cb" |
24, 97 ms for n = 10,000, 20,000 | 0.0 ms |
/(?:ab)+c/ |
"ab" x n . "dc", 5,000 and 10,000 characters |
51, 201 ms | 3.5, 13.8 ms |
/(?:a\|b)+c/ |
"ab" x n . "dc", 5,000 and 10,000 characters |
331, 1,325 ms | 27.5 ms, then false (“JIT stack limit exhausted”) |
/^\s+$/ |
" " x n . "x" |
0.2 ms for n = 20,000 | 0.0 ms |
The cost is stated for the interpreter: pcre.jit=0, a PHP built without JIT, or a pattern that starts with (*NO_JIT). The JIT may avoid it for some patterns, here every loop on one character, not for all. pcre.backtrack_limit does not stop it: the limit counts each attempt apart, so with the default limit /\s+$/ spends two seconds on 20,000 spaces and returns 0 without an error; it trips only when one attempt exceeds it.
An attempt tied to the start of the search is immune when every alternative is: ^ without m, \A, \G, the A modifier, and a leading .* under s (PCRE2 anchors it; so is a leading class of every character without /u, such as [\s\S]*, and under /u a class whose characters and ranges cover every code point, the surrogates included, such as [\x00-\x{10FFFF}]*, but not [\s\S]*, where \s and \S are Unicode properties, nor [\x00-\x{D7FF}\x{E000}-\x{10FFFF}]*), as are ^ under m and a leading .* without s when the run cannot hold a newline of the pattern’s convention. An option the pattern opens with does not change that, but two: under (*NO_DOTSTAR_ANCHOR) PCRE2 ties a leading .* neither to the search start nor to line starts, and under (*NO_START_OPT) it still anchors one under s but starts one without s at every position, so /(*NO_DOTSTAR_ANCHOR).*[xy]/s and /(*NO_START_OPT).*[xy]/ are quadratic. Two more decide which attempts may end on an empty match: under (*NOTEMPTY) none may, so /(*NOTEMPTY)(?:a+\d)?/ tries a+\d at every position of "a" x n and is quadratic, where /(?:a+\d)?/ matches the empty string at once; under (*NOTEMPTY_ATSTART) only the attempt at the search start may not, so /(*NOTEMPTY_ATSTART)(?:^|a+b)/, whose empty match holds at the subject’s start alone, is quadratic, and /(*NOTEMPTY_ATSTART)(?:a+\d)?/, which matches the empty string at the next position, is not reported. A match \K leaves empty is empty too, since \K sets the start of the match where it stands: /(*NOTEMPTY)a+\K/ gives back every a+ at every position of "a" x n and is quadratic, where /a+\K/ matches the empty string at the run’s end at once, and under (*NOTEMPTY_ATSTART) that empty match stands past the search start, so /(*NOTEMPTY_ATSTART)a+\K/ is not reported. A run that gives nothing back is read all the same: /(*NOTEMPTY)a++\K/ and /(*NOTEMPTY)(?>a+\K)/ read the rest of the run at every attempt before the refusal, and are quadratic too. A possessive or atomic .* under s, or a class PCRE2 reads as the same any character, jumps to the end of the subject in one step: a run read through it costs nothing, a run another loop reads still does (/\s+$|x.*+y/s is quadratic). A bounded repeat above 16, such as \s{1,100}, reads at most its bound per attempt: no run is read through it. A witness is looked for only when one attempt is proven linear: a worse per-attempt verdict already covers the search. When none is found, search_cost is null, which does not prove the search linear: the search proof reports a run through a lookaround, or through an atomic body it keeps with every way through it, only once confirmed mode replayed it, never a run some attempt may match inside, and stops at the analysis budget.
The result is RedosAnalysis::$searchCost, a RedosSearchCost (degree 2, the prefix, the run and the breaker, replayed; build($n) gives the attack, render() writes it), and the search_cost key of the JSON output. The severity is that of a proven quadratic attempt, medium, below the default thresholds, and it is a warning, never an error:
regex lint --redosreports it asregex.lint.redos.searchfrom--redos-threshold=medium(orchecks.redos.thresholdset tomediuminregex.json);--disable-rule=regex.lint.redos.search, or"redos.search": falseinchecks.lint.rules, turns it off. The per-attempt verdict keeps its own id,regex.lint.redos.- PHPStan reports it as
regex.redos.search, with the messageQuadratic search (ReDoS): <pattern>, fromthreshold: medium.
vendor/bin/regex lint app --redos --redos-threshold=medium -v on preg_match('/\s+$/', $subject); prints the whole hint:
app/Whitespace.php:3:12
→ /\s+$/
WARN Quadratic search: one attempt is linear (proven); an unanchored search is quadratic in PCRE2's interpreter (pcre.jit=0, a build without JIT, or (*NO_JIT)); the JIT may avoid it for some patterns. Severity: MEDIUM.
↳ Attack: " " x n . "!". pcre.backtrack_limit does not stop it: the limit counts each attempt apart. preg_match_all(), preg_replace() and preg_split() retry the same way. Anchor the pattern when every match starts at a known place (^, \A, \G or the A modifier), or bound the length of the run.
In confirmed mode, when the threshold is medium or lower, the witness is replayed without the JIT: replayed says whether an attempt started further from the end of the run takes more steps. The JIT is not measured: some pattern and subject pairs crash PHP under it (PCRE2 10.40 to 10.49), so the analysis never runs your pattern with it; the table above is how it fared on these probes, not a verdict. The step counter sees nothing inside an atomic or possessive repeat of a single character set, such as /a++b/, so the replay runs your pattern with each character a repeat reads in a group of its own, /(?:a)++b/, which changes no match and which the counter sees at each character: /a++b/, /(?>a+)b/ and /(*NOTEMPTY)a++\K/ are replayed, and /(*NOTEMPTY)(?>a+\K)/, whose atomic body the model keeps with every way through it, is reported once replayed. A repeat of every character that PCRE2 moves to the end of the subject in one step, as .*+ under s, stays as written. Where \Q may quote such a group, or where its ?, : or ) is the delimiter, the pattern is replayed as written, and a witness through such a repeat, which the model reads exactly, stays reported with replayed: false. A witness that crosses a lookaround is reported only once that replay confirms it, and a pattern holding \G, which holds wherever the replay pins an attempt, is never confirmed that way. The replay counts under the backtrackLimit and recursionLimit of the ConfirmationOptions you pass, and leaves your settings as it found them: where those limits stop the count before it ends, or ini_set() is disabled, a witness the model reads exactly stays reported with replayed: null, and one that crosses a lookaround, which needs the replay, is not reported.
The search of the functions that look for every match
preg_match_all(), preg_replace(), preg_filter(), preg_replace_callback(), preg_replace_callback_array() and preg_split() go on after each match. After an empty match PHP tries the same offset again with PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED, then moves one character on. A pattern that matches the empty string at each position of a run, and whose retry there reads to the end of the run, then costs those functions a number of steps quadratic in the run, where preg_match() stops at the first empty match. /(?:a+\d)?/ is the type. Measured with PHP 8.4.28 and PCRE2 10.49 on "a" x n:
| call | pcre.jit=0, n = 2,000 / 4,000 / 8,000 / 16,000 |
pcre.jit=1 |
|---|---|---|
preg_match() |
0.01 ms | 0.01 ms |
preg_match_all() |
2.3, 8.6, 34, 131 ms | 1.8, 6.8, 27, 106 ms |
preg_replace() |
2.2, 8.8, 35, 131 ms | 1.8, 6.8, 28, 109 ms |
preg_split() |
2.3, 8.9, 33, 127 ms | 1.8, 7.1, 28, 106 ms |
preg_replace() with a limit of 1 |
0.02 ms | 0.02 ms |
The JIT does not avoid it. PCRE2’s JIT takes no PCRE2_ANCHORED at match time, so the retry always runs in the interpreter, and each call of the loop starts afresh. preg_grep() makes no retry, and PREG_SPLIT_NO_EMPTY does not change the matching. A limit argument bounds the loop. An offset argument only shortens the part of the subject the loop reads.
When the search of preg_match() has no witness, the analysis looks for this one. It is RedosAnalysis::$everyMatchSearchCost, a RedosSearchCost, and every_match_search_cost in the JSON output. The analysis reads the pattern as each retry runs it: every attempt refuses an empty match at its own start. The pattern must also match the empty string inside the run, so that preg_match() stops there.
Each search of the loop starts where the last match ended, so \G, the A modifier and a leading .* tie nothing there. /\G(?:a+\d)?/ and /(?:a+\d)?/A are quadratic in preg_match_all(): 2.5, 9.5, 37, 144 ms and 2.3, 8.8, 35, 136 ms. ^ without m and \A hold at the subject’s start alone, and protect.
The patterns that stay linear are those whose retry does one of these:
- takes the rest of the run at once, as
/a*/does; - reads one character at most, as
/x?/,/(?=a)/,/\b/and/$/do; - reads a bounded run, as
/(?:a{1,50}\d)?/does.
regex lint and PHPStan report it as the search cost: regex.lint.redos.search, and regex.redos.search in PHPStan with the same message, Quadratic search (ReDoS): <pattern>. They report it at the calls that run such a loop: the six functions, their Safe\ drop-ins and the composer/pcre methods that call them, unless a literal limit bounds the call. The language server does the same.
A preg_match() call, and a pattern analysed with no call, keep the verdict of one search. The severity, the threshold, the switches and confirmed mode are those of the search cost above. In confirmed mode the step replay pins the retry, (*NOTEMPTY_ATSTART) with the A modifier, without the JIT.
vendor/bin/regex lint app --redos --redos-threshold=medium on $fields = preg_split('/(?:[^,]*,)?/', $line); prints:
app/Fields.php:3:22
→ /(?:[^,]*,)?/
WARN Quadratic search after an empty match: one attempt is linear (proven), but preg_split() finds an empty match at
each position of the run and, as PHP does after every empty match, tries that position again for a non-empty
one, which reads to the end of the run; PHP runs that retry in PCRE2's interpreter, whatever pcre.jit.
Severity: MEDIUM.
↳ Attack: "!" x n.
↳ pcre.backtrack_limit does not stop it: the limit counts each call apart.
↳ preg_match() and preg_grep() stop at the first match and make no such retry.
↳ Make every match read at least one character, or bound the length of the run; ^ or \A before every
alternative stops it, \G and the A modifier do not.
The extractor reports a pattern that several calls read, as a constant or a variable, once, at its first call, and the cost follows that call.
A match that is short but not empty costs the same loop the same way and is not reported, as in /a*b|a/ above or /a(?:a+\d)?/.
Outside the model: heuristics and budget
A pattern holding a construct the model does not cover is judged by the structural heuristics, and says so:
vendor/bin/regex analyze '/(a)\1+$/'
Status : Potential backtracking (heuristic)
Severity : MEDIUM (score 5)
Mode : THEORETICAL
Confidence : MEDIUM
A condition that asks whether a group is set, (?(1)…) or (?(<name>)…), or whether a recursion runs, (?(R)…), reads no character: the heuristics read it neither as a backreference nor as a subroutine call. /((?(1)|b))+/, which PCRE2 reads in 5 steps whatever the length of the subject, gets no backreference finding.
A backreference to a group of variable length, in a loop, is critical, unless the body of the loop reads its input one way: each alternation chooses its branch by the first character, read in the case the engine reads it, and each count is fixed. The PCRE2 manual’s /^(a|b\1)+$/ is then rated as any loop is, medium, and PCRE2 reads it in a number of steps that grows with the subject: 3,004, 6,004 and 12,004 on 1,000, 2,000 and 4,000 a and a !; so is /^(a|b\1)+$/i. Under i, /^(a|A\1)+$/i chooses between its branches at each letter, and stays critical.
A recursion into the whole pattern that the attempt tries first, before it reads a character, as in /((?R)?a?)+/, enters the pattern again where it started. PCRE2 stops the match there: preg_match() returns false on every subject the engine runs the pattern on, whatever its length, from PCRE2 10.39 to 10.49. Without the JIT, preg_last_error() is PREG_INTERNAL_ERROR, a recursion loop found at the 7th step on PCRE2 10.49; with it, PREG_JIT_STACKLIMIT_ERROR, once the JIT stack runs out, in about 0.01 ms at 1, 1,000 or 100,000 letters. Nothing after the recursion runs and nothing backtracks, so the verdict is low, with one finding that says so. A recursion after a step that reads a character (/a(?R)?b/), one tried last (/(?R)??a/), or one behind an anchor or a lookaround keeps the heuristics’ verdict.
An atomic group, a possessive repeat, or a repeat whose body ends with (*COMMIT), (*PRUNE) or (*SKIP) stops the backtracking only once its body has matched: until then PCRE backtracks inside it as anywhere. The heuristics leave alone the loops that end such a body, as in /^(?:(?:a+)+(*COMMIT))+b/, and read every other loop in it as they read any loop: /(?>(a+)+b)/, /^(?:(?:a+)+b)++/ and /^(?>(\w+\s?)+:)/, which exhaust the backtrack limit on 20 a and a ! before the last character, are critical. An item that may match nothing, as \s? there, keeps no two iterations of a loop apart; a loop that ends an iteration is kept apart from the next one by a first character it never takes: in Friedl’s /(?C1)\/\*[^*]*\*+([^\/*][^*]*\*+)*\//, the run of stars never takes the [^\/*] that starts the next iteration. A verb stops nothing where PCRE ignores it: a (*SKIP:NAME) with no (*MARK:NAME) that PCRE finds going back from it, or a verb inside a lookaround or an atomic group, which acts there alone. A mark written before the skip is not found when it stands inside a lookaround or an atomic group, which PCRE never goes back into once they have matched, or on a branch the match may not take. /^(?:\w+\s?(*SKIP:n))+:/, /^(?=(*MARK:n))(?:\w+\s?(*SKIP:n))+:/ and /^(?:\w+\s?(?=(*COMMIT)))+:/ are critical, /^(?:(*MARK:n)\w+\s?(*SKIP:n))+:/ is safe.
Where the model does not decide, the heuristics read a count of more than 16, which the model would read as a loop, as a loop, and a count of variable length inside a loop as a nested loop: /^(?:a|a){1,40}(*MARK:y)$/, /^(?:\d{1,3}\.?){1,30}(*MARK:y)$/ and /^(?:(?1)){1,30}(a|a)$/ exhaust the backtrack limit on 24 characters and a !, and are critical. /^(?:a|a){1,16}(*MARK:y)$/ never reaches the limit, and a dot after each run of /^(?:\d{1,3}\.){1,30}(*MARK:y)$/ keeps the runs apart.
An alternation in a loop whose branches may start with the same character is critical, unless the loop, read alone before an end that never matches, is proven linear: /^((?:a|ab)+)\1$/ reads ab one way, and is rated as any loop is, medium, while /^((?:a|ab|b)+)\1$/ reads it two ways and stays critical. A loop holding an anchor, an assertion or a lookaround, or a reference or a call to a group outside it, is not put to that proof. The loops put to it share one budget of steps, the one the proof of the whole pattern has: past it, a loop keeps the finding. A branch whose first characters the heuristics cannot list, a backreference or a Unicode property, may start as any other branch does, in whichever order the branches are written: /^(a)(?:a|\1)+$/ and /^(a)(?:\1|a)+$/ are both critical, and so are /^(["'])(?:[a-z]|\p{Ll})+\1$/u and its branches swapped.
The heuristics read the characters PCRE reads, written as escapes or not, above ASCII too, under PCRE2’s own tables, the ones PHP compiles with under the C locale. Under another locale’s tables they read the same bytes a pattern writes and a negated class takes, and what those tables decide as they give it: the bytes of \d, \s, \w and the POSIX classes without /u, [:lower:] and [:upper:] taking every letter under i as the engine reads them, and the other case of a character under i, of an ASCII one under /u too. So "/^(x)\\w+\xE9+\\1$/", "/^(x)[[:alpha:]]+\xE9+\\1$/" and "/^(x)\xC9+\xE9+\\1$/i", with raw bytes, are safe under C and medium under fr_FR.ISO8859-1, where \xE9 is a word character and a letter and \xC9 its capital, "/^(x)\\W+\xE9+\\1$/" is medium under C and safe there, and /^(x)a+B+\1$/i is safe under both. Without /u a character is a byte: a UTF-8 sequence spelled byte by byte beside an ASCII class, /^((?:[a-z]|[\xC2-\xDF][\x80-\xBF])+)%?\1/, starts apart from it and is medium, while [^a], \D, \W and \S take every byte they do not name, and the dot every byte but the newlines of the convention in force unless s is set, so /^((?:[^a]|é)+)\1$/ and /^((?:.|é)+)\1$/ are critical. Under (*ANY) the next line, \x85, is a newline the dot does not take, whichever branch comes first: /(*ANY)^((?:.|\x85)+)\1$/ and /(*ANY)^((?:\x85|.)+)\1$/ are not critical, and both are under s. Under /u a character above ASCII is known by the byte it starts with, at the end of a repeat as at the start of the next: /^((?:é+é)+)\1$/u is critical, as /^((?:a+a)+)\1$/ is. Under i, set by the modifier, an option setting or a group, a letter meets its other case, and where (?-i) turns i off again it does not: /^((?:a|A)+)\1$/i and /^((?:a|(?-i:A))+)\1$/i are critical, /(?i)^((?-i)(?:a|A)+)\1$/ is not, and [^a] leaves A out. Under iu k meets the Kelvin sign and s the long s, unless r keeps ASCII apart, and a character above ASCII may meet one that starts with any byte; under (*UCP) a Latin-1 letter meets its other case, which PCRE2’s own tables leave apart without it. An option setting reads nothing: the items around it meet as if it were not there, so /^((?i)a+)\1$/ is read as /^(a+)\1$/i. An item that may match empty, x?, x*, x{0,3} or (?:|x), and a lookaround, which reads nothing, keep a loop apart only with what stands past them: the heuristics read on to the first item that always reads a character, and each item on the way must start or end apart from the loop. Past eight such items, nothing further keeps a loop apart, of the loops it meets further only the first is named, and past 1,024 such pairs in one sequence the loops further are taken to meet, so that a run of loops that may all match empty costs work that grows with its length, not with its square, and /^(x)(?:ba+c?d?e?f?g?h?i?j?k?a+z)+\1$/ is high, as with fewer items between the two a+. /^(x?a+)\1$/ is read as /^(a+)\1$/, medium, and /^(?:(?!x)a+)*$/ as /^(?:a+)*$/, critical, while /^(xa+)\1$/, /^(a+[^a]a+)\1$/ and /^(a+(*COMMIT))\1$/, where the engine never goes back past the verb, are safe.
A subroutine call in a loop runs the group it calls at each iteration: the heuristics read that group as if it stood in place of the call, and so they read a call outside any loop, where nothing written around the group protects it: /^(?:(?>x((?:a+)+))|y(?1)$)/, whose nested loops the atomic group keeps safe where they are written, is critical where the call runs them. /^(?:(?1))+(a|a)$/ and /^(?:(?&w)\s?)+$(?(DEFINE)(?<w>[a-z]+))/, which exhaust the backtrack limit on 24 letters and a !, are critical, while /^(?:(?&w),)+$(?(DEFINE)(?<w>[a-z]+))/ keeps its runs apart. A call is read again wherever it runs, a call a DEFINE block reaches first included: /(?(DEFINE)(?<wrap>(?&atom))(?<atom>a|a))^(?&wrap)+$/ is critical. A call met again while the group it calls is being read is a recursion, and is not read again. A branch that is a call starts as the group it calls: /^(?:[a-z]|(?&c))+$(?(DEFINE)(?<c>[a-z0-9]))/ and /^(a)(?:a|(?1))+$/ read a letter both ways and are critical, /^(?:-|(?&c))+$(?(DEFINE)(?<c>[a-z0-9]))/ is not. A branch that recurses into the whole pattern is left out and the other branches are still compared: /^x(?:a|a|(?R))+$/ is critical.
The model works within a budget counted in states and steps, never in time, so the same pattern gets the same verdict on every machine. Past it, the heuristics decide:
vendor/bin/regex analyze '/^(?:(?:\d{1,16}\.){1,16}\d{1,16})(?:,(?:\d{1,16}\.){1,16}\d{1,16}){1,16}$/'
Status : Potential backtracking (heuristic)
Severity : LOW (score 2)
Mode : THEORETICAL
Confidence : LOW
Note: analysis budget exceeded, the heuristics decided
RedosOptions sets the budget on a RedosAnalyzer you build yourself:
| option | default | role |
|---|---|---|
maxStates |
2000 |
character-reading states the pattern’s automata may hold |
maxSteps |
250_000 |
states created, product pairs visited and character classes scanned, the memory of the search charged by size |
boundedRepeatCutoff |
16 |
largest bounded-repeat maximum unrolled; past it, {m,n} is analysed as {m,}, an exact count {n} kept |
use PHPRegex\Redos\RedosAnalyzer;
use PHPRegex\Redos\RedosOptions;
$analyzer = new RedosAnalyzer(options: new RedosOptions(maxStates: 100, maxSteps: 5_000));
$analysis = $analyzer->analyze('/^(?:\d{1,16}|[a-f]{1,16})+$/');
echo $analysis->proof->value, "\n"; // budget_exceeded
echo $analysis->headline(), "\n"; // Potential backtracking (heuristic)
With the default budget, the same pattern is Exponential backtracking (proven). The budget bounds the memory of the analysis as well as its work: a pattern built to exhaust it ends with budget_exceeded.
Regex::redos() uses the default budget. The configuration files have no key for it in 2.0.
A ceiling without a witness
A verdict says what an attack costs, from the input that mounts it. When the model finds an
ambiguity but no input to drive it, as in /(.*)'(.*)'(.*)/i, the verdict stays
unknown — and a ceiling may still be proven. RedosAnalysis::$upperBoundDegree is the
degree d of a bound n^d on the steps of one match attempt:
use PHPRegex\Parser\RegexParser;
use PHPRegex\Redos\RedosAnalyzer;
$analyzer = new RedosAnalyzer(RegexParser::create());
$analyzer->analyze("/(.*)'(.*)'(.*)/i")->upperBoundDegree; // 3: at most n^3, attack or not
$analyzer->analyze('/^a+b$/')->upperBoundDegree; // 1
$analyzer->analyze('/(a+)+$/')->upperBoundDegree; // null: no polynomial ceiling
The argument: when no state of the pattern’s automaton has two distinct paths back to itself
on one word, two states of a strongly connected part are joined by at most one path on any
word (Weber and Seidl, 1991). A path then crosses at most c loops of the automaton, and an
attempt follows at most n^c partial paths, which bounds a backtracking matcher’s search
tree. The automaton reads at least what the pattern reads, bounded repeats it treats as
unbounded included, so the bound holds for the pattern.
It is an upper bound, worded “at most”: /^(?:a|b)*c+d*$/ gets 3 though its attempts are
linear. It is null when such a state exists — witnessed or not — and when the pattern
leaves the model. Never below a proven degree, it turns about a fifth of the corpus
patterns left unknown into ones with a polynomial ceiling.
The JSON carries it as upper_bound_degree.
Reading the result
Next to severity, score, confidence, findings, hotspots, recommendations and confirmation, RedosAnalysis carries:
| field | type | meaning |
|---|---|---|
complexity |
RedosComplexity |
linear, polynomial, exponential, or unknown when nothing was proven |
degree |
?int |
the degree of a polynomial verdict, 2 or more; null otherwise |
proof |
RedosProof |
proven, heuristic, budget_exceeded or not_analyzed |
witness |
?RedosWitness |
the attack of a proven vulnerable verdict |
replayed |
?bool |
whether the witness made the running PCRE fail; null when no replay was attempted |
abstractions |
list<string> |
what the model analysed differently from the pattern as written |
pcreVersion |
string |
the PCRE2 release the verdict was computed with |
analysisVersion |
string |
RedosAnalyzer::ANALYSIS_VERSION, raised when the model changes |
searchCost |
?RedosSearchCost |
the witness of a quadratic unanchored search, looked for when one attempt is proven linear; null when none was found, never a proof of a linear search |
findings and hotspots come from the structural heuristics, severity from the proof when there is one. A proof that one attempt is linear settles the verdict, so the result carries none of the heuristics’ output: no findings, hotspots or recommendations, and no vulnerablePart, trigger, falsePositiveRisk, suggestedRewrite or culpritNode. /a+/ and /^(?:a|ab)+c/, which the heuristics alone call medium and critical, are safe (proven) with none of them, so analyze and debug print no hotspot, culprit or finding and generate no attack subject. A proven vulnerable verdict and a heuristic one keep them: they point at the loop at fault.
isSafe() keeps its meaning (safe or low); isProvenSafe() is true only for a proven linear verdict:
$analyzer = new RedosAnalyzer();
$analyzer->analyze('/^[a-z0-9-]+$/')->isProvenSafe(); // true: safe (proven)
$analyzer->analyze('/(a)?(?(1)a|b)/')->isSafe(); // true: no risk found (heuristic)
$analyzer->analyze('/(a)?(?(1)a|b)/')->isProvenSafe(); // false
The JSON output (vendor/bin/regex analyze --format=json, debug --format=json, lint --format=json) carries the same fields in snake case (pcre_version, analysis_version, search_cost, upper_bound_degree), and the witness as its three escaped parts; the JSON output reference lists every key:
"complexity": "exponential",
"degree": null,
"proof": "proven",
"witness": {
"prefix": "",
"pump": "a",
"suffix": "!"
},
"replayed": true,
"abstractions": [],
"pcre_version": "10.49",
"php_version": "8.4.26",
"analysis_version": "1",
"search_cost": null,
"upper_bound_degree": null
On real code
On the repository’s corpus of real-world patterns, the model proves the class of about 95 % of them; the heuristics decide for about 5 %, mostly patterns outside the model, a few with an ambiguity the analysis could not witness, almost none because of the budget. Analysing a pattern takes about a third of a millisecond at the median and about 5 ms at the 99th percentile.
In confirmed mode, about seven in eight of the corpus’ proven exponential verdicts reproduce on PCRE2; the others are reported as not reproduced, through a bounded repeat analysed as unbounded or a loop that PCRE’s optimizations defuse.
Using PHPRegex
CLI
# Theoretical mode (default)
vendor/bin/regex analyze '/(a+)+$/'
# Replay the attack on the running PCRE
vendor/bin/regex analyze '/(a+)+$/' --redos-mode=confirmed
# Heatmap, findings and attack
vendor/bin/regex debug '/(a+)+$/'
# Every pattern of a code base
vendor/bin/regex lint src/ --redos --no-lint --no-optimize
See the CLI guide for the output of each command.
PHP
use PHPRegex\Toolkit\Regex;
$analysis = Regex::create()->redos('/(a+)+b/');
echo $analysis->severity->value, "\n"; // critical
echo $analysis->headline(), "\n"; // Exponential backtracking (proven)
echo $analysis->witness->render(), "\n"; // "a" x n . "!b"
How to Report a Vulnerability Responsibly
Before filing a security issue:
- Run confirmed mode, and keep the attack and the replayed length it prints.
- Include the pattern, the input lengths, the timings, the JIT setting and the PCRE limits.
- Verify the issue in the real code path (not just synthetic tests).
See SECURITY.md for reporting channels.
Repairs with proofs
RedosRepairer rewrites a pattern open to catastrophic backtracking and keeps the rewrites
the model proves linear, each with what the automata prove about it:
use PHPRegex\Optimizer\RedosRepairer;
$repairs = (new RedosRepairer())->repair('/href="([^"]+)*"/');
$repairs[0]->pattern; // '/href="([^"]*)"/'
$repairs[0]->sameSubjects; // true: the automata prove it matches the same subjects
$repairs[0]->sameMatches; // false: on 'href=""', $1 is '' where it was unset
$repairs[0]->isCertified(); // true: same subjects, proven linear
It tries a repeat of a repeat flattened, (?:a+)+ to a+; the optimizer’s own rewrite;
each greedy quantifier made possessive, then all of them. The rewrites of the quantifiers
under a hotspot of the analysis are tried first, and none is left out: /^\s*(?:\w+\s*)*$/
is repaired though the analysis names no hotspot in it. A rewrite proven to match other
subjects is dropped. One the automata cannot judge stays listed with sameSubjects set to
null, after the certified ones: the possessive forms mostly, as /^(\w++\s?)+$/ for
/^(\w+\s?)+$/, linear for sure, the same subjects for you to check. With ReDoS checks on,
the PHPStan rule prints a certified repair in the tip of the error.
firstRepair() returns the repair repair() offers first, or null. It stops at the first
rewrite certified that writes the same $matches, as none after it can come before it, so
the rewrites after it are not proven: the PHPStan rule asks for that one alone.
(new RedosRepairer())->firstRepair('/^(?:a+)+$/')?->pattern; // '/^a+$/'
Fixing Vulnerable Patterns (Verify Behavior)
These rewrites remove the ambiguity, but can change what the pattern matches or captures. Run the analysis again on the rewrite, and validate it with tests.
Use possessive quantifiers or atomic groups
Vulnerable: /(a+)+b/ Exponential backtracking (proven)
Safer: /a++b/ safe (proven)
Safer: /(?>a+)b/ safe (proven)
Possessive quantifiers and atomic groups never give back what they matched.
Simplify nested repeats
Vulnerable: /(a+)+b/ Exponential backtracking (proven)
Equivalent: /a+b/ safe (proven) (verify captures)
Remove overlapping alternatives
Vulnerable: /(a|aa)+$/ Exponential backtracking (proven)
Safer: /a+$/ safe (proven)
(a|b)+c is not ambiguous, and is proven safe: only alternatives that can match the same text cost anything.
Avoid repeating a group that can match nothing
Vulnerable: /(a*)*$/ Exponential backtracking (proven)
Safer: /a*$/ safe (proven)
(a?)+ is proven safe: PCRE stops repeating a group once an iteration matched nothing.
Separate adjacent quantifiers
Vulnerable: /a+a+$/ Polynomial backtracking, degree 2 (proven)
Safer: /a+$/ safe (proven)
Safer: /a++a+$/ safe (proven) (if the split must be preserved, verify behavior)
Bound your repeats
Vulnerable: /(\d+)+$/ Exponential backtracking (proven)
Safer: /\d{1,10}$/ safe (proven)
Quick Reference: Vulnerable vs Safer (Verify Behavior)
(a+)+ -> a++ or (?>a+)
(a|aa)+ -> a+
(\d+)+ -> \d++ or \d{1,10}
(.+)+ -> .++ or .{1,100}
(a*)* -> a*
a+a+ -> a+ or a++a+
(\w+\d+)+ -> (?>\w+\d+)+
(?>\w+\d+)+ is judged no risk found (heuristic): its atomic body is more than one run over one set, so the model lists it in abstractions and the heuristics decide.
Defense in Depth
- Analyze patterns before they reach production, in CI with
regex lint --redosor PHPStan. - Check the return value of
preg_*forfalse, andpreg_last_error(): a vulnerable pattern fails silently. - Limit the length of untrusted input before matching it.
- Prefer deterministic patterns, possessive quantifiers and atomic groups in hot paths.