[ Expressjs ] Cracking nuts, put the IP Address to BlackList
The best way dealing with the un-welcome people is kicking him out of your party. The best way dealing with un-welcome IPs is to BLACK LIST.
Background about today, an APP service running on Node.js server which included a static HTML website and API service. We got few un-welcome IPs list on hand and my boss told me“Peter, black list them.”.
I love Node.js and Express, the design of middleware speedups I get the job done and leaving office early to have a Friday night.
The problem is being broken down to three parts:
- Define blacklist IP
- Geting client IP
- Blocking Client IP, if it is in the blacklist
Extracting Client ID in Express.js is super easy, Router and req are tools which accelerating to extract all the client information which included Header, Cookies, Post Body, Get URL Parameters etc.
Define blacklist IP
Putting unwelcome IPs in an array, which will be used in middleware to check where the router is going to direct.
var BLACKLIST =['192.0.0.1'];
//better to store as an String in process.env.BLACKLIST
Fetch Client IP
Express provide a super friendly req to fetch the client IP within few line of code.
req.connection.remoteAddress return the IP, could be ipv4 or ipv6.
var getClientIp = function(req) {
var ipAddress = req.connection.remoteAddress;if (!ipAddress) {
return '';
}// convert from "::ffff:192.0.0.1" to "192.0.0.1"
if (ipAddress.substr(0, 7) == "::ffff:") {
ipAddress = ipAddress.substr(7)
}return ipAddress;
};
Blocking Client IP, if it is in the blacklist
Add an USER BLOCKING middleware function(req, res, next) inside app.use( ), this middleware function will be executed for every request to the app. Like a filter which let the right IPs to go through.
app.use(function(req, res, next) {
var ipAddress = getClientIp(req);if(BLACKLIST.indexOf(ipAddress) !== -1){
next();
} else {
res.send(ipAddress + ' IP is not in whiteList')
}
});
Putting all together
It is an example of putting above 3 parts together in a Express.js framework. To modify one which fit your BlackList IPs, go and push your IPs in BLACKLIST Array and they will never ever access the service.
var express = require(‘express’)
var app = express()
// Part1, defining blacklist
var BLACKLIST =['192.0.0.1'];// Part2, Geting client IP
var getClientIp = function(req) {
var ipAddress = req.connection.remoteAddress;if (!ipAddress) {
return '';
}// convert from "::ffff:192.0.0.1" to "192.0.0.1"
if (ipAddress.substr(0, 7) == "::ffff:") {
ipAddress = ipAddress.substr(7)
}return ipAddress;
};//Part3, Blocking Client IP, if it is in the blacklist
app.use(function(req, res, next) {
var ipAddress = getClientIp(req); if(BLACKLIST.indexOf(ipAddress) === -1){
next();
} else {
res.send(ipAddress + ' IP is not in whiteList')
}
});app.get(‘/’, function (req, res) {
res.send(‘Hello World!’)
})
#Thanks to Pierre Chamberlain, corrected the mistake BLACKLIST.indexOf(ipAddress) === -1
Remark
- req.headers[‘x-forwarded-for’]
- req.connection.remoteAddress
- req.connection.socket.remoteAddress
1) x-forwarded-for: client, proxy1, proxy2, proxy3
If you are running behind a proxy like NGiNX or what have you, only then you should check for ‘x-forwarded-for’ (by alessioalex)
2) req.connection.remoteAddress
Default server is listening to IPv6 connections and the IPV6_V6ONLY flag isn’t set with the result that IPv4 connections are processed by the same socket. (by Wladimir Palant)
3) req.connection.socket.remoteAddress
On https, req.connection.remoteAddress is undefined, but req.connection.socket.remoteAddress does work(by Mathijs Kwik)
You may also like:
[Javascript] override Object.constructor( )
[Expressjs] override res.send
Like this story? It is helpful to others? It helps me know if you’d like to see write more about his topic and helps people see the story, when tap the heart below.
Reference:
Git:
https://github.com/wahengchang/javascript-must-know/tree/master/middleware_blockIp
express-ipfilter
https://www.npmjs.com/package/express-ipfilter
expressjs.com
http://expressjs.com/en/api.html
stackoverflow
http://stackoverflow.com/questions/10849687/express-js-how-to-get-remote-client-address
http://stackoverflow.com/questions/24896386/request-connection-remoteaddress-now-prefixed-in-ffff-in-node-js
http://stackoverflow.com/questions/5999379/how-to-find-out-the-remote-address-in-node-js-if-it-is-https-request
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!