Skip to content
NutekSecurityPublic

About

Web Application Firewall - it all starts with a request... Malicious ones should be dropped, not otherwise.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

5 Commits

Folders and files

Repository files navigation

nutekWAF πŸ›‘οΈ

nutekWAF is a high-performance, language-agnostic Web Application Firewall (WAF) engine built in Rust. It intercepts and blocks malicious payloads using regex-based signature matching. Designed for high throughput and low-latency validation, it offers dual API interfacesβ€”HTTP JSON API and gRPC APIβ€”making it easy to integrate with backend stacks.


Table of Contents

  1. Key Features
  2. Architecture Overview
  3. Configuration
  4. Getting Started
  5. Rules Creation Process
  6. API Reference
  7. Integrating with an Application
  8. Deploying to GCP Cloud Run
  9. Code File Directory & Symbols

Key Features

  • πŸš€ Rust Core: Sub-millisecond matching latency using a compiled SignatureEngine.
  • πŸ”„ Hot-Reload Watcher: Monitors the rules directory and reloads YAML signatures automatically without any service downtime. See hot_reload.rs.
  • πŸ”Œ Dual API Layer: Seamless integration via gRPC (port 8086) and HTTP/JSON (port 8443).
  • πŸ‹ Docker Ready: Built-in multi-stage Dockerfile and docker-compose.yml for rapid deployment.

Architecture Overview

nutekWAF runs as a standalone security microservice (often as a sidecar or a dedicated gateway). Application servers forward incoming request data (query strings, body payloads, headers) to nutekWAF before processing them.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      HTTP (JSON)      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Client App /   │──────────────────────►│  nutekWAF   β”‚
β”‚  API Gateway    │◄──────────────────────│   (Rust)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      gRPC (Proto)     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                 β–²
                                                 β”‚ Reads/Watches
                                                 β”‚
                                          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                          β”‚ YAML Rules  β”‚
                                          β”‚ Directory   β”‚
                                          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Configuration

The service loads its configuration from waf.conf.json. Below is the configuration structure:

{
  "wafServer": {
    "grpc_port": 8086,
    "http_api_port": 8443,
    "log_level": "info"
  },
  "config": {
    "rules_directory": "rules",
    "state_file": "state/signature_enc.yaml.enc",
    "default_action": "block"
  },
  "signatures": {
    "max_length": 65000,
    "rate_limit_per_ip": 100
  }
}

Getting Started

1. Run using Docker Compose (Recommended)

The quickest way to start nutekWAF alongside the vulnerable example-app is using Docker Compose:

docker-compose up --build

This spawns two containers:

  1. nutekWAF-server at http://localhost:8443 (WAF engine)
  2. nutekWAF-example-app at http://localhost:3000 (Node.js demo app protected by the WAF)

Testing the WAF in Action

  • Normal Benign Request (Allowed):

    curl -i "http://localhost:3000/search?q=apple"

    Response: HTTP/1.1 200 OK (Processes query and returns results)

  • SQL Injection Attack Payload (Blocked):

    curl -i "http://localhost:3000/search?q=apple%20UNION%20SELECT%20*%20FROM%20users"

    Response: HTTP/1.1 403 Forbidden

    {"error":"Access Denied by nutekWAF","rules":["sql_injection_owasp"]}

2. Run Locally (Native Rust Build)

Ensure you have the Rust toolchain and protobuf-compiler installed, then run:

cargo build --release
cargo run --release

Rules Creation Process

nutekWAF compiles and checks signatures against rule definitions written in YAML format inside the configured rules directory.

Rule Schema

Every rule file contains a top-level rules list. The individual rules follow the schema represented by the Rule struct:

