Technical Reference · Security Architecture

CloFix WAF: 10-Stage Request Inspection Pipeline

A complete technical reference for how CloFix Web Application Firewall processes every incoming HTTP/HTTPS request through ten sequential security stages — from behavioral heuristics and signature matching to AI-powered anomaly detection, intelligent load balancing, and response sanitization.

📅 Updated March 2026 🕐 25 min read 🌐 clofix.com WAF Architecture OWASP CRS v4 Production Ready v4.2
10
Inspection Stages
<2ms
Avg Latency P99
99.97%
Threat Detection
500K+
Rules & Signatures

CloFix WAF operates as a fully transparent reverse proxy, sitting between your clients and origin servers. Unlike traditional WAFs that apply rules sequentially and stop at the first match, CloFix evaluates all stages in parallel where possible and aggregates a composite risk score before rendering a verdict. This architecture eliminates single-point blind spots and significantly reduces both false positives and false negatives.

ℹ️
How to read this document: Each stage is documented with its purpose, detailed operations, configuration syntax, and links to related documentation. Use the sidebar Table of Contents to navigate directly to any stage.

📊 Interactive Pipeline Visualization

Click any stage node to view an inline summary. The animated dots represent live request packets flowing through the pipeline.

// request flow — click any stage node for details
01
📈
BEHAVIOR ANALYZER
Heuristics & Scoring
02
📜
CRS ENGINE
Signature Matching
03
⚙️
JS ENGINE
Runtime Analysis
04
🔧
LUA ENGINE
Custom Logic
05
🧠
AI NEURAL
Anomaly Score
06
🛡️
CLOFIX CORE
Risk Arbiter
07
⚖️
CUSTOM RULES
Policy Verdict
08
💉
JS INJECTOR
Client-side Shield
09
⚖️
LOAD BALANCER
Traffic Distribution
10
🏢
BACKEND SERVER
Origin Response

⚡ Performance Architecture

CloFix is engineered to add less than 2ms of latency at the 99th percentile while processing all 10 stages. This is achieved through a combination of the Coraza engine with Hyperscan SIMD regex acceleration, connection pooling, and parallel stage evaluation where data dependencies allow.

MetricCloFix WAFIndustry AverageStatus
Average Request Latency (P50)<0.8ms3–8ms✓ 4× faster
P99 Tail Latency<2ms15–40ms✓ Exceptional
Throughput (req/s per node)120,000+20,000–50,000✓ 2.4–6× higher
Threat Detection Rate99.97%92–96%✓ Best-in-class
False Positive Rate (default config)<0.02%0.5–2%✓ 25× lower
Zero-Day Detection (AI stage)~89%N/A (signature only)✓ AI advantage
Rule Evaluation EngineCoraza + HyperscanModSecurity✓ 5–10× faster

📈 Stage 01: Behavior Analyzer — Browser vs Tool Detection Engine

01
Behavior Analyzer — Production Heuristics (13-layer)
JA3/JA4 TLS, velocity, path entropy, timing CV, error rate, injection patterns, UA rotation, burst detection
JA3 fingerprint DBRate limiting 60rpmTool scoring 0-100

Production-hardened behavioral analysis engine — implements 13-layer heuristic detection (velocity, entropy, timing consistency, static asset ratio, error rate, sequential enumeration, parameter fuzzing, UA rotation, response time CV, burst patterns). Uses JA3 TLS fingerprinting with 85+ browser signature database (Chrome 120+, Firefox 121, Safari 17, Edge, Brave, Tor). Calculates composite tool score (0–100) with configurable thresholds. Blocks ~40% of malicious traffic at near-zero cost.

