title: MongoDB $regex query and potential exploits
body: <p>We have a REST API for querying records in a MongoDB. Very simple, something along the following:</p>
  
  <pre><code>GET /api/items?q=foo
  </code></pre>
  
  <p>During development, it was convenient to allow regular expressions as the query <code>q</code>. We would simply pass the query parameter to a MongoDB <code>$regex</code> operator and not do any escaping:</p>
  
  <pre><code>db.getCollection('items').find({ name: { $regex: req.query.q, $options: 'i' } });
  </code></pre>
  
  <p>Thus we have a very flexible and convenient way of querying our data. Now, that things are getting “serious” i.e. closer to production, I'm asking myself about the security implications. Could someone send “DoS” queries with expensive backtracking?</p>
  
  <p>I’m probably not destructive enough to think of such a query, so I’ve searched the Internet and came across this very interesting read, which mentions several attacks: <a href="https://www.rexegg.com/regex-explosive-quantifiers.html" rel="noreferrer">The Explosive Quantifier Trap</a>.</p>
  
  <p>Discarding the fact, that the mentioned queries on the above page behave far from “catastrophic” as expected (neither in a MongoDB query, nor in online tools such as <a href="https://regex101.com" rel="noreferrer">regex101.com</a>), I’d still like to know:</p>
  
  <ol>
  <li>Is this a real issue or am I chasing non-existent threats?</li>
  <li>Should we better get away from the regex parameters entirely? </li>
  <li>Does MongoDB have any mechanism (i.e. timeout) to prevent DoS attacks through malicious regexes? (fwiw: we’re running in a Node.js environment)</li>
  <li>Are there any libraries to detect such attacks before issuing a query?</li>
  </ol>