Instructions for the MongoDB server cluster are represented in two forms:
With BSON being the main mechanism. BSONAs a client program assembles a query in MongoDB, it builds a BSON object, not a string. Thus traditional SQL Injection attacks are not a problem. More details and some nuances are covered below. MongoDB queries are represented as BSON objects. Typically the programming language gives a convenient way to build these objects that is injection free. For example in C++ one would write: BSONObj my_query = BSON( "name" << a_name ); auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", my_query); my_query then will have a value such as { name : "Joe" }. If my_query contained special characters such as ", :, {, etc., nothing bad happens, they are just part of the string. JavascriptSome care is appropriate when using server-side Javascript. For example when using the $where statement in a query, do not concatenate user supplied data to build Javascript code; this would be analogous to a SQL injection vulnerability. Fortunately, most queries in MongoDB can be expressed without Javascript. Also, we can mix the two modes. It's a good idea to make all the user-supplied fields go straight to a BSON field, and have your Javascript code be static and passed in the $where field. If you need to pass user-supplied values into a $where clause, a good approach is to escape them using the CodeWScope mechanism. By setting the user values as variables in the scope document you will avoid the need to have them eval'ed on the server-side. If you need to use db.eval() with user supplied values, you can either use a CodeWScope or you can supply extra arguments to your function. Something like: db.eval(function(userVal){...}, user_value); This will ensure that user_value gets sent as data rather than code. Dollar Sign Operator EscapingField names in MongoDB query language have semantic meaning. The dollar sign is a reserved character and is used to represent operators, such as $inc. Some care must be taken to assure users can not delivery $operators without the application's expectation. For example, sometimes it is useful to build a BSON object where the key is user-provided. In these situations, keys will need to have substitutions for the reserved $ and . characters. If you are unsure what characters to use, the Unicode full width equivalents aren't a bad choice: U+FF04 ($) and U+FFOE (.) For example: BSONObj my_object = BSON( a_key << a_name ); The user may have supplied a $ value within a_key. my_object could be { $where : "things" }. Here we can look at a few cases:
One way to handle user-generated keys is to always put them in sub-objects. Then they are never at top level (where $operators live) anyway. See Also |

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.
blog comments powered by Disqus