Blog | G5 Cyber Security

NodeJS: Block Unwanted Request Data

TL;DR

You want to stop users sending requests with specific parameter or header names that could cause problems (like security issues). This guide shows you how to do it in NodeJS using middleware.

Solution

  1. Understand the Problem: Users might try to send data with names like X-Forwarded-For or parameters designed to exploit your application. Blocking these at an early stage is good practice.
    • Why block? Prevent injection attacks, bypass security checks, and avoid unexpected behaviour.
    • Where to block? Middleware is the ideal place – it sits between incoming requests and your route handlers.
  2. Create a Blocklist: Define an array of parameter/header names you want to disallow.
    const blockedParamsAndHeaders = [
      'X-Forwarded-For',
      'User-Agent',
      'Referer',
      'Content-Type',
      'Authorization'
    ];
    
  3. Middleware Function: Write a middleware function to check incoming requests.
    function blockUnwantedData(req, res, next) {
      const requestData = { ...req.query, ...req.headers };
    
      for (const key in requestData) {
        if (blockedParamsAndHeaders.includes(key)) {
          console.warn(`Blocked unwanted data: ${key}`);
          return res.status(400).send('Bad Request - Invalid Data');
        }
      }
    
      next(); // Allow the request to proceed if no blocked items are found.
    }
    
    • Explanation: This function combines query parameters and headers into a single object. It then iterates through this object, checking each key against your blocklist. If a match is found, it logs a warning and sends a 400 Bad Request response.
  4. Apply the Middleware: Use the middleware function in your application.
    const express = require('express');
    const app = express();
    
    // Import blockUnwantedData from previous step...
    app.use(blockUnwantedData);
    
    // Your routes here...
    app.get('/some-route', (req, res) => {
      res.send('Route handled successfully');
    });
    
    • Important: Place the middleware before your route handlers to ensure all requests are checked.
  5. Testing: Test with a request containing a blocked parameter or header.
    1. Use tools like Postman, curl, or Insomnia.
    2. Send a request with X-Forwarded-For: somevalue in the headers.
    3. Verify you receive a 400 Bad Request response and see the warning message in your console.
  6. Refinements (Optional):
    • Case-Insensitive Matching: Convert both keys and blocklist items to lowercase for case-insensitive blocking.
      if (blockedParamsAndHeaders.map(item => item.toLowerCase()).includes(key.toLowerCase())) { ... }
    • More Sophisticated Validation: Use a validation library like express-validator for more complex checks beyond just blocking names.
Exit mobile version