We have a REST API for querying records in a MongoDB. Very simple, something along the following:
GET /api/items?q=foo
During development, it was convenient to allow regular expressions as the query q
. We would simply pass the query parameter to a MongoDB $regex
operator and not do any escaping:
db.getCollection('items').find({ name: { $regex: req.query.q, $options: 'i' } });
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?
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: The Explosive Quantifier Trap.
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 regex101.com), I’d still like to know:
Definition. $regex. Provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support.
MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language. Unlike text search, we do not need to do any configuration or command to use regular expressions.
In MongoDB, we can use the $regex operator to find a query that contains a string.
My pretty personal gut feeling says: Don't bother. But then again, if you do nonetheless or even have to then here are a few suggestions for how to deal with this requirement:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With