Field Type Required Description
id String Yes Unique identifier for the rule (e.g. xss_filter_owasp).
name String Yes Human-readable name of the rule.
severity String Yes Severity level (e.g., critical, high, medium, low).
pattern String Yes Regex pattern (supports Rust's regex crate syntax).
description String No Detailed explanation of what the rule detects.
source_type String No Source classification (e.g., manual, automatic).
owner String No Contact email of the rule creator.
update_time String No Timestamp of the latest pattern modification.

Example custom rule: rules/custom_test_rule.yaml

rules:
  - id: custom_test_rule
    name: Custom Test Rule
    severity: medium
    description: "Detects custom test token in incoming payloads"
    pattern: '(?i)MAGIC_TEST_STRING'
    source_type: "manual"
    owner: "security-ops@nuteksecurity.com"
    update_time: "2026-07-19T20:30:00Z"

Hot-Reloading Signatures

When you add, delete, or modify any .yaml file within the rules/ directory:

  1. The filesystem watcher in hot_reload.rs detects the file event.
  2. The WAF engine automatically triggers load_rules_from_dir and recompiles all signatures in-memory.
  3. No process restarts or manual signals are needed!

Bulk Rule Creation from Payload Lists (e.g., PayloadsAllTheThings)

nutekWAF includes a utility script payload_to_rule.py to compile bulk lists of dangerous payloads (such as lists of XSS, SQLi, or Path Traversal payloads from repositories like PayloadsAllTheThings) directly into a single optimized nutekWAF YAML rule.

Structure of the Input File

The input file must be a plain text file containing one dangerous payload per line.

  • Empty lines are automatically skipped.
  • Lines starting with # are treated as comments and ignored.

Example input file (payloads.txt):

# SQL Injection examples
' UNION SELECT NULL, NULL, NULL--
' OR 1=1--
admin' --

Rule Compilation Command

Run the parser script to compile the payload list:

python3 tools/payload_to_rule.py <input_list.txt> <rule_id> <rule_name> <output.yaml>

Example usage:

python3 tools/payload_to_rule.py tools/test_payloads.txt custom_sqli_list "PayloadsAllTheThings SQLi List" rules/patt_sqli.yaml

How it Works

The script reads each raw payload, escapes special regex characters (e.g. . * ? etc.) so they match literally, and combines them using the logical regex OR operator (|) to form a case-insensitive match group: (?i)(payload1|payload2|payload3). This single generated pattern is saved under the rule's pattern key. The resulting file is then saved in the rules directory, where the WAF automatically hot-reloads it in-memory.


API Reference

HTTP JSON API (Port 8443)

1. Check Payload

  • Endpoint: POST /waf/check
  • Headers: Content-Type: application/json
  • Request Body:
    {
      "payload": "user-supplied input or full HTTP request block"
    }
  • Response (Allow - 200 OK):
    {
      "action": "allow",
      "matched_rules": []
    }
  • Response (Block - 403 Forbidden):
    {
      "action": "block",
      "matched_rules": ["sql_injection_owasp"]
    }

2. Get Rules/Signature Snapshot

  • Endpoint: GET /waf/snapshot/signatures
  • Response (200 OK):
    {
      "signature_state": {
        "rule_count": 59,
        "file_format": "v7_owasp",
        "checksum": "sha256:d857823528b12fcf..."
      }
    }

3. Health Check

  • Endpoint: GET /waf/health
  • Response (200 OK): "OK"

gRPC API (Port 8086)

Defined in proto/waf.proto, the service exposes the following RPC methods:

service SignatureService {
    rpc LoadRuleFile (LoadRuleFileRequest) returns (LoadRuleFileResponse);
    rpc InitializeSignatureState (InitializeStateRequest) returns (InitializeStateResponse);
}

Integrating with an Application

To protect a web application, you must introduce middleware that captures incoming user input and validates it against nutekWAF.

Node.js (Express) Integration Example

Here is the implementation matching example-app/index.js:

const express = require('express');
const axios = require('axios');

const app = express();
const port = 3000;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// WAF Middleware
const wafMiddleware = async (req, res, next) => {
    // Reconstruct request properties to evaluate
    const payloadData = [
        req.url,
        JSON.stringify(req.query),
        JSON.stringify(req.body)
    ].join(' ');

    try {
        // Send payload block to WAF HTTP endpoint
        const response = await axios.post('http://localhost:8443/waf/check', {
            payload: payloadData
        });

        // WAF returned 200 OK, proceed to the route handler
        next();
    } catch (error) {
        if (error.response && error.response.status === 403) {
            // WAF returned 403 Forbidden (request blocked)
            const matchedRules = error.response.data.matched_rules || [];
            console.warn(`[WAF BLOCK] Intercepted threat on path ${req.url}. Rules: ${matchedRules.join(', ')}`);
            
            return res.status(403).json({
                error: "Access Denied by nutekWAF",
                rules: matchedRules
            });
        }
        
        // WAF Communication Failure: Fallback Policy
        // In high-security systems, fail closed here. For local testing, we fail open.
        console.error(`[WAF ERROR] Failed to connect to WAF: ${error.message}`);
        next();
    }
};

// Protect all routes with WAF middleware
app.use(wafMiddleware);

// --- Protected Routes ---
app.get('/search', (req, res) => {
    res.send(`Search results for: ${req.query.q || ''}`);
});

app.listen(port, () => {
    console.log(`Application protected by nutekWAF listening on port ${port}`);
});

Deploying to GCP Cloud Run

nutekWAF can be easily deployed in a serverless container environment on Google Cloud Platform (GCP) Cloud Run. Since the core engine is stateless and exposes a standard HTTP API, it fits perfectly within Cloud Run's autoscaling model.

Prerequisites

  • Install the Google Cloud SDK.
  • Enable the Artifact Registry and Cloud Run APIs in your GCP Console or via CLI:
    gcloud services enable artifactregistry.googleapis.com run.googleapis.com

Step-by-Step Deployment

1. Setup Artifact Registry

Create a Docker repository in your region (e.g., us-central1):

gcloud artifacts repositories create nutekwaf-repo \
    --repository-format=docker \
    --location=us-central1 \
    --description="nutekWAF Docker Repository"

Configure docker authentication:

gcloud auth configure-docker us-central1-docker.pkg.dev

2. Build and Tag the Container

Tag the container matching the repository address format: [LOCATION]-docker.pkg.dev/[PROJECT-ID]/[REPOSITORY]/[IMAGE]:[TAG]

# Build the Docker image locally
docker build -t us-central1-docker.pkg.dev/YOUR_PROJECT_ID/nutekwaf-repo/nutekwaf:latest .

3. Push to Artifact Registry

Push the built image to your repository:

docker push us-central1-docker.pkg.dev/YOUR_PROJECT_ID/nutekwaf-repo/nutekwaf:latest

Alternatively, you can build directly on GCP using Cloud Build:

gcloud builds submit --tag us-central1-docker.pkg.dev/YOUR_PROJECT_ID/nutekwaf-repo/nutekwaf:latest .

4. Deploy to Cloud Run

Deploy the container to Cloud Run. Make sure to specify the WAF HTTP port 8443 (as defined in waf.conf.json) via the --port argument:

gcloud run deploy nutekwaf \
    --image=us-central1-docker.pkg.dev/YOUR_PROJECT_ID/nutekwaf-repo/nutekwaf:latest \
    --platform=managed \
    --region=us-central1 \
    --allow-unauthenticated \
    --port=8443

5. Verify the Cloud Run Endpoint

Once deployed, Cloud Run will print the Service URL (e.g., https://nutekwaf-xxxxxx.a.run.app). You can test it by querying the health endpoint:

curl -i https://nutekwaf-xxxxxx.a.run.app/waf/health

Production Architecture on GCP

In a production GCP environment:

  1. Sidecar Deployment: If deploying your web application on Cloud Run as well, you can run nutekWAF as a Cloud Run Sidecar Container to allow high-speed local communications over localhost without external network roundtrips.
  2. Google Cloud Load Balancer: You can configure a Google Cloud Load Balancer (GCLB) with Cloud Armor, or route your web application's ingress traffic through the nutekWAF container before it forwards valid requests to backend services.

Code File Directory & Symbols

Below is the layout of core system code files and their corresponding symbols:

  • πŸ“ src/
    • πŸ“„ main.rs - WAF main daemon entry point, starting gRPC, HTTP API, and the hot-reload loop.
    • πŸ“„ engine.rs - Holds the core regex matcher SignatureEngine.
    • πŸ“„ models.rs - Declares WAF structures such as Rule.
    • πŸ“„ http_api.rs - Configures the routing logic using create_router for the Axum HTTP engine.
    • πŸ“„ grpc_api.rs - Implements the Tonic-based gRPC handlers WafGrpcServer.
    • πŸ“„ hot_reload.rs - Implements asynchronous filesystem watcher logic in start_hot_reload.
  • πŸ“ proto/
    • πŸ“„ waf.proto - Protobuf descriptors for WAF microservices.
  • πŸ“ rules/
    • πŸ“„ default.yaml - Default OWASP signatures.
  • βš™οΈ Cargo.toml - Cargo manifest specifying compiler settings and dependencies.
  • βš™οΈ docker-compose.yml - Configuration for WAF & web application multi-container environment.

About

Web Application Firewall - it all starts with a request... Malicious ones should be dropped, not otherwise.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages