Prevent MongoDB Injection

Looking at preventing injection attacks on my MongoDB which is using my API.

Private keys are sent to the API, and the API checks if the private key exists in the database:

App.findOne({ privateKey: privateKey }, function (err, app) {
  //do something here
}

      

Simple search like this (I am using Mongoosejs) vulnerable to injection attacks? I've read that using $ where might be, but not sure if I need to do anything here to prevent malicious activity.

Any advice would be much appreciated.

UPDATE: . After reading a little, I changed my query to the following:

App.findOne({ privateKey: String(privateKey) }, function (err, app) {
  //do something here
}

      

Is this an improvement?

+3


source to share


3 answers


It is vulnerable to some injection attacks if you do not use the variable type privateKey

, for example if someone sent you a private key { "$gte" : "abracadabra" }

, the request could return a document that the client should not access. Providing the type privateKey

as String should be sufficient to protect against simple injection attacks.



+3


source


Since the Mongoose driver follows a schema, you just need to set the privateKey as a string field. If someone passes in an object like { $ne: null }

Mongoose will convert it to a string and there won't be any damage.

Note: { $ne: null }

means not zero which will fetch the first result without knowing its key.

Another option is to disinfect the entrances before using them. You can use mongo-sanitize for this task :



It will strip out any keys starting with "$" in the input, so you can pass it to MongoDB without worrying about malicious user rewriting.

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

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

App.findOne({ privateKey: privateKey }, function (err, app) {
    //do something here
}

      

+1


source


There are actually several solutions for MongoDB.

First: There is a multipurpose content-filter . Also provides filtering protection for MongoDB.

Second: I saw this solution here that can be applied to MongoDB as well. It's very easy to implement. Use only the built-in escape()

JavaScript function .

escape()

converts a string to code ascii

. $ne

converted to %24ne

.

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

App.findOne({ privateKey: privateKey }, function (err, app) {
  //do something here
}

      

Actually a similar question was asked here .

0


source







All Articles