How dangerous is a mongo query which is fed directly from a URL query string? How dangerous is a mongo query which is fed directly from a URL query string? mongoose mongoose

How dangerous is a mongo query which is fed directly from a URL query string?


As far as injection being problem, like with SQL, the risk is significantly lower... albeit theoretically possible via an unknown attack vector.

The data structures and protocol are binary and API driven rather than leveraging escaped values within a domain-specific-language. Basically, you can't just trick the parser into adding a ";db.dropCollection()" at the end.

If it's only used for queries, it's probably fine... but I'd still caution you to use a tiny bit of validation:

  • Ensure only alphanumeric characters (filter or invalidate nulls and anything else you wouldn't normally accept)
  • Enforce a max length (like 255 characters) per term
  • Enforce a max length of the entire query
  • Strip special parameter names starting with "$", like "$where" & such
  • Don't allow nested arrays/documents/hashes... only strings & ints

Also, keep in mind, an empty query returns everything. You might want a limit on that return value. :)


Operator injection is a serious problem here and I would recommend you at least encode/escape certain characters, more specifically the $ symbol: http://docs.mongodb.org/manual/faq/developers/#dollar-sign-operator-escaping

If the user is allowed to append a $ symbol to the beginning of strings or elements within your $_GET or $_POST or whatever they will quickly use that to: http://xkcd.com/327/ and you will be a gonner, to say the least.


As far as i know Express doesnt provide any out of box control for sanitization. Either you can write your own Middleware our do some basic checks in your own logic.And as you said the case you mention is a bit risky.

But for ease of use the required types built into Mongoose models at least give you the default sanitizations and some control over what gets into or not.

E.g something like this

var Person = new Schema({  title   : { type: String, required: true }, age     : { type: Number, min: 5, max: 20 }, meta    : {      likes : [String]    , birth : { type: Date, default: Date.now }  }

});

Check this for more info also.

http://mongoosejs.com/docs/2.7.x/docs/model-definition.html