Securing your node js application (2)

MongoDB Injection

var express    = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.urlencoded({extended: false}));'/login', function (req, res) {
  var username = req.body.username;
  var password = req.body.password;
  var search = {
      username: username,
      password: password
  db.user.find(search, function(err, result) {
    // do something with result


Here if you pass username as {"$gt": ""} and password as {"$gt": ""}, You can bypass the security. It’s simple if the server accepts json payload. It’s possible even if it only accepts url encoded key - value pairs.

You just need to change your request to send username[$gt]=&password[$gt]= which will translate to following:

    "username": {"$gt": undefined},
    "password": {"$gt": undefined}

The solution to this exploit is quite simple. Like parameterized query in SQL, we just need to set the query selector explicitly.

db.users.find({username: { $in: [username] }, password: { $in: [password] }}, function(err, result){
  // do something with result.