Implementing node.js security checklist

1
In this post, we will look into some of the security checklists while implementing a node.js project for n numbers of the user.

node-js-security-checklist
1. Sensitive Data on the Client Side
When deploying front end applications make sure that you never expose API secrets and credentials in your source code, as it will be readable by anyone.

There is no good way to check this automatically, but you have a couple of options to mitigate the risk of accidentally exposing sensitive data on the client side:
a. use of pull requests
b. regular code reviews

2. Session Management
The importance of secure use of cookies cannot be understated: especially within dynamic web applications, which need to maintain state across a stateless protocol such as HTTP.

Cookie Flags
The following is a list of the attributes that can be set for each cookie and what they mean:
Secure - this attribute tells the browser to only send the cookie if the request is being sent over HTTPS.
HttpOnly - this attribute is used to help prevent attacks such as cross-site scripting since it does not allow the cookie to be accessed via JavaScript.

Cookie Scope
domain - this attribute is used to compare against the domain of the server in which the URL is being requested. If the domain matches or if it is a sub-domain, then the path attribute will be checked next.

path - in addition to the domain, the URL path that the cookie is valid for can be specified. If the domain and path match, then the cookie will be sent in the request.
expires - this attribute is used to set persistent cookies since the cookie does not expire until the set date is exceeded

In Node.js you can easily create this cookie using the cookies package. Again, this is quite low
-level, so you will probably end up using a wrapper, like the cookie-session.
var cookieSession = require('cookie-session');
var express = require('express');
var app = express();
app.use(cookieSession({
  name: 'session',
  keys: [
    process.env.COOKIE_KEY1,
    process.env.COOKIE_KEY2
  ]
}));
app.use(function (req, res, next) {
  var n = req.session.views || 0;
  req.session.views = n++;
  res.end(n + ' views');
});
app.listen(3000);


3. CSRF
Cross-Site Request Forgery is an attack that forces a user to execute unwanted actions on a web application in which they're currently logged in. These attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request.

In Node.js to mitigate this kind of attacks, you can use the csrf module. As it is quite low-level, there are wrappers for different frameworks as well. One example of this is the csurf module: an express middleware for CSRF protection.

On the route handler level you have to do something like this:
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var bodyParser = require('body-parser');
var express = require('express');

// setup route middlewares
var csrfProtection = csrf({ cookie: true });
var parseForm = bodyParser.urlencoded({ extended: false });

// create express app
var app = express();

// we need this because "cookie" is true in csrfProtection
app.use(cookieParser());

app.get('/form', csrfProtection, function(req, res) {
  // pass the csrfToken to the view
  res.render('send', { csrfToken: req.csrfToken() });
});

app.post('/process', parseForm, csrfProtection, function(req, res) {
  res.send('data is being processed');
});

While on the view layer you have to use the CSRF token like this:
<form action="/process" method="POST">
  <input type="hidden" name="_csrf" value="{{csrfToken}}">
  Favorite color: <input type="text" name="favoriteColor">
  <button type="submit">Submit</button>
</form>

4. SQL Injection

SQL injection consists of injection of a partial or complete SQL query via user input. It can read sensitive information or be destructive as well.
Take the following example:
select title, author from books where id=$id
In this example
$id is coming from the user - what if the user enters 2 or 1=1?
The query becomes the following:
select title, author from books where id=2 or 1=1
The easiest way to defend against this kind of attacks is to use parameterized queries or prepared statements.
If you are using PostgreSQL from Node.js then you probably using the node-postgres module. To create a parameterized query all you need to do is:
var q = 'SELECT name FROM books WHERE id = $1';
client.query(q, ['3'], function(err, result) {});
sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. Use this tool to test your applications for SQL injection vulnerabilities.

5. Security HTTP Headers

There are some security-related HTTP headers that your site should set. These headers are:

Strict-Transport-Security enforces secure (HTTP over SSL/TLS) connections to the server
X-Frame-Options provides clickjacking protection
X-XSS-Protection enables the Cross-site scripting (XSS) filter built into most recent web browsers
X-Content-Type-Options prevents browsers from MIME-sniffing a response away from the declared content-type
Content-Security-Policy prevents a wide range of attacks, including Cross-site scripting and other cross-site injections

In Node.js it is easy to set these using the Helmet module:
var express = require('express');
var helmet = require('helmet');
var app = express();

app.use(helmet());
Helmet is available for Koa as well: koa-helmet.

Also, in most architectures, these headers can be set in web server configuration (Apache, nginx), without changing the actual application's code. In nginx it would look something like this:
# nginx.conf
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
For a complete example take a look at this nginx configuration file.
If you quickly want to check if your site has all the necessary headers check out this online checker:
http://cyh.herokuapp.com/cyh.

6. Error Handling using Error Codes, Stack Traces

During different error scenarios, the application may leak sensitive details about the underlying infrastructure, like X-Powered-By: Express.

Stack traces are not treated as vulnerabilities by themselves, but they often reveal information that can be interesting to an attacker. Providing debugging information as a result of operations that generate errors is considered a bad practice. You should always log them, but do not show them to the users.

NPM
With great power comes great responsibility - NPM has lots of packages what you can use instantly, but that comes with a cost: you should check what you are requiring to your applications. They may contain security issues that are critical.

The Node Security Project
Luckily the Node Security project has a great tool that can check your used modules for known vulnerabilities.

npm i nsp -g
# either audit the shrinkwrap
nsp audit-shrinkwrap
# or the package.json
nsp audit-package

You can also use requireSafe to help you with this.





Tags

Post a Comment

1Comments
  1. Thank you for this blog! Thanks for sharing Information on Nodejs. I really Thanks to share the blog for such an beautiful Information.
    https://nareshit.com/nodejs-online-training/

    ReplyDelete
Post a Comment