Regular Expression Denial of Service (ReDoS) in JS & PHP: Spotting Catastrophic Backtracking
Here is a pattern I keep finding in slug and username validators: /^([a-z0-9]+-?)+$/ . It looks harmless and passes every unit test. Now send it thirty lowercase letters followed by an
What is ReDoS and how do you spot catastrophic backtracking in JavaScript and PHP?
</h2> <p><strong>Direct answer:</strong> ReDoS happens when a backtracking regex engine, like V8's Irregexp in Node.js or PCRE2 behind PHP's <code>preg_*</code> functions, tries exponentially or polynomially many ways to match a crafted input that ultimately fails. Spot it by looking for nested or overlapping quantifiers, then prove it with a growing near-miss input and a timer.</p> <h2>Why the engine explodes
</h2> <p>Both V8 and PCRE2 are backtracking engines. When a match fails, they go back and try every other way the pattern could have consumed the input. That is fine when there is only one way. It is a disaster when the pattern is <em>ambiguous</em>.</p> <p>In <code>^([a-z0-9]+-?)+$</code>, the hyphen is optional, so the string <code>aaaa</code> can be split as <code>aaaa</code>, <code>aaa|a</code>, <code>aa|aa</code>, <code>a|a|a|a</code> and so on. That is 2^(n-1) splits. When the final <code>$</code> fails on the trailing <code>_</code>, the engine tries all of them. Here is what I measured on Node 24:</p> <div class="table-wrapper-paragraph"><table> <thead> <tr> <th>Letters before <code>_</code> </th> <th>Time for one <code>test()</code> </th> </tr> </thead> <tbody> <tr> <td>24</td> <td>98 ms</td> </tr> <tr> <td>26</td> <td>385 ms</td> </tr> <tr> <td>28</td> <td>1,572 ms</td> </tr> <tr> <td>30</td> <td>6,502 ms</td> </tr> </tbody> </table></div> <p>Every two extra characters multiply the time by roughly four. At 40 characters you are looking at hours. Note that a <em>matching</em> input is fast; ReDoS only shows up on near-misses, which is why normal tests never catch it.</p> <p><a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgzfiokz1bs4zylxe4j9a.jpg" class="article-body-image-wrapper"><img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgzfiokz1bs4zylxe4j9a.jpg" alt="Brass maze model under warm light with long shadows, representing the many paths a backtracking regex engine explores" width="800" height="420"></a><br> <em>AI-generated image.</em></p> <h2>The five pattern smells I look for
</h2> <div class="table-wrapper-paragraph"><table> <thead> <tr> <th>Smell</th> <th>Vulnerable example</th> <th>Why it blows up</th> <th>Safe rewrite</th> <th>Growth</th> </tr> </thead> <tbody> <tr> <td><strong>Nested quantifiers</strong></td> <td><code>^([a-z0-9]+-?)+$</code></td> <td>Inner and outer <code>+</code> can split the same run many ways</td> <td><code>^[a-z0-9]+(?:-[a-z0-9]+)*$</code></td> <td>Exponential</td> </tr> <tr> <td><strong>Overlapping alternation</strong></td> <td>A group alternating <code>\w</code> and <code>\d</code>, repeated with <code>+</code> </td> <td>Both branches match the same character</td> <td> <code>^\w+$</code> (one branch)</td> <td>Exponential</td> </tr> <tr> <td><strong>Adjacent overlapping repeats</strong></td> <td> <code>^\w+\w*@</code> or <code>\d+\.?\d*</code> </td> <td>Two quantifiers compete for the same characters</td> <td>Make the boundary mandatory or merge them</td> <td>Polynomial</td> </tr> <tr> <td><strong>Unanchored greedy tail</strong></td> <td> <code>/\s+$/</code> on long whitespace</td> <td>Engine retries from every start position</td> <td>Trim in code, or use <code>trimEnd()</code> </td> <td>Quadratic</td> </tr> <tr> <td><strong><code>.*</code> chains</strong></td> <td><code>.*=.*;.*</code></td> <td>Each <code>.*</code> re-scans what the previous one gave back</td> <td>Use negated classes: <code>[^=]*=[^;]*;</code> </td> <td>Polynomial</td> </tr> </tbody> </table></div> <p>The last two are not academic. The Stack Overflow outage in July 2016 was traced to a whitespace-trimming regex, and Cloudflare's global outage in July 2019 was traced to a WAF rule containing <code>.*(?:.*=.*)</code>. Both were super-linear, not exponential, and both were enough.</p> <h2>Proving it in JavaScript
</h2> <p>I keep a tiny harness and grow the near-miss input until the time curve is obvious:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="c1">// redos-probe.js — run with: node redos-probe.js</span> <span class="kd">const</span> <span class="nx">pattern</span> <span class="o">=</span> <span class="sr">/^</span><span class="se">([</span><span class="sr">a-z0-9</span><span class="se">]</span><span class="sr">+-</span><span class="se">?)</span><span class="sr">+$/</span><span class="p">;</span> <span class="k">for </span><span class="p">(</span><span class="kd">const</span> <span class="nx">n</span> <span class="k">of</span> <span class="p">[</span><span class="mi">20</span><span class="p">,</span> <span class="mi">22</span><span class="p">,</span> <span class="mi">24</span><span class="p">,</span> <span class="mi">26</span><span class="p">,</span> <span class="mi">28</span><span class="p">])</span> <span class="p">{</span> <span class="kd">const</span> <span class="nx">input</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">a</span><span class="dl">'</span><span class="p">.</span><span class="nf">repeat</span><span class="p">(</span><span class="nx">n</span><span class="p">)</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">_</span><span class="dl">'</span><span class="p">;</span> <span class="c1">// near-miss: valid prefix, invalid last char</span> <span class="kd">const</span> <span class="nx">t0</span> <span class="o">=</span> <span class="nx">process</span><span class="p">.</span><span class="nx">hrtime</span><span class="p">.</span><span class="nf">bigint</span><span class="p">();</span> <span class="nx">pattern</span><span class="p">.</span><span class="nf">test</span><span class="p">(</span><span class="nx">input</span><span class="p">);</span> <span class="kd">const</span> <span class="nx">ms</span> <span class="o">=</span> <span class="nc">Number</span><span class="p">(</span><span class="nx">process</span><span class="p">.</span><span class="nx">hrtime</span><span class="p">.</span><span class="nf">bigint</span><span class="p">()</span> <span class="o">-</span> <span class="nx">t0</span><span class="p">)</span> <span class="o">/</span> <span class="mi">1</span><span class="nx">e6</span><span class="p">;</span> <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="nx">n</span><span class="p">,</span> <span class="nx">ms</span><span class="p">.</span><span class="nf">toFixed</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="dl">'</span><span class="s1"> ms</span><span class="dl">'</span><span class="p">);</span> <span class="p">}</span> </code></pre> </div> <p>If the time roughly doubles (or quadruples every two steps), you have exponential backtracking. If it grows with the square of the length, polynomial.</p> <p>For static detection I run two tools:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight shell"><code>npm i <span class="nt">-D</span> eslint eslint-plugin-regexp recheck </code></pre> </div> <p><code>eslint-plugin-regexp</code>'s recommended config includes <code>regexp/no-super-linear-backtracking</code>, which flagged both the slug pattern and a typical hand-rolled email pattern with "exponential backtracking" messages. <code>recheck</code> goes further and generates an attack string. On <code>\s+$</code> it reported <code>vulnerable polynomial</code>, which the recommended lint config did not flag. Use both.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="kd">const</span> <span class="p">{</span> <span class="nx">check</span> <span class="p">}</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">recheck</span><span class="dl">'</span><span class="p">);</span> <span class="nf">check</span><span class="p">(</span><span class="dl">'</span><span class="s1">^([a-z0-9]+-?)+$</span><span class="dl">'</span><span class="p">,</span> <span class="dl">''</span><span class="p">).</span><span class="nf">then</span><span class="p">((</span><span class="nx">r</span><span class="p">)</span> <span class="o">=></span> <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="nx">r</span><span class="p">.</span><span class="nx">status</span><span class="p">,</span> <span class="nx">r</span><span class="p">.</span><span class="nx">complexity</span><span class="p">.</span><span class="nx">type</span><span class="p">));</span> <span class="c1">// vulnerable exponential</span> </code></pre> </div> <h2>Fixing it in JavaScript
</h2> <p><strong>1. Rewrite the pattern to be unambiguous.</strong> This is the real fix. Each character should have exactly one way to be consumed:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight javascript"><code><span class="c1">// BEFORE: ambiguous, exponential</span> <span class="kd">const</span> <span class="nx">slugBad</span> <span class="o">=</span> <span class="sr">/^</span><span class="se">([</span><span class="sr">a-z0-9</span><span class="se">]</span><span class="sr">+-</span><span class="se">?)</span><span class="sr">+$/</span><span class="p">;</span> <span class="c1">// AFTER: hyphen is mandatory between groups, so there is one parse</span> <span class="kd">const</span> <span class="nx">slugGood</span> <span class="o">=</span> <span class="sr">/^</span><span class="se">[</span><span class="sr">a-z0-9</span><span class="se">]</span><span class="sr">+</span><span class="se">(?:</span><span class="sr">-</span><span class="se">[</span><span class="sr">a-z0-9</span><span class="se">]</span><span class="sr">+</span><span class="se">)</span><span class="sr">*$/</span><span class="p">;</span> </code></pre> </div> <p>It accepts the same slugs, and the 30-character near-miss now takes well under a millisecond.</p> <p><strong>2. Cap input length before the regex runs.</strong> A slug longer than 100 characters is invalid anyway. <code>if (input.length > 100) return false;</code> turns any exponential pattern into a bounded one, and it costs nothing.</p> <p><strong>3. Use a linear-time engine where you can.</strong> V8 ships an experimental non-backtracking engine. In Node 24, starting the process with <code>--enable-experimental-regexp-engine</code> enables the <code>l</code> flag:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight shell"><code>node <span class="nt">--enable-experimental-regexp-engine</span> <span class="nt">-e</span> <span class="se">\</span> <span class="s2">"console.log(/^([a-z0-9]+-?)+</span><span class="nv">$/</span><span class="s2">l.test('a'.repeat(100000) + '_'))"</span> <span class="c"># false, in about 7 ms</span> </code></pre> </div> <p>Without the flag, <code>new RegExp('a', 'l')</code> throws "Invalid flags". With it, patterns that need backtracking features are rejected at compile time: I got "Cannot be executed in linear time" for both a backreference <code>(a)\1</code> and a lookahead <code>(?=a)b</code>. There is also <code>--enable-experimental-regexp-engine-on-excessive-backtracks</code>, which falls back to the linear engine after a backtrack threshold (50,000 by default in <code>node --v8-options</code>). Both are experimental V8 flags, so I treat them as defense in depth, not as the fix. For untrusted patterns (search features, user-defined filters), use the <code>re2</code> npm package, which binds Google's RE2.</p> <p><strong>4. Never run user-supplied patterns on the main thread.</strong> If users can submit regexes, run them in a worker with a timeout, or in RE2.</p> <h2>PHP: PCRE fails differently, and that is its own bug
</h2> <p>PHP's <code>preg_*</code> functions use PCRE2. They do not hang forever, because <code>pcre.backtrack_limit</code> (default 1,000,000) caps the work. PCRE2's documentation says this match limit is also applied when the pattern is JIT-compiled (<code>pcre.jit=1</code> is the default), though it is counted differently. When the limit trips, the call fails instead of answering:</p> <ul> <li> <code>preg_match()</code> returns <code>false</code>, not <code>0</code>.</li> <li> <code>preg_replace()</code> returns <code>null</code>.</li> <li> <code>preg_last_error()</code> returns <code>PREG_BACKTRACK_LIMIT_ERROR</code>, and <code>preg_last_error_msg()</code> (PHP 8+) returns "Backtrack limit exhausted". With JIT you may also see <code>PREG_JIT_STACKLIMIT_ERROR</code>.</li> </ul> <p>That is where the security bug lives. Code like <code>if (!preg_match($re, $input))</code> treats <code>false</code> as "no match", and <code>$body = preg_replace($re, '', $body)</code> silently replaces the content with <code>null</code>. Depending on the branch, you get a validation bypass, a sanitizer that does nothing, or data loss. Each call still burns CPU up to the limit, so an attacker can keep PHP-FPM workers busy.</p> <p>I wrap every <code>preg_*</code> call on user input:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight php"><code><span class="k">function</span> <span class="n">safe_preg_match</span><span class="p">(</span><span class="kt">string</span> <span class="nv">$pattern</span><span class="p">,</span> <span class="kt">string</span> <span class="nv">$subject</span><span class="p">,</span> <span class="kt">?array</span> <span class="o">&</span><span class="nv">$m</span> <span class="o">=</span> <span class="kc">null</span><span class="p">):</span> <span class="kt">bool</span> <span class="p">{</span> <span class="nv">$result</span> <span class="o">=</span> <span class="nb">preg_match</span><span class="p">(</span><span class="nv">$pattern</span><span class="p">,</span> <span class="nv">$subject</span><span class="p">,</span> <span class="nv">$m</span><span class="p">);</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$result</span> <span class="o">===</span> <span class="kc">false</span><span class="p">)</span> <span class="p">{</span> <span class="k">throw</span> <span class="k">new</span> <span class="nc">RuntimeException</span><span class="p">(</span><span class="s1">'Regex failed: '</span> <span class="mf">.</span> <span class="nb">preg_last_error_msg</span><span class="p">());</span> <span class="p">}</span> <span class="k">return</span> <span class="nv">$result</span> <span class="o">===</span> <span class="mi">1</span><span class="p">;</span> <span class="p">}</span> </code></pre> </div> <p>PCRE also gives you tools JavaScript does not have. Possessive quantifiers (<code>++</code>, <code>*+</code>) and atomic groups (<code>(?>...)</code>) refuse to give characters back:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight php"><code><span class="c1">// Ambiguous: exponential, will hit the backtrack limit</span> <span class="nv">$bad</span> <span class="o">=</span> <span class="s1">'/^([a-z0-9]+-?)+$/'</span><span class="p">;</span> <span class="c1">// Atomic group: each iteration commits, no re-splitting</span> <span class="nv">$atom</span> <span class="o">=</span> <span class="s1">'/^(?>[a-z0-9]+-?)+$/'</span><span class="p">;</span> <span class="c1">// Unambiguous rewrite: my preferred fix, same in JS and PHP</span> <span class="nv">$good</span> <span class="o">=</span> <span class="s1">'/^[a-z0-9]+(?:-[a-z0-9]+)*$/'</span><span class="p">;</span> </code></pre> </div> <p>Do not "fix" ReDoS by raising <code>pcre.backtrack_limit</code>. That only makes each malicious request burn more CPU before it fails.</p> <h2>ReDoS review checklist
</h2> <ol> <li>Grep for <code>+)+</code>, <code>*)*</code>, <code>+)*</code>, <code>(.*)*</code> and alternations where branches overlap.</li> <li>Run <code>eslint-plugin-regexp</code> and <code>recheck</code> in CI on JS; copy PHP patterns into a JS test file to scan them too, where the syntax is compatible.</li> <li>Probe each user-facing pattern with a growing near-miss input and time it.</li> <li>Cap input length before matching.</li> <li>In PHP, treat <code>false</code>/<code>null</code> from <code>preg_*</code> as an error, never as "no match".</li> <li>Run user-supplied patterns only in RE2 or an isolated worker with a timeout.</li> <li>Paste suspicious patterns into a regex tester with near-miss strings before shipping.</li> </ol> <h2>FAQ
</h2> <h3>Is ReDoS a risk in the browser too?
</h3> <p>Yes, but the impact is smaller: a slow regex freezes the user's own tab. It becomes serious when the same validation code is shared with a Node.js backend, which is common with Nuxt, Next.js and shared validation schemas.</p> <h3>Do Zod or Joi protect me from ReDoS?
</h3> <p>No. Their string validators run whatever regex you pass to <code>.regex()</code> on V8. Some built-in validators have also had ReDoS fixes over the years, so keep those libraries updated.</p> <h3>Does PHP's JIT make ReDoS impossible?
</h3> <p>No. JIT makes matching faster, but a pattern with exponential paths is still exponential. The match limit still applies, so the call fails with an error rather than hanging.</p> <h3>What about Laravel's <code>regex:</code> validation rule?
</h3> <p>It calls <code>preg_match()</code> under the hood, so the same backtracking limits and failure modes apply. Keep patterns unambiguous and add a <code>max:</code> rule before <code>regex:</code> so long inputs are rejected first.</p> <h3>Are lookaheads dangerous?
</h3> <p>Not by themselves. A lookahead containing a nested quantifier can be, and lookaheads rule out V8's linear engine. In JavaScript you can emulate an atomic group with <code>(?=(pattern))\1</code>, but I prefer rewriting the pattern.</p> <h3>How do I find the attacking input for a pattern?
</h3> <p><code>recheck</code> prints one. Otherwise, take a long valid prefix the ambiguous part can split, and end with a character that makes the overall match fail.</p> <p>Next in this series, Part 5 covers subdomain takeover and dangling DNS reconnaissance.</p> <h3>Follow & Connect
</h3> <ul> <li> <strong>Website:</strong> <a href="https://pixelvalut.com/tools/?utm_source=devto&utm_medium=series&utm_campaign=redos-catastrophic-backtracking-regex-security-js-php" rel="noopener noreferrer">PixelValut Tools</a> </li> <li> <strong>YouTube:</strong> <a href="https://www.youtube.com/@pixel-valut" rel="noopener noreferrer">PixelValut (@pixel-valut)</a> </li> <li> <strong>TikTok:</strong> <a href="https://www.tiktok.com/@pixelvalut007" rel="noopener noreferrer">PixelValut (@pixelvalut007)</a> </li> <li> <strong>GitHub:</strong> <a href="https://github.com/ali111887" rel="noopener noreferrer">Muhammad Ali Mughal (@ali111887)</a> </li> <li> <strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/muhammad-ali-m-03434a120/" rel="noopener noreferrer">Muhammad Ali Mughal</a> </li> </ul>Original source
Tags
Related Articles
Continue reading with these similar posts

Elon Musk Is Portrayed on ‘SNL’: “The Worst Thing South Africa Has Ever Done”
Jeremy Culhane plays the character in the show’s latest attempt to assess its relationship with the mogul.

King Charles Was Umbrella-Less but in His Element on Caribbean Tour
In his twilight years, the British monarch is embracing his role as a global statesman, even when that involves heavy rain and difficult questions about his nation’s history.

Cathie Wood 'always feels better when the market is worried' — here's why
The Ark Invest CEO said there was a "wall of worry" gripping markets right now.

IP Companies Spin Books Into Sold-Out Plays, Series and Signature Scents at Taiwan Creative Content Fest
Taiwanese companies laid out how original stories can grow from books into stage plays, series, fragrances and even travel itineraries at a Taiwan Creative Content Fest (TCCF) session on cross-sector

TeamGroup GA Pro 2TB SSD Review: A faltering attempt at a mid-range PCIe 5.0 SSD
Every once in a while we get a drive that comes across our desk that stands out, for good or for

vivo X500 Ultra on track to launch next year, says tipster
Read vivo X500 Ultra on track to launch next year, says tipster and explore its linked sources.