🔍 Detection Layers (13+ Signals)
  • JA3 Browser DB: Chrome 120+, Firefox 121, Safari 17, Edge, Brave — instant allow if matched. Confidence 1.0.
  • Velocity (Rate Limiting): >120 req/min = tool. Extreme bursts >480/min add +50pts. Default threshold: 60 req/min with burst 100.
  • Path Entropy: <0.5 entropy = low diversity scanner (+20pts). Calculates Shannon entropy over normalized paths.
  • Timing Coefficient of Variation: <20% variance = machine timing (+25pts). Humans have 20-40% variance.
  • Static Asset Ratio: <8% static assets (CSS/JS/images) = tool (+15pts). Real users load 10-30% assets.
  • Error Rate (4xx/5xx): >30% error rate = scanner (+25pts). Legitimate 404s typically 10-15%.
  • Sequential Enumeration: /item/1, /item/2 pattern detection = +35pts. Uses extractLastNumber() logic.
  • Parameter Fuzzing: >10 unique parameters per path = +30pts. Detects scanner parameter enumeration.
  • UA Rotation: >3 distinct User-Agents in 10 requests = evasion attempt (+25pts).
  • Response Time CV: <15% uniform timing = automation (+20pts). Tools produce consistent response times.
  • Burst Detection: 20+ requests after silence = +30pts. Sudden spikes after idle period.
  • Injection Pattern Detection: SQLi/XSS/LFI signatures in query string = +50pts. Patterns: '--, 1=1--, <script, javascript:, union+select, exec(, base64_decode(.
  • Empty/Minimal UA: len(UA)=0 → +45pts, len(UA)<20 → +35pts, len(UA)<40 → +15pts.
  • Path Traversal: ../, ..\\, %2e%2e patterns = +45pts.
🎯 Scoring Logic: Score ≥85 = TOOL (block/challenge). Score 65–84 = monitor (challenge). Score 30–64 = elevated suspicion. Score <30 = ALLOW. Established sessions (>10 min) with clean history reduce suspicion by -15pts. Block duration = 15min.
⚙️ Configuration (Default BEConfig)
toolVelocityThreshold = 120 // req/min toolEntropyThreshold = 0.5 // path diversity toolTimingCVThreshold = 0.20 // 20% variance toolErrorThreshold = 0.30 // 30% error rate toolAssetThreshold = 0.08 // 8% static assets toolSequentialThreshold = 0.25 // 25% sequential browserScoreThreshold = 85 // >85 = tool learningScoreThreshold = 65 // monitor zone rate_limit { requests_per_minute 60; burst 100; key $binary_remote_addr; action challenge; }
// JA3 Browser Database (excerpt) "e7d97a9fb3e5f8c9c2c1b5f8c9c2c1b5": {Name:"Chrome 120+", Family:"Chrome"}, "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6": {Name:"Firefox 121", Family:"Firefox"}, "e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0": {Name:"Safari 17", Family:"Safari"}
📌 ProcessRequest Logic: If JA3 matches browser DB → immediate ALLOW. Otherwise profile key = JA3 hash or IP fallback. Profile tracks last 200 requests, analyzes last 10min window via AnalyzeBehavior(). Tool score computed from 16+ signals. Block duration = 15min with auto-expiry.

The CRS Engine implements the complete OWASP Core Rule Set v4 — the industry benchmark for WAF rule coverage. It processes requests through four phases (request headers, request body, response headers, response body) applying over 200 individual rules across 25 rule files. Rather than binary block/allow decisions per rule, it uses anomaly scoring — each matched rule adds points; the total is forwarded to CloFix Core.

SQL Injection (942xxx)XSS (941xxx)LFI (930xxx)RFI (931xxx)Cmd Injection (932xxx)SSRF (933xxx)NoSQL InjectionPrototype PollutionXXESSTI
Rule File Coverage
  • 920xxx — Protocol Enforcement: HTTP method restrictions, header completeness validation, Content-Type enforcement, character encoding validation. Blocks malformed requests that evade downstream parsing.
  • 930xxx — LFI / Path Traversal: Detects ../ sequences, null byte injection, URL-encoded traversal (%2e%2e%2f), and double-encoding techniques used to escape the web root.
  • 931xxx — RFI (Remote File Inclusion): Blocks http:// and ftp:// in file parameters, PHP wrapper schemes (php://, data://), and cloud metadata endpoint URLs (169.254.169.254).
  • 932xxx — Command Injection: Unix shell metacharacters (;, |, &&, backtick), Windows command separators, OS command sequences (whoami, passwd, /etc/shadow), and command substitution patterns.
  • 933xxx — PHP Injection: PHP function calls in user input (eval(), system(), exec()), PHP wrappers, and PHP variable injection patterns.
  • 941xxx — XSS: HTML event handlers (onerror, onload), JavaScript protocol URIs (javascript:), DOM sinks, and obfuscated script injection using character encoding.
  • 942xxx — SQL Injection: UNION-based, time-based blind (SLEEP(), WAITFOR DELAY), boolean-based blind, error-based, and stacked queries. Covers MySQL, MSSQL, Oracle, PostgreSQL, and SQLite dialects.
