CloFix WAF · Scripting Engine

CloFix WASM Engine

High-performance WebAssembly module execution engine with memory isolation, timeout protection, and intelligent request processing for custom WAF rules. Runs custom WAF logic with isolated engines for precise request control.

Scripting Engine #2 38 details Published

Overview

💡 How it works: CloFix WASM Engine embeds the wazero WebAssembly runtime (zero dependencies, pure Go). When a request arrives, the engine builds a rich WASMRequest structure with 80+ fields including HTTP details, geo location, threat intel, and bot scores. The engine acquires a pre-warmed module instance from the pool, calls wasm_alloc to allocate memory for the request JSON, writes the data to linear memory, then calls process_request. The module processes the request using 40+ host functions (get_header, set_cookie, rate_limit, is_tor, etc.), returns a decision (allow/block/challenge/redirect) with optional headers/cookies. The engine parses the response, applies any modifications (headers, cookies, redirects), and returns the final decision to the proxy layer. Execution timeouts (default 100ms) prevent runaway modules - if a module times out, the engine marks it as failed and continues to the next module. Instance pooling eliminates cold starts - modules are loaded once and reused across requests. All host functions are pre-registered and validated - modules can only access safe, WAF-specific operations. The included validator tool checks modules before loading - verifies required exports (process_request, wasm_alloc), validates imports (only env/wasi_snapshot_preview1), enforces memory limits, scans for dangerous patterns, and detects incompatible compilers (Rust wasm-bindgen, Go syscall/js). This ensures only safe, compatible modules run in production.

📊 Performance Metrics:

🔒 Security Hardening:

🚀 Deployment Examples:

Feature details

Memory Isolation & Security

Each WASM module runs in its own sandbox with configurable memory limits (default 64MB) - prevents memory corruption and protects host system from malicious modules

Execution Timeout Protection

Configurable timeouts per module (default 100ms) - automatically terminates runaway modules, prevents DoS attacks, and ensures predictable WAF performance

Instance Pooling

Pre-warmed module instances with configurable pool size (default 8) - eliminates cold starts, reduces latency by 70-90%, and handles sudden traffic spikes

Host Function API (40+ Functions)

Rich request/response manipulation, geoIP lookup, threat intelligence, crypto utilities, rate limiting, and string operations - build complex WAF logic without writing custom C extensions

Zero-Copy Memory Access

Direct memory mapping between host and WASM - minimizes data copying overhead, achieves sub-millisecond request processing latency

Multiple Language Support

Write modules in 8+ languages - TinyGo (strongly recommended), Rust (wasm32-wasi), C/C++ (wasi-sdk), AssemblyScript, Zig, and more - use your existing skills

Automatic Module Reload

Hot reload modules without restarting the WAF - zero-downtime rule updates, instant security policy changes, and A/B testing of new rules

Comprehensive Request Data

80+ request fields available - headers, cookies, geo location (country/city/ASN), TLS fingerprint (JA3/JA4), bot detection scores, anomaly scores, and client reputation

Built-in Rate Limiting

Token bucket algorithm with configurable limits per key - protect APIs and endpoints without external Redis or database dependencies

Threat Intelligence Integration

Real-time IP reputation, Tor exit node detection, VPN/proxy detection, datacenter IP identification - block malicious traffic before it reaches your applications

Geolocation Processing

Country, city, region, postal code, latitude/longitude, ASN, ISP - implement geo-fencing, localize responses, or route traffic based on client location

Response Manipulation

Add/remove headers, set cookies with secure/httpOnly flags, redirect requests, customize status codes - modify responses without changing backend code

Advanced String Utilities

Regex matching, substring search, case conversion, URL encoding/decoding - complex pattern matching without performance penalties

Crypto Operations

SHA256 hashing, Base64 encoding/decoding - verify signatures, decode tokens, or transform data without external libraries

JSON Processing

Parse and manipulate JSON request/response bodies - inspect form data, validate JSON schemas, or extract specific fields for analysis

Real-time Statistics

Per-module metrics - execution count, error rate, timeout rate, block rate, average latency - identify performance bottlenecks and security threats

Timeline Analytics

Hourly request/block tracking - visualize traffic patterns, detect attack spikes, and monitor rule effectiveness over time

Top Blocked IPs

Automatic tracking of most frequently blocked IPs - identify attackers, implement additional protections, or report to threat feeds

