How can I prevent JavaScript NoSQL injections into MongoDB?
I am working on a Node.js application and I am passing req.body
, which is a json object, into the mongoose model's save function. I thought there were safeguards behind the scenes, but this doesn't appear to be the case.
One would think that having a NoSQL database prevents any sort of SQL Injection. However, that's not the case. Just like any other database, MongoDB uses commands to fetch and display data on the web application.
The best way to prevent NoSQL injection attacks is to avoid using raw user input in your application code, especially when writing database queries. For example, MongoDB has built-in functionality to build secure queries without using JavaScript.
External injection are also possible with MongoDB. It is often associated with unvalidated user data getting into MongoDB queries. It is always important to detect and prevent NoSQL injection by testing any data that may be received by your server.
NoSQL ≠ No Injection attacks. Non-SQL databases are vulnerable to dangerous and damaging attacks, which must be proactively prevented. Even with the best-efforts during development and deployment, vulnerabilities may remain in the application, causing the risk of non-SQL injections to increase.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With