Paranoia Levels Explained
LevelDescriptionUse Case
1Base rules only, very low false positivesPublic-facing marketing sites
2Additional rules, low false positive rateE-commerce, SaaS platforms
3Stricter rules, moderate false positivesFinancial, healthcare APIs
4Maximum security, requires tuningGovernment, military, PCI-DSS
# CRS Engine Configuration
crs {
  enabled            on;
  paranoid_level     2;
  anomaly_threshold  5;

  # Rule-level scoring weights
  score_critical  5;
  score_error     4;
  score_warning   3;
  score_notice    2;

  # Exclude specific rule IDs if needed
  rule_exclusions "920300,942450";
}
📘 Complete CRS Documentation →

Modern attackers frequently obfuscate malicious JavaScript to evade signature-based detection. The JS Engine executes payloads in a secure V8-based sandbox with a 2-second execution timeout, automatically deobfuscating layered encoding schemes and detecting dangerous code patterns that only emerge at runtime. All JavaScript files served by your application are also pre-scanned on a configurable interval.

Detection Capabilities
  • Multi-layer Payload Deobfuscation: Automatically decodes Base64 (atob()), hex escape sequences (\x41\x42), Unicode escapes (\u0041), and URL encoding. Handles nested encoding: Base64 inside hex inside URL encoding — the engine iterates until no further decoding is possible or a threat pattern is found.
  • DOM-based XSS Detection: Identifies dangerous sinks with user-controlled data flows: document.write(), innerHTML, outerHTML, eval(), setTimeout(string), setInterval(string), location.href. Performs taint analysis to trace data from sources (location.search, document.cookie) to sinks.
  • Prototype Pollution Detection: Detects attempts to inject properties into Object.prototype via __proto__, constructor.prototype, or Object.setPrototypeOf() with attacker-controlled keys. This can lead to privilege escalation and RCE in Node.js environments.
  • Pattern Extraction & Caching: Scans all served JavaScript files every 5 minutes, extracting function signatures, regex patterns, and API endpoint strings. Cached patterns enable zero-latency matching for subsequent requests without full sandbox execution.
  • CVE Exploit Signature Matching: Maintains a continuously updated database of JavaScript CVE exploit patterns. Detects exploitation of known library vulnerabilities (jQuery XSS, Lodash Prototype Pollution, Angular Template Injection) by matching characteristic code patterns.
Configuration & Tuning
# JS Engine Configuration
js_engine {
  enabled            on;
  execution_timeout  2s;
  scan_interval      5m;
  max_payload_size   512kb;

  # File extensions to scan
  include_extensions .js .mjs .cjs;

  # Deobfuscation depth (iterations)
  decode_depth      8;

  # CVE pattern database
  cve_db            auto-update;
  cve_update_interval 1h;
}
⚠️
Performance note: Full sandbox execution only runs for requests where the CRS Engine flags a JavaScript-related anomaly score ≥ 2, or for new JavaScript files not yet in the pattern cache. This keeps average overhead below 0.3ms.
📘 JavaScript Engine Guide →

The Lua Engine exposes the full power of CloFix's internal API to user-defined scripts, enabling organizations to implement security logic that no off-the-shelf WAF rule can express. Scripts run in an isolated LuaJIT environment with direct access to request context, threat intelligence services, cross-request shared memory dictionaries, and all CloFix security APIs. Scripts are organized per domain in ./lua_script/<domain>/ and executed in alphabetical order.

