I was reading my trusty O'Reilly book and came across a passage about how Mongo, by nature, avoids the morass of SQL injection-like flaws.
In my gut, I think I understand this. If unsanitized vars are passed into queries, they can't break out of the document-oriented query structure with a UNION
, JOIN
, query turned comment, etc.
How does MongoDB avoid the SQL injection mess? Is it just by nature of this query syntax?
MongoDB avoids the potential for problems by not parsing.
Any API, anywhere, that involves encoding user data in formatted text that gets parsed has the potential for the caller and callee to disagree on how that text should be parsed. These disagreements can be security issues when data is misinterpreted as metadata. This is true whether you're talking about printf format strings, including user generated content in HTML, or generating SQL.
Since MongoDB doesn't parse structured text to figure out what to do, there is no possibility of misinterpreting user input as instructions, and hence no possible security hole.
Incidentally the advice of avoiding APIs that require parsing is item 5 in http://cr.yp.to/qmail/guarantee.html. If you're interested in writing secure software, the other 6 suggestions are worth looking at as well.
Update (2018): The original answer as I gave it remains true to the best of my knowledge. From the point of what is sent to MongoDB to what is sent back, there is no SQL injection attack. The injection attacks that I'm aware of happen outside of MongoDB and are actually problems in how external languages and libraries set up the data structure that will be passed to MongoDB. Furthermore the location of the vulnerability is in how data is parsed on the way to becoming a data structure. Therefore the original answer accurately describes both how to avoid injection attacks, and what puts you at risk of them.
But this accuracy is cold comfort to a programmer who is hit by injection attacks from defects that were not obvious in their own code. Few of us distinguish between the external tool and all the layers between our code and that external tool. And the fact remains that it requires vigilance on our part to anticipate and close off injection attacks. With all tools. And this will remain the case for the foreseeable future.