<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/"><channel><title>Denial of Service | FirewallSync</title><link>https://firewallsync.com/tags/denial-of-service/</link><description>Practical cybersecurity writing for engineering teams that ship fast.</description><language>en-us</language><image><url>https://firewallsync.com/icon-512.png</url><title>FirewallSync</title><link>https://firewallsync.com/</link></image><lastBuildDate>Sat, 31 Oct 2026 04:50:00 +0000</lastBuildDate><atom:link href="https://firewallsync.com/tags/denial-of-service/index.xml" rel="self" type="application/rss+xml"/><item><title>User-Supplied Regex: How to Run It Without ReDoS</title><link>https://firewallsync.com/posts/user-supplied-regex-redos-safe-engines/</link><guid>https://firewallsync.com/posts/user-supplied-regex-redos-safe-engines/</guid><pubDate>Sat, 31 Oct 2026 04:50:00 +0000</pubDate><dc:creator>Craig Leslie</dc:creator><category>AppSec &amp; APIs</category><description>Search filters, alert rules, routing configs and log tools all end up accepting regular expressions from users. In a backtracking engine that is a denial-of-service switch you hand to whoever can type a pattern. This guide shows which engines are built for untrusted patterns (RE2, Go, Rust), which ones say plainly that they are not (.NET), what timeouts and possessive quantifiers can and cannot do, and two tested patterns for Python and Node.js.</description><enclosure url="https://firewallsync.com/posts/user-supplied-regex-redos-safe-engines/cover_hu13911530470990273703.jpg" type="image/jpeg" length="0"/><media:content url="https://firewallsync.com/posts/user-supplied-regex-redos-safe-engines/cover_hu13911530470990273703.jpg" medium="image" type="image/jpeg" width="1200" height="630"/><content:encoded><![CDATA[<p><img src="https://firewallsync.com/posts/user-supplied-regex-redos-safe-engines/cover_hu13911530470990273703.jpg" alt="Taut strands of red, orange, pink, purple, yellow and white thread crossing at angles to form a dense grid against a blurred grey background" width="1200" height="630"></p><p>If your product lets users type a regular expression (a log search box, an alerting rule, a URL routing rule, a &ldquo;block messages matching&rdquo; filter), you have handed them a way to burn your CPU. In a backtracking engine, a short pattern and a short input can keep a thread busy for seconds or years. The fix is not a better regex review process, because you are not the one writing the patterns.</p>
<p><strong>The short answer:</strong> run user-supplied patterns on an engine that guarantees linear-time matching (RE2, Go&rsquo;s <code>regexp</code>, Rust&rsquo;s <code>regex</code>), cap pattern length, and reject features those engines do not support instead of quietly falling back. If you are stuck with a backtracking engine, run the match somewhere you can kill it on a deadline.</p>
<h2 id="why-a-backtracking-engine-is-the-problem">Why a backtracking engine is the problem</h2>
<p>Python&rsquo;s <code>re</code>, JavaScript&rsquo;s <code>RegExp</code> (V8&rsquo;s Irregexp) and .NET&rsquo;s default engine are backtracking engines. When a match fails, they back up and try every other way the pattern could have split the input. For most patterns that is fast. For patterns with nested or overlapping repetition, the number of ways to split the input grows exponentially.</p>
<p>OWASP&rsquo;s wiki page on <a href="https://wiki.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS">ReDoS</a> describes an &ldquo;evil&rdquo; regex as one with grouping with repetition where the repeated group contains repetition or overlapping alternation. Its examples include <code>(a+)+</code>, <code>([a-zA-Z]+)*</code>, <code>(a|aa)+</code> and <code>(a|a?)+</code>.</p>
<p>We timed the first one in Python 3.13.18 against a string of <code>a</code> characters followed by <code>!</code>, so the match has to fail:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#f92672">import</span> re<span style="color:#f92672">,</span> time
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>pat <span style="color:#f92672">=</span> re<span style="color:#f92672">.</span>compile(<span style="color:#e6db74">r</span><span style="color:#e6db74">&#39;^(a+)+$&#39;</span>)
</span></span><span style="display:flex;"><span>pos <span style="color:#f92672">=</span> re<span style="color:#f92672">.</span>compile(<span style="color:#e6db74">r</span><span style="color:#e6db74">&#39;^(?:a++)+$&#39;</span>)   <span style="color:#75715e"># possessive quantifier, Python 3.11+</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">for</span> n <span style="color:#f92672">in</span> (<span style="color:#ae81ff">18</span>, <span style="color:#ae81ff">20</span>, <span style="color:#ae81ff">22</span>, <span style="color:#ae81ff">24</span>):
</span></span><span style="display:flex;"><span>    s <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;a&#39;</span> <span style="color:#f92672">*</span> n <span style="color:#f92672">+</span> <span style="color:#e6db74">&#39;!&#39;</span>
</span></span><span style="display:flex;"><span>    t <span style="color:#f92672">=</span> time<span style="color:#f92672">.</span>perf_counter(); pat<span style="color:#f92672">.</span><span style="color:#66d9ef">match</span>(s); t1 <span style="color:#f92672">=</span> time<span style="color:#f92672">.</span>perf_counter() <span style="color:#f92672">-</span> t
</span></span><span style="display:flex;"><span>    t <span style="color:#f92672">=</span> time<span style="color:#f92672">.</span>perf_counter(); pos<span style="color:#f92672">.</span><span style="color:#66d9ef">match</span>(s); t2 <span style="color:#f92672">=</span> time<span style="color:#f92672">.</span>perf_counter() <span style="color:#f92672">-</span> t
</span></span><span style="display:flex;"><span>    print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;n=</span><span style="color:#e6db74">{</span>n<span style="color:#e6db74">:</span><span style="color:#e6db74">2d</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> backtracking=</span><span style="color:#e6db74">{</span>t1<span style="color:#e6db74">:</span><span style="color:#e6db74">8.4f</span><span style="color:#e6db74">}</span><span style="color:#e6db74">s possessive=</span><span style="color:#e6db74">{</span>t2<span style="color:#e6db74">:</span><span style="color:#e6db74">.6f</span><span style="color:#e6db74">}</span><span style="color:#e6db74">s&#34;</span>)
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-text" data-lang="text"><span style="display:flex;"><span>n=18 backtracking=  0.0088s possessive=0.000005s
</span></span><span style="display:flex;"><span>n=20 backtracking=  0.0429s possessive=0.000005s
</span></span><span style="display:flex;"><span>n=22 backtracking=  0.1680s possessive=0.000003s
</span></span><span style="display:flex;"><span>n=24 backtracking=  0.5356s possessive=0.000005s
</span></span></code></pre></div><p>Each additional two characters roughly quadrupled the time. Extrapolate to a 40-character input and one request ties up a worker for hours. Node.js 22 behaves the same way: <code>/^(a+)+$/.test('a'.repeat(24) + '!')</code> took 495 ms in our sandbox.</p>
<p>The possessive rewrite fixes this pattern because <code>a++</code> refuses to give characters back. That is a valid fix when <strong>you</strong> write the pattern. It does nothing when a user writes it, because the user will not write the possessive version.</p>
<h2 id="two-different-threats">Two different threats</h2>
<p>It helps to separate the cases, because the defences differ.</p>
<table>
  <thead>
      <tr>
          <th>Situation</th>
          <th>Who controls the pattern</th>
          <th>Main fix</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Your validator runs on user input</td>
          <td>You</td>
          <td>Review the pattern, use possessive quantifiers or atomic groups, limit input length</td>
      </tr>
      <tr>
          <td>Users submit patterns (search, rules, filters)</td>
          <td>The attacker</td>
          <td>Use a linear-time engine, cap pattern size, isolate matching</td>
      </tr>
      <tr>
          <td>User text is spliced into your pattern</td>
          <td>Partly the attacker</td>
          <td>Escape it (<code>re.escape</code>, or an escape helper in JavaScript) or use a plain substring search</td>
      </tr>
  </tbody>
</table>
<p>This article is about the second row. The third row is the most common way the second row happens by accident: someone builds <code>new RegExp(userInput)</code> to implement a &ldquo;contains&rdquo; search that never needed a regex.</p>
<h2 id="engines-that-are-built-for-untrusted-patterns">Engines that are built for untrusted patterns</h2>
<p><strong>RE2.</strong> Google&rsquo;s <a href="https://github.com/google/re2">RE2 README</a> states the design goal directly: it was built &ldquo;to handle regular expressions from untrusted users without risk&rdquo;, and &ldquo;one of its primary guarantees is that the match time is linear in the length of the input string&rdquo;. It also says its parser, compiler and execution engines &ldquo;limit their memory usage by working within a configurable budget&rdquo;. The price is features: RE2 &ldquo;does not support constructs for which only backtracking solutions are known to exist&rdquo;. That means no backreferences and no look-around.</p>
<p><strong>Go&rsquo;s <code>regexp</code>.</strong> The package uses RE2 syntax, and its source documents that the implementation &ldquo;is guaranteed to run in time linear in the size of the input&rdquo;.</p>
<p><strong>Rust&rsquo;s <code>regex</code> crate.</strong> Its <a href="https://github.com/rust-lang/regex">README</a> says &ldquo;all regex searches in this crate have worst case <code>O(m * n)</code> time complexity, where <code>m</code> is proportional to the size of the regex and <code>n</code> is proportional to the size of the string being searched&rdquo;. Its documentation says the crate &ldquo;also, to a certain extent, supports untrusted patterns&rdquo;, mainly &ldquo;by limiting their size by default&rdquo;, which you can tune with <code>RegexBuilder::size_limit</code>.</p>
<p>Note the <code>m</code> in that complexity. Linear in the input is not the same as free: a huge pattern still costs more to compile and run. That is why a pattern length cap belongs in front of every engine, safe or not.</p>
<h2 id="engines-that-say-they-are-not">Engines that say they are not</h2>
<p><strong>.NET.</strong> Microsoft&rsquo;s <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-regex">regex best-practices page</a> is unusually direct:</p>
<blockquote>
<p>The .NET regular expression engine does not offer protection against untrusted <em>patterns</em>, and applications should not create regular expression patterns from untrusted user-provided values.</p>
</blockquote>
<p>It adds that time-out values and <code>RegexOptions.NonBacktracking</code> (introduced in .NET 7, which &ldquo;guarantees linear-time processing in the length of the input&rdquo;) &ldquo;help protect against accidental performance problems in developer-authored patterns. They are not intended as a security boundary against malicious patterns.&rdquo; Use them for your own patterns, and do not treat them as permission to accept user-written ones.</p>
<p><strong>Ruby.</strong> Ruby 3.2 added two ReDoS mitigations, described in the <a href="https://www.ruby-lang.org/en/news/2022/12/25/ruby-3-2-0-released/">3.2.0 release notes</a>. A memoization-based matcher completes &ldquo;most Regexp matching (about 90% in our experiments)&rdquo; in linear time, at the cost of memory &ldquo;proportional to the input length&rdquo;. Because that optimization &ldquo;cannot be applied to some kind of regular expressions, such as those including advanced features (e.g., back-references or look-around)&rdquo;, Ruby also added <code>Regexp.timeout</code>, a global setting, and a per-regex <code>timeout:</code> keyword on <code>Regexp.new</code>. Both help. Neither turns Ruby&rsquo;s engine into one designed for hostile patterns.</p>
<p><strong>Python and JavaScript.</strong> Python&rsquo;s <code>re</code> documentation describes no match timeout. Python 3.11 added possessive quantifiers and atomic groups <code>(?&gt;...)</code>, which help you write safer patterns but do nothing about patterns you did not write. JavaScript&rsquo;s <code>RegExp</code> has no timeout either. V8 has shipped an <a href="https://v8.dev/blog/non-backtracking-regexp">experimental non-backtracking engine</a> since V8 8.8, behind <code>--enable-experimental-regexp-engine</code>, which adds a non-standard <code>l</code> (&ldquo;linear&rdquo;) flag. V8&rsquo;s own post calls it experimental &ldquo;because Irregexp is orders of magnitude faster than the new engine on most common patterns&rdquo;. With the flag on, <code>/^(a+)+$/l</code> failed on a 50,000-character evil input in about 3 ms in our Node.js 22.23 test. Running production on an experimental V8 flag is a decision to make deliberately, not a default.</p>
<p>Accepting patterns also exposes you to bugs in the regex parser and compiler themselves, not just slow matching. Our write-up of <a href="/posts/gitlab-cve-2026-97229-ci-regex-rce-patch-and-hunt/">GitLab CVE-2026-97229</a> covers a remote code execution flaw in how GitLab compiled regular expressions from CI/CD configuration. Using a small, heavily fuzzed engine reduces that risk too.</p>
<h2 id="pattern-1-python-with-re2">Pattern 1: Python with RE2</h2>
<p>This uses the <code>google-re2</code> package (we tested 1.1.20251105 with Python 3.13). It caps pattern length, compiles with RE2, and turns unsupported syntax into a clear error your API can return as a 400.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#f92672">import</span> re2
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>MAX_PATTERN <span style="color:#f92672">=</span> <span style="color:#ae81ff">256</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">compile_user_pattern</span>(pattern: str):
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;&#34;&#34;Compile a user-supplied pattern with RE2 or raise ValueError.&#34;&#34;&#34;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> len(pattern) <span style="color:#f92672">&gt;</span> MAX_PATTERN:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">raise</span> <span style="color:#a6e22e">ValueError</span>(<span style="color:#e6db74">&#34;pattern too long&#34;</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> re2<span style="color:#f92672">.</span>compile(pattern)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">except</span> re2<span style="color:#f92672">.</span>error <span style="color:#66d9ef">as</span> e:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">raise</span> <span style="color:#a6e22e">ValueError</span>(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;unsupported or invalid pattern: </span><span style="color:#e6db74">{</span>e<span style="color:#e6db74">}</span><span style="color:#e6db74">&#34;</span>) <span style="color:#f92672">from</span> None
</span></span></code></pre></div><p>What happened when we ran it:</p>
<table>
  <thead>
      <tr>
          <th>Input</th>
          <th>Result</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><code>^(a+)+$</code> searched against 1,000,000 <code>a</code> characters plus <code>!</code></td>
          <td>No match, returned in about 2 ms</td>
      </tr>
      <tr>
          <td><code>(\w+)\s\1</code> (backreference)</td>
          <td>Rejected: <code>invalid escape sequence: \1</code></td>
      </tr>
      <tr>
          <td><code>^(?=.*\d).+$</code> (look-ahead)</td>
          <td>Rejected: <code>invalid perl operator: (?=</code></td>
      </tr>
      <tr>
          <td>300-character pattern</td>
          <td>Rejected by the length cap</td>
      </tr>
  </tbody>
</table>
<p>The same evil pattern that took half a second on 24 characters in <code>re</code> finished a million characters in milliseconds. Two practical notes from the test: RE2 logs parse errors to stderr through its own logging, so expect noise in your logs when users submit bad patterns. And do not catch the error and retry with <code>re</code>. That fallback reopens the exact hole you closed.</p>
<h2 id="pattern-2-nodejs-with-a-killable-worker">Pattern 2: Node.js with a killable worker</h2>
<p>If you cannot add a native RE2 binding, isolate the backtracking engine. A worker thread can be terminated mid-match, which a <code>setTimeout</code> on the main thread cannot do: a regex blocks the event loop until it returns. This is tested on Node.js 22.23.4:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-javascript" data-lang="javascript"><span style="display:flex;"><span><span style="color:#75715e">// safe_match.mjs: run an untrusted pattern in a worker and kill it after a deadline.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">import</span> { <span style="color:#a6e22e">Worker</span> } <span style="color:#a6e22e">from</span> <span style="color:#e6db74">&#39;node:worker_threads&#39;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">WORKER_SRC</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">`
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">  const { parentPort, workerData } = require(&#39;node:worker_threads&#39;);
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">  const { pattern, flags, input } = workerData;
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">  try {
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    parentPort.postMessage({ ok: true, match: new RegExp(pattern, flags).test(input) });
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">  } catch (e) {
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">    parentPort.postMessage({ ok: false, error: e.message });
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">  }
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">`</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">export</span> <span style="color:#66d9ef">function</span> <span style="color:#a6e22e">safeTest</span>(<span style="color:#a6e22e">pattern</span>, <span style="color:#a6e22e">input</span>, { <span style="color:#a6e22e">flags</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;&#39;</span>, <span style="color:#a6e22e">timeoutMs</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">100</span>, <span style="color:#a6e22e">maxPattern</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">256</span> } <span style="color:#f92672">=</span> {}) {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">pattern</span>.<span style="color:#a6e22e">length</span> <span style="color:#f92672">&gt;</span> <span style="color:#a6e22e">maxPattern</span>) <span style="color:#66d9ef">return</span> Promise.<span style="color:#a6e22e">resolve</span>({ <span style="color:#a6e22e">ok</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">false</span>, <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;pattern too long&#39;</span> });
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">if</span> (<span style="color:#f92672">!</span><span style="color:#e6db74">/^[gimsuy]*$/</span>.<span style="color:#a6e22e">test</span>(<span style="color:#a6e22e">flags</span>)) <span style="color:#66d9ef">return</span> Promise.<span style="color:#a6e22e">resolve</span>({ <span style="color:#a6e22e">ok</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">false</span>, <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;bad flags&#39;</span> });
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> Promise((<span style="color:#a6e22e">resolve</span>) =&gt; {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">w</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Worker</span>(<span style="color:#a6e22e">WORKER_SRC</span>, {
</span></span><span style="display:flex;"><span>      eval<span style="color:#f92672">:</span> <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#a6e22e">workerData</span><span style="color:#f92672">:</span> { <span style="color:#a6e22e">pattern</span>, <span style="color:#a6e22e">flags</span>, <span style="color:#a6e22e">input</span> },
</span></span><span style="display:flex;"><span>      <span style="color:#a6e22e">resourceLimits</span><span style="color:#f92672">:</span> { <span style="color:#a6e22e">maxOldGenerationSizeMb</span><span style="color:#f92672">:</span> <span style="color:#ae81ff">32</span> },
</span></span><span style="display:flex;"><span>    });
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">timer</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">setTimeout</span>(() =&gt; { <span style="color:#a6e22e">w</span>.<span style="color:#a6e22e">terminate</span>(); <span style="color:#a6e22e">resolve</span>({ <span style="color:#a6e22e">ok</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">false</span>, <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;timeout&#39;</span> }); }, <span style="color:#a6e22e">timeoutMs</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">w</span>.<span style="color:#a6e22e">once</span>(<span style="color:#e6db74">&#39;message&#39;</span>, (<span style="color:#a6e22e">m</span>) =&gt; { <span style="color:#a6e22e">clearTimeout</span>(<span style="color:#a6e22e">timer</span>); <span style="color:#a6e22e">w</span>.<span style="color:#a6e22e">terminate</span>(); <span style="color:#a6e22e">resolve</span>(<span style="color:#a6e22e">m</span>); });
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">w</span>.<span style="color:#a6e22e">once</span>(<span style="color:#e6db74">&#39;error&#39;</span>, (<span style="color:#a6e22e">e</span>) =&gt; { <span style="color:#a6e22e">clearTimeout</span>(<span style="color:#a6e22e">timer</span>); <span style="color:#a6e22e">resolve</span>({ <span style="color:#a6e22e">ok</span><span style="color:#f92672">:</span> <span style="color:#66d9ef">false</span>, <span style="color:#a6e22e">error</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">message</span> }); });
</span></span><span style="display:flex;"><span>  });
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Results:</p>
<ul>
<li><code>safeTest('^(a+)+$', 'a'.repeat(40) + '!')</code> returned <code>{ ok: false, error: 'timeout' }</code> after 103 ms. On the main thread that match would not finish.</li>
<li><code>safeTest('^[a-z]+@example\\.com$', 'alice@example.com')</code> returned <code>{ ok: true, match: true }</code>.</li>
<li><code>safeTest('(unclosed', 'x')</code> returned the syntax error instead of throwing.</li>
</ul>
<p>The cost: spawning a worker per call averaged 25.4 ms in our sandbox, over 20 calls. That is fine for saving a rule. It is too slow for matching every log line. For high-volume matching, keep a small pool of long-lived workers and replace any worker you have to terminate, or move to an RE2 binding. This is a containment pattern, not a fix: an attacker can still make every match hit the timeout, so rate-limit pattern submissions and count timeouts per user.</p>
<h2 id="a-checklist-for-features-that-accept-patterns">A checklist for features that accept patterns</h2>
<ol>
<li><strong>Ask whether you need regex at all.</strong> Substring, prefix or glob matching covers most &ldquo;search&rdquo; features and has no ReDoS surface.</li>
<li><strong>Pick a linear-time engine</strong> (RE2 or a binding, Go <code>regexp</code>, Rust <code>regex</code>) for any pattern a user can write, including admins and API clients.</li>
<li><strong>Cap pattern length</strong> and, if you can, the number of patterns per user or rule set.</li>
<li><strong>Reject unsupported features with a clear message.</strong> Never fall back to a backtracking engine.</li>
<li><strong>Cap input length</strong> for each match. Linear time on a 2 GB input is still a lot of time. Our post on <a href="/posts/nodejs-decompression-bomb-zlib-limits/">decompression bombs in Node.js</a> covers the related problem of inputs that grow after you accept them.</li>
<li><strong>If you must backtrack, isolate it.</strong> Use a worker or process you can kill, a hard deadline, and a memory limit. Ruby&rsquo;s <code>Regexp.timeout</code> and .NET&rsquo;s <code>matchTimeout</code> are useful extra layers.</li>
<li><strong>Watch for it.</strong> Log match timeouts and compile failures by user, and alert on spikes.</li>
</ol>
<h2 id="limits-of-this-article">Limits of this article</h2>
<ul>
<li>Timings are from a shared cloud sandbox and will differ on your hardware. The growth rate, not the absolute numbers, is the point.</li>
<li>We did not test .NET or Ruby directly, and we do not cover Java, PCRE or other engines here. Statements about them come from their documentation, quoted above.</li>
<li>We tested one Python RE2 binding (<code>google-re2</code>). Node.js RE2 bindings exist, but we did not test one for this article.</li>
<li>A linear-time engine removes catastrophic backtracking. It does not remove the need for size limits, rate limits or patching the engine itself.</li>
</ul>
<h2 id="sources-and-verification">Sources and verification</h2>
<table>
  <thead>
      <tr>
          <th>Important claim</th>
          <th>Source</th>
          <th>Status</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Backtracking times for <code>^(a+)+$</code> in Python 3.13.18 and Node.js 22.23.4; RE2 and worker results</td>
          <td>Our tests, code above</td>
          <td>Verified (our sandbox)</td>
      </tr>
      <tr>
          <td>&ldquo;Evil&rdquo; regex conditions and examples; attacker can inject an evil regex</td>
          <td><a href="https://wiki.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS">OWASP wiki: ReDoS</a></td>
          <td>Verified (archived wiki page)</td>
      </tr>
      <tr>
          <td>RE2: built for untrusted users, linear in input, memory budget, no backtracking-only constructs</td>
          <td><a href="https://github.com/google/re2">google/re2 README</a></td>
          <td>Verified</td>
      </tr>
      <tr>
          <td>Go regexp: linear in the size of the input</td>
          <td><a href="https://github.com/golang/go/blob/master/src/regexp/regexp.go">Go source, regexp.go</a></td>
          <td>Verified</td>
      </tr>
      <tr>
          <td>Rust regex: worst case O(m * n); untrusted patterns handled mainly by size limit</td>
          <td><a href="https://github.com/rust-lang/regex">rust-lang/regex README and docs</a></td>
          <td>Verified</td>
      </tr>
      <tr>
          <td>.NET: no protection against untrusted patterns; timeouts and NonBacktracking not a security boundary</td>
          <td><a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-regex">Microsoft Learn: regex best practices</a></td>
          <td>Verified (docs source on GitHub)</td>
      </tr>
      <tr>
          <td>Ruby 3.2 memoization (about 90% linear) and Regexp.timeout</td>
          <td><a href="https://www.ruby-lang.org/en/news/2022/12/25/ruby-3-2-0-released/">Ruby 3.2.0 release notes</a></td>
          <td>Verified</td>
      </tr>
      <tr>
          <td>Python 3.11 possessive quantifiers and atomic groups; no timeout documented</td>
          <td><a href="https://docs.python.org/3/library/re.html">Python re documentation</a></td>
          <td>Verified</td>
      </tr>
      <tr>
          <td>V8 experimental non-backtracking engine, <code>l</code> flag, slower than Irregexp</td>
          <td><a href="https://v8.dev/blog/non-backtracking-regexp">V8 blog</a></td>
          <td>Verified</td>
      </tr>
  </tbody>
</table>
]]></content:encoded></item><item><title>Node.js Decompression Bombs: zlib Limits That Work</title><link>https://firewallsync.com/posts/nodejs-decompression-bomb-zlib-limits/</link><guid>https://firewallsync.com/posts/nodejs-decompression-bomb-zlib-limits/</guid><pubDate>Thu, 29 Oct 2026 04:40:00 +0000</pubDate><dc:creator>John Marshall</dc:creator><category>AppSec &amp; APIs</category><description>A 100 KB gzip body can decompress to 100 MB. Node's maxOutputLength stops that in the one-shot zlib functions, but streams silently ignore it, and fetch() decompresses responses with no cap at all. We tested where the limits hold in Node.js 22 and Express 5, with code you can copy.</description><enclosure url="https://firewallsync.com/posts/nodejs-decompression-bomb-zlib-limits/cover_hu6171799600051493283.jpg" type="image/jpeg" length="0"/><media:content url="https://firewallsync.com/posts/nodejs-decompression-bomb-zlib-limits/cover_hu6171799600051493283.jpg" medium="image" type="image/jpeg" width="1200" height="630"/><content:encoded><![CDATA[<p><img src="https://firewallsync.com/posts/nodejs-decompression-bomb-zlib-limits/cover_hu6171799600051493283.jpg" alt="Water pouring over a low concrete weir below a calm lake, with a metal railing on one side and bare trees on the far shore" width="1200" height="630"></p><p>A decompression bomb is a small compressed payload that expands into far more data than your service expects, enough to exhaust memory or tie up a CPU core. MITRE files it as <a href="https://cwe.mitre.org/data/definitions/409.html">CWE-409</a>, &ldquo;Improper Handling of Highly Compressed Data (Data Amplification)&rdquo;. In Node.js, the defence is to <strong>count decompressed bytes and stop at a limit you choose</strong>. Node gives you that limit in one place, <code>maxOutputLength</code> on the one-shot zlib functions, and nowhere else. Streams, HTTP clients and custom middleware all need their own cap.</p>
<p>We ran every example below on Node.js 22.23.4. Results for each are in the text.</p>
<h2 id="how-big-the-amplification-gets">How big the amplification gets</h2>
<p>We compressed 100 MiB (104,857,600 bytes) of zeros with each codec Node ships:</p>
<table>
  <thead>
      <tr>
          <th>Codec</th>
          <th>Compressed size</th>
          <th>Ratio</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>gzip (level 9)</td>
          <td>101,941 bytes</td>
          <td>about 1,029 : 1</td>
      </tr>
      <tr>
          <td>zstd (default level)</td>
          <td>3,219 bytes</td>
          <td>about 32,575 : 1</td>
      </tr>
      <tr>
          <td>Brotli (default quality)</td>
          <td>172 bytes</td>
          <td>about 609,637 : 1</td>
      </tr>
  </tbody>
</table>
<p>Zeros are the best case for a compressor, and the ratio for real data is far lower. That&rsquo;s the point: an attacker picks the input. A request-body limit of 1 MB on the wire tells you nothing about the decompressed size.</p>
<h2 id="the-one-shot-functions-maxoutputlength-works">The one-shot functions: maxOutputLength works</h2>
<p>Node&rsquo;s one-shot functions (<code>zlib.gunzip</code>, <code>zlib.inflate</code>, <code>zlib.brotliDecompress</code>, <code>zlib.zstdDecompress</code> and their <code>*Sync</code> forms) accept <code>maxOutputLength</code>. The <a href="https://nodejs.org/api/zlib.html">zlib docs</a> describe it as an option that &ldquo;Limits output size when using convenience methods&rdquo;. The default is <code>buffer.kMaxLength</code>, the largest Buffer Node can allocate, so without it you have no practical limit.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-js" data-lang="js"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">zlib</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;node:zlib&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">LIMIT</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">1024</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">1024</span>; <span style="color:#75715e">// 1 MiB of decompressed output
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">safeGunzip</span>(<span style="color:#a6e22e">buf</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">try</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">zlib</span>.<span style="color:#a6e22e">gunzipSync</span>(<span style="color:#a6e22e">buf</span>, { <span style="color:#a6e22e">maxOutputLength</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">LIMIT</span> });
</span></span><span style="display:flex;"><span>  } <span style="color:#66d9ef">catch</span> (<span style="color:#a6e22e">err</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">code</span> <span style="color:#f92672">===</span> <span style="color:#e6db74">&#39;ERR_BUFFER_TOO_LARGE&#39;</span>) {
</span></span><span style="display:flex;"><span>      <span style="color:#66d9ef">throw</span> Object.<span style="color:#a6e22e">assign</span>(<span style="color:#66d9ef">new</span> Error(<span style="color:#e6db74">&#39;decompressed payload too large&#39;</span>), { <span style="color:#a6e22e">status</span><span style="color:#f92672">:</span> <span style="color:#ae81ff">413</span> });
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">throw</span> <span style="color:#a6e22e">err</span>; <span style="color:#75715e">// corrupt input, wrong format, etc.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>With the 100 MiB bombs from the table, <code>gunzipSync</code>, <code>brotliDecompressSync</code> and <code>zstdDecompressSync</code> all threw <code>RangeError</code> with code <code>ERR_BUFFER_TOO_LARGE</code> and the message &ldquo;Cannot create a Buffer larger than 1048576 bytes&rdquo;. The async <code>zlib.gunzip()</code> passed the same error to its callback.</p>
<p>Use the one-shot functions when the whole payload is already in memory and you can name a sensible maximum: a webhook body, a cached blob, a small config file.</p>
<h2 id="streams-maxoutputlength-is-ignored">Streams: maxOutputLength is ignored</h2>
<p>The stream classes accept the same options object, so this looks right:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-js" data-lang="js"><span style="display:flex;"><span><span style="color:#75715e">// Looks safe. Isn&#39;t.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#a6e22e">zlib</span>.<span style="color:#a6e22e">createGunzip</span>({ <span style="color:#a6e22e">maxOutputLength</span><span style="color:#f92672">:</span> <span style="color:#ae81ff">1024</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">1024</span> });
</span></span></code></pre></div><p>In our test, piping the gzip bomb through that stream delivered all 104,857,600 bytes and finished without an error. The option is documented for the convenience methods only, and the stream path doesn&rsquo;t enforce it. Nothing warns you.</p>
<p>The fix is a Transform that counts bytes after the decompressor and fails the pipeline when the count passes your limit:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-js" data-lang="js"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">zlib</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;node:zlib&#39;</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">pipeline</span>, <span style="color:#a6e22e">Transform</span> } <span style="color:#f92672">=</span> <span style="color:#a6e22e">require</span>(<span style="color:#e6db74">&#39;node:stream&#39;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Fail the pipeline once decompressed output exceeds maxBytes.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">function</span> <span style="color:#a6e22e">byteLimit</span>(<span style="color:#a6e22e">maxBytes</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">let</span> <span style="color:#a6e22e">seen</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>;
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">Transform</span>({
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">transform</span>(<span style="color:#a6e22e">chunk</span>, <span style="color:#a6e22e">_enc</span>, <span style="color:#a6e22e">cb</span>) {
</span></span><span style="display:flex;"><span>      <span style="color:#a6e22e">seen</span> <span style="color:#f92672">+=</span> <span style="color:#a6e22e">chunk</span>.<span style="color:#a6e22e">length</span>;
</span></span><span style="display:flex;"><span>      <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">seen</span> <span style="color:#f92672">&gt;</span> <span style="color:#a6e22e">maxBytes</span>) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">RangeError</span>(<span style="color:#e6db74">`decompressed body exceeds </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">maxBytes</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> bytes`</span>);
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">code</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;ERR_DECOMPRESSED_TOO_LARGE&#39;</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">cb</span>(<span style="color:#a6e22e">err</span>);
</span></span><span style="display:flex;"><span>      }
</span></span><span style="display:flex;"><span>      <span style="color:#a6e22e">cb</span>(<span style="color:#66d9ef">null</span>, <span style="color:#a6e22e">chunk</span>);
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>  });
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">pipeline</span>(
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">source</span>,                 <span style="color:#75715e">// e.g. req, a file stream, an upstream response
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>  <span style="color:#a6e22e">zlib</span>.<span style="color:#a6e22e">createGunzip</span>(),
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">byteLimit</span>(<span style="color:#ae81ff">1024</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">1024</span>),
</span></span><span style="display:flex;"><span>  <span style="color:#a6e22e">destination</span>,
</span></span><span style="display:flex;"><span>  (<span style="color:#a6e22e">err</span>) =&gt; { <span style="color:#75715e">/* err.code === &#39;ERR_DECOMPRESSED_TOO_LARGE&#39; on a bomb */</span> },
</span></span><span style="display:flex;"><span>);
</span></span></code></pre></div><p>Against the 100 MiB bomb, the pipeline failed with <code>ERR_DECOMPRESSED_TOO_LARGE</code> after exactly 1,048,576 bytes had reached the destination. <code>pipeline()</code> destroys every stream in the chain on error, so the decompressor stops as well.</p>
<p>Two details make this work. The limiter must sit <strong>after</strong> the decompressor, because counting compressed bytes is the mistake you&rsquo;re avoiding. And use <code>pipeline()</code>, not chained <code>.pipe()</code> calls, which don&rsquo;t propagate errors or destroy the upstream streams.</p>
<h2 id="express-the-body-parser-already-counts-decompressed-bytes">Express: the body parser already counts decompressed bytes</h2>
<p>Express&rsquo;s <code>express.json()</code>, <code>express.urlencoded()</code>, <code>express.text()</code> and <code>express.raw()</code> come from <a href="https://github.com/expressjs/body-parser">body-parser</a>. Its <code>inflate</code> option defaults to <code>true</code>, and in body-parser 2.4.0 it decodes <code>deflate</code>, <code>gzip</code>, <code>br</code> and, where Node supports it, <code>zstd</code>.</p>
<p>We sent <code>express.json()</code> (default <code>limit</code> of <code>'100kb'</code>) a 10 MB JSON body compressed each way:</p>
<table>
  <thead>
      <tr>
          <th>Content-Encoding</th>
          <th>Bytes on the wire</th>
          <th>Result</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>gzip</td>
          <td>10,232</td>
          <td>413, <code>entity.too.large</code></td>
      </tr>
      <tr>
          <td>br</td>
          <td>41</td>
          <td>413, <code>entity.too.large</code></td>
      </tr>
      <tr>
          <td>zstd</td>
          <td>355</td>
          <td>413, <code>entity.too.large</code></td>
      </tr>
      <tr>
          <td>gzip with <code>inflate: false</code></td>
          <td>10,232</td>
          <td>415, <code>encoding.unsupported</code></td>
      </tr>
  </tbody>
</table>
<p>All three compressed bodies were under 100 KB on the wire and still got 413, so the limit is applied to the decoded body. That&rsquo;s the behaviour you want. Tested with Express 5.3.0, body-parser 2.4.0 and raw-body 3.0.2.</p>
<p>Two cautions. The body-parser README warns that limits &ldquo;above the default, for example payloads of 5 MB or more&rdquo; increase memory use and response times, so raise <code>limit</code> per route, not globally. And if you don&rsquo;t expect compressed request bodies, <code>inflate: false</code> turns them away with 415 before any decoding.</p>
<p>Custom code is where the gaps are: a handler that does <code>req.pipe(zlib.createGunzip())</code> for an upload endpoint, or a framework plugin with its own decoder. Give each one the byte limiter above.</p>
<h2 id="fetch-responses-are-decompressed-with-no-cap">fetch(): responses are decompressed with no cap</h2>
<p>Node&rsquo;s built-in <code>fetch()</code> decodes <code>Content-Encoding: gzip</code> for you. We served the 100 MiB gzip bomb from a local server:</p>
<ul>
<li><code>res.headers.get('content-length')</code> returned <code>101941</code>, the compressed size.</li>
<li><code>await res.arrayBuffer()</code> returned 104,857,600 bytes.</li>
</ul>
<p>There&rsquo;s no size option on <code>arrayBuffer()</code>, <code>json()</code> or <code>text()</code>. If you fetch URLs you don&rsquo;t control (webhooks, link previews, feed readers, anything with a user-supplied URL), read the body with a cap:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-js" data-lang="js"><span style="display:flex;"><span><span style="color:#75715e">// Read at most maxBytes of a fetch() response body (after fetch&#39;s own decompression).
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">async</span> <span style="color:#66d9ef">function</span> <span style="color:#a6e22e">readCapped</span>(<span style="color:#a6e22e">res</span>, <span style="color:#a6e22e">maxBytes</span>) {
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">reader</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">res</span>.<span style="color:#a6e22e">body</span>.<span style="color:#a6e22e">getReader</span>();
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">const</span> <span style="color:#a6e22e">chunks</span> <span style="color:#f92672">=</span> [];
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">let</span> <span style="color:#a6e22e">total</span> <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span>;
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">for</span> (;;) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> { <span style="color:#a6e22e">done</span>, <span style="color:#a6e22e">value</span> } <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">reader</span>.<span style="color:#a6e22e">read</span>();
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">done</span>) <span style="color:#66d9ef">break</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">total</span> <span style="color:#f92672">+=</span> <span style="color:#a6e22e">value</span>.<span style="color:#a6e22e">byteLength</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">total</span> <span style="color:#f92672">&gt;</span> <span style="color:#a6e22e">maxBytes</span>) {
</span></span><span style="display:flex;"><span>      <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">reader</span>.<span style="color:#a6e22e">cancel</span>();
</span></span><span style="display:flex;"><span>      <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> <span style="color:#a6e22e">RangeError</span>(<span style="color:#e6db74">`response exceeds </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">maxBytes</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> bytes`</span>);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">chunks</span>.<span style="color:#a6e22e">push</span>(<span style="color:#a6e22e">value</span>);
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>  <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">Buffer</span>.<span style="color:#a6e22e">concat</span>(<span style="color:#a6e22e">chunks</span>);
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">res</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">fetch</span>(<span style="color:#a6e22e">url</span>, { <span style="color:#a6e22e">signal</span><span style="color:#f92672">:</span> <span style="color:#a6e22e">AbortSignal</span>.<span style="color:#a6e22e">timeout</span>(<span style="color:#ae81ff">10_000</span>) });
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">body</span> <span style="color:#f92672">=</span> <span style="color:#66d9ef">await</span> <span style="color:#a6e22e">readCapped</span>(<span style="color:#a6e22e">res</span>, <span style="color:#ae81ff">1024</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">1024</span>);
</span></span></code></pre></div><p>Against the bomb, <code>readCapped(res, 1 MiB)</code> threw &ldquo;response exceeds 1048576 bytes&rdquo;. Pair it with a timeout, because a slow trickle is a different attack that a byte cap doesn&rsquo;t stop. Fetching arbitrary URLs has bigger risks than size, too; our <a href="/posts/ssrf-explained-how-server-side-request-forgery-works-and-how-to-prevent-it/">SSRF guide</a> covers the network side.</p>
<h2 id="a-checklist-for-node-services">A checklist for Node services</h2>
<table>
  <thead>
      <tr>
          <th>Where you decompress</th>
          <th>What enforces the limit</th>
          <th>Default</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><code>zlib.*Sync()</code> / <code>zlib.*()</code> one-shot</td>
          <td><code>maxOutputLength</code></td>
          <td><code>buffer.kMaxLength</code> (no practical limit)</td>
      </tr>
      <tr>
          <td><code>zlib.create*()</code> streams</td>
          <td>Your own byte-counting Transform</td>
          <td>None; <code>maxOutputLength</code> is ignored</td>
      </tr>
      <tr>
          <td><code>express.json()</code> and other body-parser parsers</td>
          <td><code>limit</code>, counted after decoding</td>
          <td><code>'100kb'</code></td>
      </tr>
      <tr>
          <td><code>fetch()</code> response bodies</td>
          <td>A capped reader</td>
          <td>None</td>
      </tr>
      <tr>
          <td>Uploaded archives (zip, tar.gz)</td>
          <td>Per-entry and total extracted-size limits in your extractor</td>
          <td>Depends on the library</td>
      </tr>
  </tbody>
</table>
<p>Also consider:</p>
<ul>
<li><strong>Keep the decoder patched.</strong> Size limits don&rsquo;t help against bugs in the decompressor itself. CVE-2026-111497 was an out-of-bounds write in Brotli&rsquo;s decoder, fixed in Node.js 22.23.4, 24.22.1 and 26.12.1; see our <a href="/posts/brotli-cve-2026-111497-find-and-patch-every-copy/">Brotli guide</a>.</li>
<li><strong>Decide whether you need each codec.</strong> zstd arrived in Node.js 22.15.0 and is marked Experimental in the Node 22 docs, yet body-parser 2.4.0 accepts it automatically when the runtime supports it. If clients never send it, <code>inflate: false</code> or a proxy rule removes that path.</li>
<li><strong>Push the limit to the edge as well.</strong> A reverse proxy that decompresses request bodies should cap the decoded size too, so the application isn&rsquo;t your only control.</li>
</ul>
<h2 id="limits-of-this-article">Limits of this article</h2>
<p>All results come from Node.js 22.23.4 on Linux with Express 5.3.0, body-parser 2.4.0 and raw-body 3.0.2, using 100 MiB of zeros as the bomb. Other Node release lines, frameworks (Fastify, Koa, NestJS adapters) and HTTP clients (axios, undici&rsquo;s <code>request</code>) may behave differently. Test them the same way. We measured whether limits held, not peak memory use or CPU time.</p>
<h2 id="sources-and-verification">Sources and verification</h2>
<table>
  <thead>
      <tr>
          <th>Important claim</th>
          <th>Source</th>
          <th>Status</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>maxOutputLength &ldquo;Limits output size when using convenience methods&rdquo;; default <code>buffer.kMaxLength</code></td>
          <td><a href="https://nodejs.org/api/zlib.html">Node.js zlib docs</a> (<a href="https://github.com/nodejs/node/blob/v22.23.4/doc/api/zlib.md">v22.23.4 source</a>)</td>
          <td>Verified</td>
      </tr>
      <tr>
          <td>zstd added in v22.15.0; Stability 1, Experimental</td>
          <td>Node.js v22.23.4 zlib docs</td>
          <td>Verified</td>
      </tr>
      <tr>
          <td>Compression ratios; ERR_BUFFER_TOO_LARGE; streams ignore maxOutputLength; byte limiter; fetch() results</td>
          <td>Our tests on Node.js 22.23.4 (code above)</td>
          <td>Verified (tested)</td>
      </tr>
      <tr>
          <td>Express limit applies after decompression; 413/415 results</td>
          <td>Our tests on Express 5.3.0 / body-parser 2.4.0</td>
          <td>Verified (tested)</td>
      </tr>
      <tr>
          <td>body-parser decodes deflate, gzip, br, zstd; inflate default true; limit default &lsquo;100kb&rsquo;; 5 MB warning</td>
          <td><a href="https://github.com/expressjs/body-parser">body-parser</a> 2.4.0 source and README</td>
          <td>Verified</td>
      </tr>
      <tr>
          <td>CWE-409 title</td>
          <td><a href="https://cwe.mitre.org/data/definitions/409.html">MITRE CWE-409</a></td>
          <td>Verified</td>
      </tr>
  </tbody>
</table>
]]></content:encoded></item></channel></rss>