Available APIs
  • clofix.request — Full Request Context: Read IP, all headers, body (raw/parsed), cookies, query parameters, GeoIP data (country, city, ASN), TLS fingerprint (JA3/JA4), HTTP method, URI, protocol version, and all scores from previous stages.
  • clofix.is_tor(ip) / clofix.is_vpn(ip): Real-time queries against continuously updated anonymization databases. Returns a boolean and a confidence score (0–1).
  • clofix.ip_reputation(ip): Returns a composite reputation object: { score: 0-100, categories: ["botnet","scanner"], last_seen: timestamp } sourced from multiple threat intelligence feeds.
  • clofix.rate_limit_ip(key, limit, window): Atomic counter-based rate limiting with configurable key (any string), limit, and time window. Uses shared memory for cross-worker consistency. Returns { allowed: bool, count: n, remaining: n }.
  • clofix.normalize_payload(input): Multi-pass normalization supporting URL decoding, Base64 decoding, HTML entity decoding, hex unescaping, and Unicode normalization. Returns both the decoded string and the encoding types detected.
  • clofix.log_attack(name, type, payload): Structured attack log with automatic capture of full request context, geographic data, TLS fingerprint, and all stage scores. Emits to SIEM, Webhook, and dashboard simultaneously.
  • Shared Dictionaries: Cross-request, cross-worker persistent state using Lua shared dictionaries (lua_shared_dict). Used for distributed rate limiting, progressive blocking (track failed auth attempts), and IP reputation caching.
Example: API Key Validation Script
-- lua_script/example.com/01_api_auth.lua
local req = clofix.request

-- Only apply to /api/ paths
if not req.uri:match('^/api/') then return end

local api_key = req.headers['X-API-Key']

-- Missing API key
if not api_key then
  clofix.log_attack('MISSING_API_KEY', 'auth', req.uri)
  return clofix.block(401, '{"error":"API key required"}')
end

-- Rate limit: 1000 req/hr per API key
local rl = clofix.rate_limit_ip(api_key, 1000, 3600)
if not rl.allowed then
  return clofix.block(429, '{"error":"Rate limit exceeded"}')
end

-- Check IP reputation
local rep = clofix.ip_reputation(req.ip)
if rep.score > 80 then
  clofix.log_attack('HIGH_RISK_IP', 'reputation', req.ip)
  return clofix.challenge()
end
📘 Full Lua Scripting Reference →

The AI Neural Engine is CloFix's most sophisticated detection layer — a multi-model machine learning system trained on billions of HTTP requests. Unlike all previous stages which rely on known patterns, the AI Engine detects previously unseen attack patterns by identifying statistical anomalies in request structure, timing, and behavioral signals. It is specifically designed to catch the ~10% of sophisticated attacks that evade all signature-based methods.

AI Detection Modules
  • AI Attack Detector (ML Classification): An ensemble of Random Forest, Gradient Boosting, and Transformer models trained on 2B+ labeled requests. Features include 340+ request characteristics — header ordering, value distributions, parameter naming patterns, timing jitter, and content entropy. Outputs a threat probability (0.0–1.0); threshold 0.85 triggers blocking.
  • Traffic Anomaly Detection: Longitudinal behavioral baseline built per-domain over 7 days. Detects statistically significant deviations: traffic volume spikes (>3σ), unusual endpoint access patterns, geographic shifts, and time-of-day anomalies. Integrated DDoS detection uses per-second sliding windows with automatic mitigation escalation.
  • Automation Tool Fingerprinting: Detects headless browsers (Puppeteer, Playwright, Selenium WebDriver, PhantomJS, Splash) through 60+ JavaScript behavioral signals: navigator.webdriver property, missing browser APIs, Chrome DevTools Protocol artifacts, inconsistent plugin arrays, and anomalous performance timing.
  • Device Identity Blocking: Cross-session device fingerprint validation using Canvas API rendering, WebGL renderer strings, AudioContext fingerprinting, and font measurement timing. Detects emulated devices, modified fingerprints, and cross-session impersonation attacks.
  • Human Biometric Analysis: When JS Injector is active, analyzes mouse movement velocity and curvature, keyboard inter-key timing (dwell time, flight time), scroll behavior patterns, and touch pressure/area (mobile). These signals are evaluated against a biometric classifier achieving 97.3% human/bot discrimination accuracy.
  • JavaScript Cryptojacking Detection: Monitors CPU utilization patterns, WebAssembly execution, and WebWorker spawning for cryptocurrency mining behavioral signatures. Cross-references against known mining pool domains and script hashes.
