home Tutorial Custom WAF: Shield Your Web Apps

Custom WAF: Shield Your Web Apps

In today’s rapidly evolving web landscape, protecting your application is critical—especially for high-performance systems. Integrating a Custom WAF (Web Application Firewall) into your stack is a proven way to fend off sophisticated attacks. This guide dives deep into the technical workings of a Custom WAF, explains its architecture, and demonstrates how to integrate and configure the custom middleware (available on GitHub) for Express and NestJS. Whether you’re a software developer or a solution architect, understanding the inner workings of a Custom WAF will empower you to tailor security measures that align with your application’s performance requirements.


1. What is a Web Application Firewall (WAF) and Why Do You Need One?

A Web Application Firewall (WAF) is a security tool that filters, monitors, and blocks HTTP traffic between your web application and the Internet. Unlike traditional network firewalls that operate at the network layer, a WAF inspects traffic at the application layer to detect and block attacks that target application vulnerabilities.

Key Technical Benefits of a WAF:

  • Granular Request Filtering: A Custom WAF leverages rule-based systems (often implemented with regular expressions) to parse and analyze both query parameters and request bodies.
  • Layer 7 Protection: By operating at the application layer, it can identify sophisticated patterns such as SQL injections and XSS, even when attackers attempt to obfuscate their payloads.
  • Integration Flexibility: The custom middleware can be integrated directly into frameworks like Express or NestJS, allowing for inline processing of HTTP requests before they reach your application logic.

2. Understanding Attack Vectors Through Technical Examples

To truly appreciate the technical merits of a Custom WAF, consider these common attack scenarios enhanced with code-level insights:

SQL Injection

  • Scenario: A login form builds an SQL query dynamically.
  • Attack Example: An attacker might inject ' OR '1'='1 into a password field.
  • Technical Detail: The middleware applies regex patterns such as /\b(OR|AND)\b\s*\d*\s*=\s*\d*/gi to detect anomalous input. If a match is found, the request is immediately rejected, preventing the altered SQL command from executing.

Cross-Site Scripting (XSS)

Technical Detail: The Custom WAF inspects incoming payloads with a regex like /\<script.*?\>.*?\<\/script\>/gi and halts requests that trigger the rule. This technical check is applied at the middleware level to ensure that no unsanitized script tags are passed to the rendering engine.

Scenario: A comment field accepts raw HTML without sanitization.

Attack Example: Submitting <script>alert('XSS');</script> can execute arbitrary scripts.

3. Integrating the Custom WAF Middleware from GitHub

Before the package hits npm, you can integrate the middleware directly from GitHub. This custom middleware is designed with a focus on performance and extensibility, offering detailed logging and error reporting to help fine-tune your security policies.

Installation:

npm install git+https://github.com/rick001/waf-middleware.git

Express Integration Example:

const express = require('express');
const wafMiddleware = require('waf-middleware');

const app = express();

// Apply Custom WAF middleware early in the request lifecycle
app.use(wafMiddleware());

app.get('/', (req, res) => {
  res.send('Hello, world! This is a secure endpoint protected by our Custom WAF.');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

NestJS Integration Example:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import wafMiddleware from 'waf-middleware';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // Integrate Custom WAF middleware for enhanced request sanitization
  app.use(wafMiddleware());
  await app.listen(3000);
}
bootstrap();

4. How the Custom WAF Middleware Works (Technical Deep-Dive)

The Custom WAF middleware implements multiple technical measures to validate and sanitize incoming HTTP requests before they reach your application.

a. Normalizing Query Parameters

  • Implementation: The middleware converts all query parameter keys to lowercase using a reducer function, ensuring that case variations cannot be used to bypass security checks.
const standardizedQuery = Object.keys(query).reduce((acc, key) => {
  acc[key.toLowerCase()] = query[key];
  return acc;
}, {});

b. Removing Empty Parameters

  • Technical Rationale: Empty query parameters can be exploited to manipulate application logic. The middleware removes these entries to reduce potential attack surfaces.
Object.keys(standardizedQuery).forEach(key => {
  if (standardizedQuery[key] === '') {
    delete standardizedQuery[key];
  }
});

c. Validating Sorting and Field Parameters

  • Detail: For parameters like sort and order, the middleware ensures values match expected patterns (e.g., ‘ASC’ or ‘DESC’) using conditional checks and regex validation.
const validSortValues = ['ASC', 'DESC'];
if (key.includes('sort')) {
  const valueStr = Array.isArray(value) ? value[0] : value;
  if (typeof valueStr === 'string' && !validSortValues.includes(valueStr.toUpperCase())) {
    return res.status(403).json({ message: 'Invalid input detected. Request blocked.' });
  }
}

d. Detecting SQL Injection Attempts

  • Regex Defense: A series of regex patterns scan both query and body parameters for common SQL injection vectors. If a match is detected, the request is blocked.
const sqlPatterns = [
  /\b(OR|AND)\b\s*\d*\s*=\s*\d*/gi,
  /\b(UNION\s+SELECT|INSERT\s+INTO|DELETE\s+FROM|DROP\s+TABLE|ALTER\s+TABLE|UPDATE\s+SET)\b/gi,
  /(--|#|\/\*)/g,
  /\b(EXEC|EXECUTE|SLEEP|WAITFOR|DELAY|HAVING|CAST|CONVERT)\b\s*\(/gi,
];
if (sqlPatterns.some(pattern => pattern.test(JSON.stringify(standardizedQuery)))) {
  return res.status(403).json({ message: 'SQL Injection attempt detected.' });
}

e. Protecting Against XSS

  • Pattern Matching: The middleware utilizes regex to detect dangerous patterns such as <script> tags or JavaScript URLs in the payload.
const xssPattern = /(<script.*?>.*?<\/script>|javascript:|on\w+\s*=)/gi;
if (xssPattern.test(JSON.stringify(standardizedQuery)) || xssPattern.test(JSON.stringify(body))) {
  return res.status(403).json({ message: 'Potential XSS attack detected.' });
}

f. Middleware Control Flow

  • Flow Logic: Once all checks pass, the middleware invokes next() to hand off the request to the subsequent handlers. This layered approach ensures that only sanitized and secure requests reach your application logic.

Integrating a Custom WAF into your web application stack is essential for defending against sophisticated cyber attacks. With advanced technical measures such as query parameter normalization, regex-based input validation, and in-depth detection for SQL injections and XSS attacks, this custom middleware offers robust, inline security for your Express or NestJS applications. Dive into the code, experiment with the configurations, and tailor our Custom WAF to meet the unique security demands of your application.

Leave a Reply