Home

Node.js IP Blacklisting: Secure Your Express App Easily

209 views

To implement IP blacklisting in a Node.js application, you can manually maintain a list of blacklisted IP addresses and check incoming requests against this list. If a request comes from a blacklisted IP, the server should immediately block the request and optionally log the attempt. Here is a basic example that demonstrates how to implement this:

Step-by-Step Implementation

  1. Set Up Express Application: First, create a simple Express application.

    npm install express
    
  2. Server Code with IP Blacklisting:

    const express = require('express');
    
    const app = express();
    
    // List of blacklisted IPs
    const blacklistedIps = new Set([
      '192.168.1.1',  // Example IPs
      '203.0.113.45', // Example IPs
    ]);
    
    // Middleware to check for blacklisted IPs
    const checkBlacklist = (req, res, next) => {
      const clientIp = req.ip;
    
      if (blacklistedIps.has(clientIp)) {
        console.log(`Blocked request from blacklisted IP: ${clientIp}`);
        return res.status(403).json({ message: 'Your IP is blacklisted.' });
      }
    
      return next();
    };
    
    // Apply the blacklisting middleware to all routes
    app.use(checkBlacklist);
    
    // Define a simple route for demonstration
    app.get('/', (req, res) => {
      res.send('Hello, your IP is not blacklisted.');
    });
    
    // Start the server
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
    

Explanation

  • Blacklisted IPs Set: This set contains IP addresses that are considered dangerous or undesirable. Modify this list according to your needs.

  • Middleware Function: The checkBlacklist middleware function checks if the client's IP is in the blacklistedIps set. If it is, the request is rejected with a 403 Forbidden status. Otherwise, the request proceeds to the next middleware or route handler.

  • Logging: The middleware logs an attempt from a blacklisted IP. This can be extended to log these events into a file or monitoring system for further investigation or alerts.

Important Considerations

  • Dynamic List Management: Consider using a more sophisticated data structure or external database for managing large or dynamically changing lists of IPs.

  • Performance: Be aware of potential performance implications if the blacklist grows large, especially if you're storing it in-memory.

  • IP Spoofing: Keep in mind that IP addresses can sometimes be spoofed, meaning this isn't a foolproof security mechanism but rather part of a multi-layered approach.

  • IPv6: If your system receives IPv6 requests, ensure your logic correctly handles and parses these addresses.

This basic setup allows you to maintain and enforce an IP blacklist in your Node.js application, enhancing security by blocking unwanted traffic.