Model Architecture
ModelThreat TypeAccuracy
Transformer (BERT-variant)Request content anomalies96.2%
Random ForestGeneral threat classification94.8%
LSTMSession behavior sequences93.1%
Biometric ClassifierHuman vs bot verification97.3%
Isolation ForestTraffic anomaly detection91.7%
# AI Engine Configuration
ai_engine {
  enabled             on;
  model_version       v3.2;
  anomaly_threshold   0.85;
  baseline_window     7d;

  ai_attack_detector {
    ml_classification  on;
    human_biometric    on;
    hardware_fp        on;
  }

  automation_detection {
    enabled         on;
    check_webdriver on;
    check_plugins   on;
    timing_analysis on;
  }
}
📘 AI Protection Reference →

CloFix Core is the central nervous system of the entire WAF. After all five preceding stages have evaluated the request and contributed their scores, CloFix Core aggregates them through a weighted formula, applies any user-defined CloFixRule directives and bypass conditions, and renders a final verdict: ALLOW, CHALLENGE, or BLOCK. This stage also hosts the unified rule processing engine that supports CloFixRule directives, JavaScript, and Lua rules in the same deployment.

Risk Score Formula
// composite risk score calculation
TotalRisk = (BehaviorScore × 0.20)
             + (CRSScore      × 0.35)
             + (JSScore       × 0.10)
             + (LuaScore      × 0.10)
             + (AIScore       × 0.25)
