MongoDB $regex query and potential exploits

ぐ巨炮叔叔 提交于 2020-12-05 07:04:05

问题


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:

  1. Is this a real issue or am I chasing non-existent threats?
  2. Should we better get away from the regex parameters entirely?
  3. Does MongoDB have any mechanism (i.e. timeout) to prevent DoS attacks through malicious regexes? (fwiw: we’re running in a Node.js environment)
  4. Are there any libraries to detect such attacks before issuing a query?

回答1:


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:

  1. You could define a maximum time that a query may run for using maxTimeMS().
  2. You could attempt to sanitize the regex input but I doubt that there are libraries out there that would help you with that given the endless variations of potentially long running complex queries. Limiting the length of a regex might help, too, but on the other hand probably defeats the purpose of allowing a user to conveniently search using arbitrary filters.
  3. You could provision are more structured query input that would e.g. only allow a user to enter a single alpha-numeric text which you would then wrap in a regex on the server-side to allow for e.g. "starts-with", "contains" or "ends-with" queries or something.
  4. You could allow one single parallel query per user (session? ip?) only which would probably help a little against fatal DoS attacks but certainly not against distributed ones... Or you could even allow only one single parallel call of that endpoint across the entire system.


来源:https://stackoverflow.com/questions/52725156/mongodb-regex-query-and-potential-exploits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!