Node.js App Security

Nowadays, we see a lot of serious security breaches in the software. Someone said that, If you develop software, security is a part of your job.
Here are some tips which you can use to improve the security of your node app:

**Helmet: **Helmet is just a collection of small middleware functions that set security-related HTTP response headers:

  • Strict-Transport-Security:  secures (HTTP over SSL/TLS) the connections to the server.
  • hidePoweredBy:  removes the X-Powered-By header.
  • hpkp:  adds Public Key Pinning headers to prevent man-in-the-middle attacks with forged certificates.
  • noCache:  is used for setting Cache-Control to disable client-side caching.
  • Content-Security-Policy:  prevents a wide range of attacks, including cross-site scripting and other cross-site injections.

Install Helmet:
npm install --save helmet

Then to use it in your code:

const express = require('express');
const helmet = require('helmet');
 
const app = express();
 
app.use(helmet());

Brute Force Protection

Brute forcing is the systematically enumerating of all possible candidates for a solution and checking whether each candidate satisfies the problem’s statement. It’s a trial-and-error method used to obtain information such as a user password. In web applications, a login endpoint can be the perfect candidate for this.

To protect your applications from these kinds of attacks, you can use the rate-limiter-flexible package in Node.js.

const redis = require('redis');
const {RateLimiterRedis} = require('rate-limiter-flexible');

const redisClient = redis.createClient({
  host: 'redis',
  port: 6379,
  enable_offline_queue: false,
});

const rateLimiter = new RateLimiterRedis({
  redis: redisClient,
  keyPrefix: 'middleware',
  points: 20, // 20 requests
  duration: 1, // per 1 minute by IP
});

const rateLimiterMiddleware = (req, res, next) => {
  rateLimiter.consume(req.connection.remoteAddress)
    .then(() => {
      next();
    })
    .catch(() => {
      res.status(429).send('Too Many Requests');
    });
};

module.exports = rateLimiterMiddleware;

Session Management

The importance of cookies cannot be understated, especially in the dynamic web applications, which need to maintain state across a stateless protocol such as HTTP.

Cookie Flags

A list of the attributes which can be set for each cookie and their meanings is as follows:

  • Secure - It gives the permission to send the cookie only if the request is being sent over HTTPS.
  • HttpOnly - We use this to prevent attacks such as cross-site scripting. It does not allow the cookie to be accessed via JavaScript.

Cookie Scope

  • Domain - This is used to compare the domain of the server from which the URL is being requested. If the domain matches or is a sub-domain of the root domain, then it will move forward.
  • Path - We can specify the URL path for which the cookie is valid. If the domain and path match, then the cookie will be sent in the request.
  • Expires - Use to set the expiration date for cookies.
const session = require('cookie-session')
const express = require('express')
const app = express()

const expiryDate = new Date(Date.now() + 60 * 60 * 1000) // 1 hour expiry time

app.use(session({
  name: 'session',
  keys: ['key1', 'key2'],
  cookie: {
    secure: true,
    httpOnly: true,
    domain: 'examplexyz.com',
    path: 'foo1/bar1',
    expires: expiryDate
  }
}))

Ensure your dependencies are secure: It is very convenient if we use npm to manage the application’s dependencies. The packages may contain critical security vulnerabilities, and one weak link in your dependencies can affect the app security.

We can use ‘npm audit’ to analyze our dependencies.

npm audit

If you want to stay more secure, consider Snyk. It aims to provide a tool that can detect and fix security-related issues in your codebase.

It works for command-line and a Github that checks your application with Snyk’s open source vulnerability database for any known vulnerabilities in your dependencies. Install the snyk CLI with the following command :

npm install -g snyk
cd your-app

You can test your application by executing following command:

snyk test

Use this command to open a wizard, which takes you through the process to fix the vulnerabilities:

snyk wizard

For more details, you can visit snyk.io.

As we know, NodeJs app security is a big topic, so it is not possible to try and cover it all here. These were some small tips which take less time, and you can use it to improve the security of your NodeJs app.

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype