<-- home

Securing your node js application (1)

Security is of prime concern while deploying an app. Thanks to the awesome nodejs community, there are lot of security middlewares one can use to mitigate common security risks.

Some vulnerabilities are:

  • SQL injection
  • XSS
  • Clickjacking
  • Man in the middle attack

This is not an exhaustive list, but the list of most common ones.

SQL Injection

You have to worry about this attack only if you are using sql databases as your database. If you use MongoDB you should check MongoDB Injection instead. Following code is vulnerable to injections.

var express    = require('express');
var bodyParser = require('body-parser');
var mysql      = require('mysql');
var connection = mysql.createConnection();

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.post('/login', function (req, res) {
  var username = req.body.username;
  var password = req.body.password;
  var query  = "SELECT * FROM users WHERE username = '" + username + 
  "' AND password = '" + password + "'";

  connection.query(query, function(err, result) {
    // do something with result
  });
});

app.listen(1337);

Consider the input where username=admin'--&password=dummy

The sql query build to SELECT * FROM users WHERE username = 'admin'--'AND password = 'dummy'

You see, -- is comment syntax in sql. How simple was it to get access. hmm!

The solution:

  • Escape user inputs.
  var user = connection.escape(req.body.username);
  var pass = connection.escape(req.body.password);
  
  • Use parameterised sql queries.
  var query  = "SELECT * FROM users WHERE username = $1 AND password = $2";
  db.query(query, [username, password], function(err, result) {
    // do something with result
  });
  

This is first one in the node js security series. I will update this with link to other posts as I complete other ones.