Structured JSON Logging

Color-coded console output with severity levels (INFO, WARN, ERROR, CRITICAL) - integrate with your existing logging pipeline

Validator Tool Included

Comprehensive WASM validator checks - header validation, import allowlist/blocklist, required exports verification, memory limit checks, and binary pattern analysis

Compiler Detection

Automatic detection of 8+ compilers - identifies browser-only WASM (rejected) vs WAF-compatible modules (accepted) with clear error messages and remediation steps

Dangerous Import Blocking

Hard blocks filesystem access (path_open), network I/O (sock_recv/send), process manipulation (proc_raise), and blocking operations (poll_oneoff) - prevents malicious modules

Configurable Validation Modes

Strict (fail on any ERROR), Standard (fail only on CRITICAL), Permissive (report only) - adapt to your security requirements

ABI Standard Compliance

process_request(ptr, len) → packed uint64 (ptr<<32|len) or two-return convention - TinyGo and Rust compatible out of the box

JSON Output Support

Machine-readable validation results for CI/CD pipelines - automate module testing before deployment

Fail-open Architecture

Configurable fail-open mode - if a module crashes or times out, requests continue processing (default) or can be configured to fail-closed for high-security environments

Concurrent Request Handling

Thread-safe design with sync.Pool and atomic counters - handles thousands of concurrent requests without lock contention

WASI Preview1 Support

Full WASI system interface implementation - modules can use random_get, clock_time_get, fd_write for logging, and memory_grow for dynamic allocation

Module Preloading

Load all modules from directory at startup - warm all pools, verify module integrity, and ensure zero errors before accepting traffic

Memory Limit Enforcement

Hard limits per module (configurable up to 64MB) - prevents memory exhaustion attacks, protects other modules, and ensures fair resource allocation

Per-Request Context

Isolated request context passed to host functions - no cross-request contamination, thread-safe header/body access, and deterministic processing

Binary Pattern Detection

Scans for embedded PE/MZ/ELF/Mach-O headers, x86 NOP sleds, and nested WASM modules - detects injection attacks and malicious payloads

SHA256 Integrity Checks

Automatic hashing of all loaded modules - audit which version is running, detect unauthorized changes, and ensure supply chain security

Multi-domain Support

Different module chains per domain - per-customer WAF rules, white-label deployments, or testing new rules on specific domains

Session Persistence

WASM modules can read/set session cookies and values - implement custom session validation, user tracking, or fraud detection logic

Bot Detection Scores

Pre-calculated bot scores based on User-Agent, header completeness, and behavioral patterns - module can block, challenge, or log suspicious requests

Anomaly Scoring

Request anomaly detection based on method, path length, query parameters, and header patterns - flag unusual requests for additional inspection

Risk Scoring Framework

Weighted risk scoring (INFO=1, WARN=5, ERROR=20, CRITICAL=35) with 0-100 scale - automated pass/fail decisions with CLEAN/LOW/MEDIUM/HIGH/CRITICAL labels

How CloFix WAF uses it

💡 How it works: CloFix WASM Engine embeds the wazero WebAssembly runtime (zero dependencies, pure Go). When a request arrives, the engine builds a rich WASMRequest structure with 80+ fields including HTTP details, geo location, threat intel, and bot scores. The engine acquires a pre-warmed module instance from the pool, calls wasm_alloc to allocate memory for the request JSON, writes the data to linear memory, then calls process_request. The module processes the request using 40+ host functions (get_header, set_cookie, rate_limit, is_tor, etc.), returns a decision (allow/block/challenge/redirect) with optional headers/cookies. The engine parses the response, applies any modifications (headers, cookies, redirects), and returns the final decision to the proxy layer. Execution timeouts (default 100ms) prevent runaway modules - if a module times out, the engine marks it as failed and continues to the next module. Instance pooling eliminates cold starts - modules are loaded once and reused across requests. All host functions are pre-registered and validated - modules can only access safe, WAF-specific operations. The included validator tool checks modules before loading - verifies required exports (process_request, wasm_alloc), validates imports (only env/wasi_snapshot_preview1), enforces memory limits, scans for dangerous patterns, and detects incompatible compilers (Rust wasm-bindgen, Go syscall/js). This ensures only safe, compatible modules run in production.

Canonical URL: https://clofix.com/features/clofix-waf/wasm-engine/