Node.js – Protection from Brute Force and DDOS Attacks

 

If you are building a Node application with Express or with another framework built on express e.g. feathers.js , Koa.js, Kraken, Sails, socket.io or another frameworks listed on http://expressjs.com/en/resources/frameworks.html, you can use the express-rate-limit middleware to protect Your solution from Brute Force and DDOS AttacksThis middleware prevents website, public REST API, and/or endpoints such as password reset from being bombarded by a large set of requests and subsequently crashing, by rate limiting all requests.

Install

$ npm install --save express-rate-limit

Usage

For an API-only server where the rate-limiter should be applied to all requests:

var RateLimit = require('express-rate-limit');
 
app.enable('trust proxy'); // only if you're behind a reverse proxy (Heroku, Bluemix, AWS if you use an ELB, custom Nginx setup, etc) 
 
var limiter = new RateLimit({
  windowMs: 15*60*1000, // 15 minutes 
  max: 100, // limit each IP to 100 requests per windowMs 
  delayMs: 0 // disable delaying - full speed until the max limit is reached 
});
 
//  apply to all requests 
app.use(limiter);

For a “regular” web server (e.g. anything that uses express.static()), where the rate-limiter should only apply to certain requests:

var RateLimit = require('express-rate-limit');
 
app.enable('trust proxy'); // only if you're behind a reverse proxy (Heroku, Bluemix, AWS if you use an ELB, custom Nginx setup, etc) 
 
var apiLimiter = new RateLimit({
  windowMs: 15*60*1000, // 15 minutes 
  max: 100,
  delayMs: 0 // disabled 
});
 
// only apply to requests that begin with /api/ 
app.use('/api/', apiLimiter);

Create multiple instances to apply different rules to different routes:

var RateLimit = require('express-rate-limit');
 
app.enable('trust proxy'); // only if you're behind a reverse proxy (Heroku, Bluemix, AWS if you use an ELB, custom Nginx setup, etc) 
 
var apiLimiter = new RateLimit({
  windowMs: 15*60*1000, // 15 minutes 
  max: 100,
  delayMs: 0 // disabled 
});
app.use('/api/', apiLimiter);
 
var createAccountLimiter = new RateLimit({
  windowMs: 60*60*1000, // 1 hour window 
  delayAfter: 1, // begin slowing down responses after the first request 
  delayMs: 3*1000, // slow down subsequent responses by 3 seconds per request 
  max: 5, // start blocking after 5 requests 
  message: "Too many accounts created from this IP, please try again after an hour"
});
app.post('/create-account', createAccountLimiter, function(req, res) {
 //... 
});

More information You can find out on https://www.npmjs.com/package/express-rate-limit

October 3rd, 2017

Leave a Reply

Your email address will not be published. Required fields are marked *