< 30
✅ ALLOW
Forward to backend normally
30–70
⚠️ CHALLENGE
Serve CAPTCHA or JS challenge
> 70
🚫 BLOCK
Return 403 with attack record
Unified Rule Processing
  • CloFixRule Directive: CRS-style declarative rules with variables (ARGS, REQUEST_HEADERS, REQUEST_BODY, RESPONSE_BODY), operators (@rx regex, @contains, @streq, @pm phrase match), transformations (t:lowercase, t:urlDecode, t:htmlEntityDecode), and actions (block, challenge, log, allow).
  • Intelligent Bypass System: Exclude rules from firing by: rule ID, rule tag (attack-sqli, paranoia-level/3), processing phase (1–4), request path (/health, /api/public/*), source IP (127.0.0.1, 192.168.0.0/16), or specific header values.
  • Virtual Patching: Deploy a CloFixRule targeting a specific vulnerability's request signature within minutes of a CVE being published — no application code change required. This is particularly valuable for zero-day vulnerabilities like Log4Shell (CVE-2021-44228) where a virtual patch can be deployed in under 5 minutes.
  • Rule Groups & Profiles: Organize rules into named groups: PCI, HIPAA, WordPress, Laravel, API-Gateway, GraphQL. Enable or disable entire groups with a single toggle. Assign execution priority (1–1000) to control order.
Configuration Reference
# Anomaly Scoring
anomaly_scoring {
  inbound_threshold   5;
  outbound_threshold  4;
  blocking_paranoia   2;
}

# Rule Groups
rule_groups {
  group "PCI"           enabled on;
  group "WordPress"     enabled on;
  group "API-Gateway"   enabled on;
}

# Intelligent Bypass
bypass {
  rule_ids  "942100,941100";
  tags      "paranoia-level/4";
  paths     "/health,/metrics,/api/public/*";
  ips       "192.168.1.0/24";
}
Example: Virtual Patch (Log4Shell)
# Virtual patch for CVE-2021-44228 (Log4Shell)
CloFixRule "id:9001,
  phase:2,
  deny,
  t:none,t:urlDecode,t:lowercase,
  msg:'Log4Shell exploit attempt',
  tag:'CVE-2021-44228',
  severity:CRITICAL,
  chain"
CloFixRule "REQUEST_HEADERS|ARGS|REQUEST_BODY
  @rx \$\{.*j.*n.*d.*i.*:
  t:none,t:urlDecode,t:lowercase";
📘 Custom Rules & Scripting →

Custom Rules is the final human-controlled override layer before traffic is processed. It allows security and operations teams to express organization-specific policies that the automated engines cannot infer — such as allowing a trusted partner's IP range to bypass bot detection, blocking entire countries during a DDoS incident, or enforcing API authentication on specific endpoints only during business hours.

Policy Types
  • IP Allowlist / Blocklist: Permanent and temporary IP-level overrides. Allowlisted IPs bypass all WAF stages (except logging). Blocklisted IPs are rejected immediately at Stage 1. Supports CIDR notation (10.0.0.0/8), individual IPs, and ASN-level blocks. Sync with external threat feeds via API.
  • GeoIP Exceptions: Override geographic block policies for specific partner IPs or CIDR ranges. Example: Allow Bangladesh (BD) IPs from a specific ISP for a local payment gateway while keeping the country in the geo-block list for all other traffic.
  • Path-Specific Security Policies: Apply elevated security profiles to sensitive endpoints. Enforce mandatory HTTPS, require specific authentication headers, enable additional Lua checks, or apply stricter CRS paranoia levels — all scoped to a specific URI path or pattern.
  • Time-Based Access Control: Restrict endpoint access by time of day, day of week, or calendar schedule. Use cases: maintenance windows (block all traffic to /admin outside business hours), scheduled report endpoints (allow only between 2–4 AM UTC), or geographically-aware time restrictions.
  • Header-Based Token Validation: Validate custom security headers, API keys, JWT tokens (signature verification, expiry check), and HMAC signatures without custom code. Configure per-endpoint with configurable rejection messages.
Configuration Examples
# IP Access Control
allowlist {
  ips "192.168.0.0/16,10.0.0.0/8"; # Internal
  ips "203.0.113.0/24";           # Partner
  bypass_waf on;
}
blocklist {
  ips "45.33.0.0/16";
  action block;
  log_reason "Known attack infrastructure";
}

# Admin endpoint — strict policy
path_policy "/admin/*" {
  require_header  "X-Admin-Token";
  paranoia_level  4;
  geo_allow       "BD,US,GB";
  time_allow      "09:00-18:00 Mon-Fri";
  timezone        "Asia/Dhaka";
}

# Health check — bypass all WAF
path_policy "/health" {
  bypass_waf  on;
  allow_ips   "10.0.0.0/8";
}
📘 CloFixRule Custom Directives →

The JS Injector operates on the response path — after CloFix has decided to ALLOW or CHALLENGE a request, it inspects the response body and injects JavaScript code into HTML pages. This enables a browser-native layer of security that complements all server-side stages, collecting telemetry that feeds back into the AI Neural Engine for future requests and serving interactive challenges when needed.

Injection Capabilities
  • Anti-CSRF Token Injection: Automatically inserts hidden CSRF token fields into all HTML forms (<input type="hidden" name="_csrf">) and injects the same token as a meta tag and into AJAX request headers via a small interceptor script. Tokens are cryptographically bound to the user session and validated server-side.
  • Bot Detection Telemetry Collection: Injects a lightweight (~4KB) telemetry script that collects: mouse movement velocity and trajectory, keyboard dwell/flight timing, scroll behavior, touch event patterns, viewport interactions, and browser environment signals. All data is encrypted and sent to the CloFix scoring API, which updates the AI model's confidence in the client's humanity score in real time.
  • Headless Browser Detection: Injects a probe script that checks for 60+ headless browser artifacts: navigator.webdriver flag, Chrome DevTools Protocol patterns, unusual window.outerWidth values, missing browser plugin arrays, Permissions API inconsistencies, and inconsistent timing in requestAnimationFrame callbacks.
  • CAPTCHA Challenge Rendering: When risk score falls in the CHALLENGE range (30–70), injects a full-page challenge overlay. Supports: CloFix native JS proof-of-work challenge, hCaptcha, reCAPTCHA v3 (invisible), and Turnstile (Cloudflare). On successful completion, issues a signed challenge cookie valid for a configurable TTL (default: 24h).
  • DOM Integrity Monitoring: Injects a MutationObserver that monitors the DOM for unauthorized modifications — detecting Magecart-style form-hijacking scripts, injected iframes, and unauthorized script tag insertion. Reports violations to the CloFix SIEM endpoint without affecting user experience.
  • Session Integrity Binding: Issues a cryptographically signed session token that binds the browser session to device fingerprint, IP, and user agent. Subsequent requests that don't match the binding are escalated to the CHALLENGE verdict.
Configuration
# JS Injector Configuration
js_injector {
  enabled          on;

  csrf_protection {
    enabled      on;
    token_ttl    1h;
    same_site    Strict;
  }

  bot_telemetry {
    enabled      on;
    sample_rate  100%;
  }

  captcha {
    provider     clofix; # or hcaptcha, recaptcha
    challenge_ttl 24h;
    difficulty   medium;
  }

  # Skip injection for specific content types
  skip_content_types "application/json
    application/xml text/plain";
}
💡
Streaming note: The JS Injector uses a streaming HTML parser — it injects code at the </head> tag without buffering the entire response, keeping injection latency under 0.1ms even for large pages.

Once a request has cleared all WAF stages, the Load Balancer selects the optimal backend server and forwards the request. On the response path, it performs critical response sanitization — stripping all headers and response body content that would reveal internal infrastructure topology to potential attackers. This stage enforces a 99.99% availability SLA through active/passive health monitoring, automatic failover, and connection draining.

Load Balancing Algorithms
  • Round Robin: Distributes requests evenly across all healthy backends in circular order. Ideal for homogeneous server fleets with similar hardware and response times.
  • Least Connections: Routes each new request to the backend with the fewest active connections. Best for mixed workloads where request duration varies significantly (short API calls + long file downloads).
  • IP Hash: Hashes the client IP to deterministically select a backend. Provides natural session affinity without cookies — ideal for applications that store session state in memory without a shared session store.
  • Weighted Round Robin: Assigns traffic proportionally based on configured weights. Route 70% to high-capacity servers and 30% to smaller instances, or gradually shift traffic during canary deployments.
  • Backend Information Hiding: Automatically strips 30+ response headers that expose infrastructure details: Server, X-Powered-By, X-Backend-Server, X-Upstream, Via, X-Real-IP, X-Cache, X-Varnish, X-Debug, X-Request-ID. Replaces Server with a configurable value or removes it entirely.
  • Response Body URL Rewriting: Parses HTML, JSON, and XML response bodies and rewrites any occurrence of backend domain names or internal IP addresses to the public frontend domain. Protects against SSRF reconnaissance from verbose error messages and API responses.
Health Monitoring & Failover
  • Active Health Checks: Proactive HTTP/HTTPS health check requests sent directly to each backend on a configurable interval (default: 10s). Checks the configured path, validates response status code and optional body content, and removes failed backends from rotation after a configurable failure threshold.
  • Passive Health Monitoring: Observes real traffic for connection failures, timeouts, and 5xx responses. Tracks max_fails (default: 3) within fail_timeout (default: 30s). Less aggressive than active checks — used as a complement to catch transient errors.
  • Connection Draining: When a backend is removed from rotation (maintenance or failure), in-flight requests are allowed to complete before the connection pool is drained. New requests are immediately routed to healthy backends. Zero dropped requests during rolling deployments.
# Load Balancer Configuration
backends {
  server https://origin1.example.com:443
    weight=10 max_fails=3 fail_timeout=30s;
  server https://origin2.example.com:443
    weight=5;
  server https://backup.example.com:443
    weight=1 backup=true;
}

load_balancer {
  algorithm       least_conn;
  sticky_session  on;
  cookie_name     CF_BACKEND;

  health_check {
    enabled   on;
    path      /health;
    interval  10s;
    timeout   3s;
    status    200;
  }

  alerts {
    slack_webhook "https://hooks.slack.com/…";
    email         "[email protected]";
  }
}
📘 Load Balancer Full Reference →

The Backend Server stage is the final destination for verified requests. After all ten stages have been traversed, the sanitized request is forwarded to your origin server. The response travels back through CloFix, where a comprehensive outbound processing pipeline ensures no internal infrastructure information leaks to the client — preserving total confidentiality of your server topology, technology stack, and internal network architecture.

Outbound Response Processing
  • Complete Header Stripping: Every backend response header that could reveal infrastructure information is automatically removed: Server, X-Powered-By, X-Backend-Server, X-Upstream, Via, X-Real-IP, X-Forwarded-For, X-Cache, X-Cache-Hit, X-Varnish, X-Debug, X-Request-ID, X-Correlation-ID, X-Runtime, X-Rack-Cache.
  • Security Header Injection: If security headers are absent, CloFix injects them: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload, X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, and a configurable Content Security Policy.
  • URL Rewriting in Response Bodies: Scans HTML (<a href>, <form action>, <img src>), JSON string values, and XML element content for internal domain names and IP addresses. Rewrites them to the public frontend domain. Uses a streaming parser — no full-body buffering.
  • Error Page Sanitization: Intercepts backend 4xx/5xx error responses that contain stack traces, database connection strings, internal hostnames, or file system paths. Replaces them with configurable clean error pages, preventing information disclosure that could assist attackers in targeting your stack.
  • Client IP Preservation: The original client IP is passed to the backend via X-Forwarded-For, X-Real-IP, and CF-Connecting-IP headers so your application can use real IP addresses for logging, analytics, and access control — while the client only ever sees CloFix as the server.
Headers Reference
# Headers stripped from backend responses
strip_headers [
  Server           X-Powered-By
  X-Backend-Server X-Upstream
  Via              X-Real-IP
  X-Forwarded-For  X-Cache
  X-Cache-Hit      X-Varnish
  X-Debug          X-Request-ID
  X-Correlation-ID X-Runtime
  X-Rack-Cache     X-Generator
];

# Headers injected if absent
inject_headers {
  Strict-Transport-Security
    "max-age=31536000; includeSubDomains";
  X-Frame-Options         "DENY";
  X-Content-Type-Options  "nosniff";
  Referrer-Policy
    "strict-origin-when-cross-origin";
}
# URL Rewriting Example
# Backend response contains:
"url": "http://internal-backend.lan/api/v2"

# CloFix rewrites to:
"url": "https://app.clofix.com/api/v2"

# Error page sanitization
error_sanitization {
  enabled      on;
  strip_traces on;
  custom_pages {
    404 "./errors/404.html";
    500 "./errors/500.html";
    503 "./errors/503.html";
  }
}

🚀 Key Security Features

🎯
Multi-Layer Detection
  • Behavioral heuristics (Rate, GeoIP, JA3/JA4)
  • OWASP CRS v4 — 25 rule files, 200+ rules
  • AI/ML: Random Forest, LSTM, Transformer
  • Custom Lua/JS scripting (clofix_main, clofix)
  • Composite weighted risk scoring
🧠
AI-Powered Zero-Day
  • ML classification — 96.2% accuracy
  • Human biometric analysis (mouse/keystroke)
  • Hardware fingerprinting (GPU, CPU, canvas)
  • Automation tool detection (Puppeteer, Selenium)
  • Behavioral baseline — 7-day learning window
Performance-First Design
  • <2ms P99 average latency
  • Coraza + Hyperscan SIMD acceleration
  • HTTP/2 & HTTP/3 (QUIC) support
  • Connection pooling & zero-copy forwarding
  • 120,000+ req/s per node throughput
🔒
Infrastructure Confidentiality
  • 30+ sensitive headers stripped automatically
  • Response body URL rewriting (HTML/JSON/XML)
  • Backend error page sanitization
  • JS Injector — client-side CSRF & anti-tamper
  • Session binding & integrity verification
🏗️
Enterprise Reliability
  • 99.99% availability SLA
  • Active + passive health monitoring
  • Zero-downtime connection draining
  • Slack/Email/Webhook/Telegram alerts
  • 5 load balancing algorithms
🛠️
Developer Friendly
  • Virtual patching — 5-minute CVE response
  • Rule testing sandbox (historical traffic)
  • Multi-language rules (CloFixRule + Lua + JS)
  • Rule metrics & ML optimization suggestions
  • Full REST API for rule management

🔬 Complete Threat Detection Matrix (All 10 Stages)

Comprehensive coverage mapping showing which stages detect each threat category. ✓ Primary detection, △ Partial/Supporting, — Not applicable.

Threat Category01
Behavior
02
CRS
03
JS
04
Lua
05
AI
06
Core
07
Custom
08
Injector
09
LB
10
Backend
SQL Injection
XSS (DOM/Reflected)CSP
DDoS / Rate AbusePrimaryAnomalyConn limit
Bot / AutomationJA3/UAPrimaryBlocklistTelemetry
Command Injection
SSRFURL rewrite
Zero-Day ExploitsVPatchPrimaryVPatchVPatch
Credential StuffingRaterate_limitBehavior
Prototype Pollution
Path Traversal (LFI)Pattern
Magecart SkimmingPatternMutation Observer
API AbuseRate/GeoProtocolAnomalyPath policiesCSRFLB
Information DisclosureBypassHeader StripPrimary
Deploy CloFix WAF in Minutes

Enterprise-grade, 10-stage protection for your applications. Start with a free trial — no credit card required.

🚀 Get Started with CloFix