JavaScript NoSQL Injection prevention in MongoDB

谁说我不能喝 提交于 2019-11-28 09:15:38

Note My answer is incorrect. Please refer to other answers.

--

As 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.

For details follow the documentation

UPDATE

Avoid expression like eval which can execute arbitrary JS. If you are taking input from user and running eval like expressions without cleaning the input you can screw up. As pointed by JoBu1324, operations like where, mapReduce and group permit to execute JS expressions directly.

Zanon

Sushant's answer is not correct. You need to be aware of NoSQL injection in MongoDB.

Example (taken from here)

User.findOne({
    "name" : req.params.name, 
    "password" : req.params.password
}, callback); 

If req.params.password is { $ne: 1 }, the user will be retrieved without knowing the password ($ne means not equals 1).

MongoDB Driver

You can use mongo-sanitize:

It will strip out any keys that start with '$' in the input, so you can pass it to MongoDB without worrying about malicious users overwriting.

var sanitize = require('mongo-sanitize');

var name = sanitize(req.params.name);
var password = sanitize(req.params.password);

User.findOne({
    "name" : name, 
    "password" : password
}, callback); 

Mongoose Driver

As it follows a schema, if the password is a string field, it will convert the object { $ne: 1 } to string and no damage will be done. In this case, you don't need to sanitize, just remember to set a proper schema.

Although the post is obsolete, I'm answering.

I know three ways.

First: There is a multipurpose content-filter. Also provides MongoDB injection protection by filtering way.

Second: mongo-sanitize, Helper to sanitize mongodb queries against query selector injections.

Third: I'd seen over here this solution which can be applied for MongoDB too. It's really simple to implement. Only use built-in escape() function of JavaScript.

escape() converts the string into ascii code. $ne is converted into %24ne.

var privateKey = escape(req.params.privateKey);

App.findOne({ key: privateKey }, function (err, app) {
  //do something here
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!