Recursive parameter decoding, abstract syntax tree analysis, engine toggles, and analysis budget control.
This is the multi-page printable view of this section. .
Security Protection Policies
- 1: AST Semantic Analysis Engine
- 2: Custom Regex Rules
- 3: IP, GeoIP & Client Fingerprinting
- 4: Bot Challenges & CAPTCHA Mitigation
- 5: Rate Limiting & Traffic Shaping
- 6: Access Control Lists (ACL)
- 7: Block Pages & HTML Sanitization
CheeseWAF provides a defense-in-depth architecture spanning from network-level controls to application semantic analysis. Baseline protection policies are defined globally in protection and protection.policy, with support for granular per-site overrides via sites[].waf.protection_policy.
1 - AST Semantic Analysis Engine
CheeseWAF’s primary detection capability is powered by an Abstract Syntax Tree (AST) grammar analysis architecture rather than traditional brittle regular expressions. Inbound payloads undergo multi-layer recursive decoding (URL encoding, Unicode normalization, hex, and nested Base64) before being parsed into domain-specific syntax trees to evaluate true payload semantics.
Through systematic evaluation and remediation against 7 external real-world corpora using an independent Corpus Fidelity Classifier, the semantic engine achieves an independently verified 97.08% True Positive Rate (TPR).
Engine Configuration Matrix
Individual specialized semantic engines can be toggled per site via sites[].waf.semantic_engines:
| Engine Key | Attack Scope & Deep Detection Capabilities |
|---|---|
sql | SQL Injection: Major SQL dialect grammar parsing; integrated XPath injection parser; heavy time-blind injection detection (Cartesian product / generate_series); whitespace comment truncation resilience |
xss | Cross-Site Scripting: HTML/SVG tag balance analysis; fully split protocol scheme detection (detects scattered tokens like j a v a s c r i p t: and CDATA/HTML comment interspersal); obfuscated javascript: URI concatenation regex; dynsrc/lowsrc attribute probes; JavaScript string escaping; malformed event handler inspection |
rce | Command & Code Injection: Comprehensive command table alignment (including id, ls, echo, netstat, lsof); newline command chains; automatic basename extraction for absolute executable paths; ; + system function calls |
lfi | File Inclusion & Path Traversal: POSIX and Windows absolute path traversal (smart Program Files exclusion to eliminate false positives); deep UTF-8 folding; SSI server-side includes (<!--#exec) |
nosql | NoSQL Injection: Deep HTTP request header analysis (e.g., X-User-Filter); MongoDB shell escaping; isolation of malicious operators from legitimate query filter operators |
ssti | Template Injection: Jinja2, Twig, and common template grammar trees; quoted operand probes; direct expression detection when entire value is a template expression |
ssrf | Server-Side Request Forgery: URI parameter schema inspection; full request body URL detection treating the whole body as a potential fetch sink |
xxe | XML External Entity: DOCTYPE entity declarations, SYSTEM/PUBLIC external resource references, and parameter entity attacks |
webshell | Webshell & Malicious Scripts: Combines PHP execution primitive analysis with Shannon entropy measurement ($\ge$ 5.2) to accurately flag high-entropy Base64 one-liners and obfuscated droppers while eliminating false positives on repeated strings, JWT tokens, and minified code |
In production, keeping core engines enabled is recommended. If a service clearly lacks a specific stack (such as a static site without SQL backends), disabling that engine saves CPU cycles.
Latency Engineering & Pre-Filter Gating
To deliver deep syntax parsing without sacrificing microsecond-level latency, CheeseWAF employs several algorithmic safeguards:
- Cheap Substring Gating: Prior to expensive AST generation or complex regular expressions, constant-time substring pre-filters discard benign traffic in microseconds.
- Worker Pool & Request Context Forking: In Phase 2, semantic analyzers run concurrently over bounded worker goroutines with isolated context copies, merging results deterministically by priority.
- 100ms Hard Budget Deadline: If oversized adversarial inputs consume parsing time, the global deadline prevents request processing hangs and triggers the configured fallback policy.
Analysis Budget & Allowlists
Fine-grained controls in sites[].waf.semantic_policy allow tuning parsing behavior:
budget_exhausted_policy: Fallback action when syntax analysis exhausts its budget:auto(derives from web_attack level),open(availability-first pass),observe(log only), orclosed(challenge/strict block).path_allowlist: URI path prefixes that bypass semantic analysis entirely.param_allowlist: Parameter keys excluded from deep AST inspection.
Migration note: The canonical location is sites[].waf.semantic_policy.budget_exhausted_policy. Values left in older, non-canonical configuration locations are not read; move them manually under each site’s waf.semantic_policy block. When migrating legacy values, map pass to open, and map block or challenge to closed (the current closed mode prefers a challenge when analysis cannot finish). Leave the field empty or set it to auto to derive the effective action from the site’s web_attack level.
Global limits can be configured in sites[].waf.performance, including max_body_bytes (default 8MB), max_header_bytes, and proxy_timeout.
Outbound Response Inspection (Data Leak Prevention)
sites[].waf.response inspects upstream HTTP response bodies to prevent sensitive credential exposure:
- Detection Scope: Discovers AWS Access Keys, generic leaked credential patterns, and any additional patterns configured for the site. The built-in default set includes password/secret-key patterns; PEM private-key detection is available when explicitly included in
sensitive_patterns(the shipped site template does not enable it by default). - Pattern Precedence: When
sites[].waf.response.sensitive_patternsis non-empty, it replaces the built-in defaults rather than extending them; include every pattern you need in the site-level list. - Tuning Advice: For large file downloads or streaming media, restrict response inspection to JSON/HTML content types via path patterns.
For classification semantics regarding isolated attacks vs embedded long-text inputs, see Isolated vs. Embedded Payloads.
2 - Custom Regex Rules
The Custom Rule Engine operates as a Phase 1 Pre-Filter in the request pipeline (engine priority 250). It executes prior to the AST Semantic Analysis Engine (priority 290+). Custom rules are designed to intercept high-frequency reconnaissance, scanner headers, and custom application path blocks. When a rule triggers with a block action, execution short-circuits immediately, eliminating unnecessary AST parsing overhead.
You can manage custom rules visually in the Rules section of the Web Console (sites[].waf.custom_rules), via the cheesewaf rules CLI utility, or using REST APIs.
Configuration Example
Field Reference & Valid Enumerations
| Field | Type | Description & Validation Constraints |
|---|---|---|
id | String | Globally unique rule ID within the site. If omitted during import, the engine generates one automatically |
name | String | Human-readable rule title for logging and UI display |
pattern | String | Regular expression pattern (Go RE2 syntax; max 16KB per pattern, max 4096 compiled instructions) |
location | String | Target inspection location. Strictly limited to: uri, query, header, body, cookie (default uri) |
action | String | Action on match. Strictly limited to: block, log, challenge (default block) |
severity | String | Threat level: low, medium, high, critical (default medium) |
priority | Integer | Rule execution priority (-1,000,000 to 1,000,000). Lower numbers execute first |
enabled | Boolean | Rule enable flag (default true) |
Deterministic Enforcement & Policy Bypass
Custom rules represent explicit administrative intent rather than probabilistic detector signals. Within the data plane pipeline:
- Direct Execution: When a request matches a custom rule, the engine unconditionally and immediately executes the designated action (
block,challenge, orlog). - Exempt from Policy Thresholds: Unlike semantic detections, custom rule actions bypass
protection_policy.web_attackgates (such as minimum severity thresholds, model confidence filters, or aggregate risk score ceilings), guaranteeing deterministic enforcement as configured.
Security Constraints & Quota Limits
To prevent malformed or unbounded rules from causing performance degradation, the configuration validator enforces strict boundaries:
- Resource Limits: A single site supports up to 256 custom rules (
maxCustomRulesCount = 256). Import document size must not exceed 1MB, and total pattern length across all rules cannot exceed 256KB. The imported document must explicitly define thecustom_rulesroot key. - ReDoS Immunity: Backed by Go’s
regexp(RE2 guarantees linear-time execution, eliminating catastrophic backtracking ReDoS). Expressions exceeding 4096 compiled program instructions are rejected. - Deduplication Check: Rule IDs must be unique within each site. Duplicate
location + patterncombinations are strictly rejected. - Content-Disposition Sanitization: When exporting rule archives (
GET /api/rules/export), output filenames are strictly sanitized against an[A-Za-z0-9._-]whitelist, preventing HTTP response header injection and directory traversal attacks.
Batch Import, Export & Template Generation
CheeseWAF provides seamless CLI and Web UI workflows for importing and exporting rules in YAML and JSON:
1. CLI Management
2. Web Management Console
In the Rules page of the Web Console, click the Import / Export button in the header:
- Drag and drop or upload local
.yamlor.jsonrule definition files. - Inspect syntax validation and preview differences prior to committing.
- Download a full JSON or YAML rule backup with a single click.
Operational Best Practices
- Focus on Definitive Signatures: Use custom rules for known static probes (admin interfaces, sensitive files, scanner fingerprints). Defer complex application injection patterns (SQL injection, XSS) to the AST semantic engine.
- Leverage Short-Circuiting: Order high-confidence malicious signatures with lower
prioritynumbers to drop bad traffic early, minimizing server CPU load.
3 - IP, GeoIP & Client Fingerprinting
CheeseWAF enforces network-layer access controls at the outermost boundary of the request pipeline. Manage these controls visually under IP in the Web console, or define them in the configuration file under protection.ip.
Static Access Lists & Base Configuration
- IP Whitelist (
whitelist): Matching client IPs bypass subsequent IP restrictions, GeoIP rules, threat intel, bot challenges, and rate limiting (the semantic engine pipeline continues to inspect payloads for application security). - IP Blacklist (
blacklist): Matching client IPs are blocked at the network entry point, returning a block page without consuming semantic engine resources.
GeoIP Country Restrictions
Block traffic from specific countries using offline MaxMind MMDB databases:
- Set
geoip.enabledtotrue. - Point
geoip.databaseto a valid Country MMDB file path (e.g.,./data/GeoLite2-Country.mmdb). - Specify ISO 3166-1 alpha-2 two-letter country codes in
blocked_countries(e.g.,["US", "RU"]).
Threat Intelligence Integration
Import third-party threat intelligence IP feeds directly into CheeseWAF. The Web console supports automated scheduled synchronization, manual updates, and connectivity tests. Query intelligence status for specific IPs via the REST endpoint POST /api/ip/threat-intel/lookup.
Client Soft-Fingerprinting & Trusted Proxies
- Client Soft-Fingerprints: The Data Plane computes lightweight fingerprints based on client User-Agent and Accept-Language headers (sha256 8-byte prefix). ALAP review can persist malicious fingerprints as defense rules to serve as corroborating evidence.
- Trusted Upstream Proxies: When CheeseWAF is deployed behind a CDN, cloud load balancer, or reverse proxy, configure
sites[].waf.access_control.trusted_cidrsortrusted_proxy_providersto correctly extract client IP addresses fromX-Forwarded-Forheaders.
4 - Bot Challenges & CAPTCHA Mitigation
Modern web applications constantly face malicious automated traffic, including AI web scrapers, credential stuffing attacks, and automated vulnerability scanners. CheeseWAF provides multi-layered bot mitigation and challenge capabilities. Configure policies in the Web console under Bot Challenge and CAPTCHA Lab, or declare them in protection.bot and console.login.captcha.
Traffic Challenge Configuration
| Configuration Parameter | Description |
|---|---|
js_challenge | Issues silent JavaScript challenge and sets clearance cookie upon validation |
captcha | Overlays interactive CAPTCHA validation on top of JS challenge |
captcha_type | Challenge mechanism: pow (Proof of Work), slider (sliding puzzle), or image (character glyphs) |
cookie_name | Name of the authorization clearance cookie; defaults to cheesewaf_js_clearance |
path_prefixes | List of URI path prefixes where challenges are strictly enforced |
exempt_path_prefixes | Whitelist of URI prefixes exempt from challenges (e.g., /health) |
suspicious_user_agents | User-Agent substring matches that immediately escalate to full human verification |
Do not check challenge signing secret values into version control. When the value is empty or a known placeholder, setup/startup generates a strong runtime secret and persists it in the protected runtime configuration or runtime secret file according to the selected deployment; it is not an in-memory-only guarantee. Keep the runtime path and permissions private.
Challenge Types & Interaction Mechanisms
- Proof of Work (PoW / Altcha): Clients compute a cryptographic hash challenge in the browser background and submit the nonce via the
X-CheeseWAF-Altcharequest header. This is fully frictionless for real users while making automated concurrent scraping computationally prohibitive. - Sliding Puzzle (Slider): Analyzes mouse drag trajectories and validates minimum drag timing thresholds (configured via
slider_captcha_*). - Character Image (Image): Supports configurable string lengths, image dimensions, and audio assistance limits.
- Experimental Behavioral Tests: Includes gesture curves, scratch-off, and icon point-and-click puzzles. Verify user experience in the console CAPTCHA Lab before rolling out to production traffic.
Custom background images and iconography can be uploaded via /api/captcha/assets.
Management Console Login Defense
console.login.captcha protects the Web Management Console login endpoint (completely isolated from business data plane traffic), supporting slider puzzles with optional PoW verification.
The source template enables the management-login slider CAPTCHA by default (console.login.captcha.enabled: true). After initialization, the first browser login therefore requires completing the human-verification challenge in addition to the username and password. For local test fixtures only, set console.login.captcha.enabled: false in a runtime configuration copy and restart; do not disable this control in production merely to bypass acceptance checks.
Additionally, enable console.login.security_entry to obscure the management portal behind an obfuscated path and pre-shared authorization cookie.
Waiting Room Queue Scheduling
Enable waiting_room: true and specify waiting_room_max_active to gracefully hold excess concurrent clients in an organized queue during flash sales or traffic surges, preventing origin resource exhaustion. The waiting room is effective only when the global protection.policy.bot_cc policy is not off and its action is challenge; enabling the site waiting-room flag alone is not sufficient. See Rate Limiting.
5 - Rate Limiting & Traffic Shaping
CheeseWAF integrates a high-performance sharded sliding-window counter rate limiting algorithm on the Data Plane to smooth out traffic spikes and mitigate HTTP flood / CC attacks. Configuration is located under protection.ratelimit, and can be updated dynamically via PUT /api/protection/ratelimit.
Base Configuration Example
| Parameter | Type | Description |
|---|---|---|
enabled | Boolean | Master switch for Data Plane rate limiting |
requests | Integer | Baseline request quota permitted within the rolling window |
window | Duration | Calculation time window (e.g., 60s, 1m) |
burst | Integer | Extra burst capacity accommodating temporary traffic surges |
This module enforces global/client-level traffic shaping on the Data Plane. For fine-grained rate limits targeting specific API endpoints (HTTP method + path), see API Security Rate Limits.
Limit Exceeded Actions
When a client’s request rate exceeds the sharded sliding-window counter capacity, the system executes one of the following actions:
- HTTP 429 Block Page: Responds immediately with HTTP 429 Too Many Requests and a customized error page.
- Waiting Room Scheduling: If Waiting Room Mechanism is active and the global
protection.policy.bot_ccpolicy is enabled with actionchallenge, excess requests are smoothly queued rather than dropped.
During initial rollout, use generous limits and observe 1–2 weeks of production traffic before tightening requests and burst thresholds.
6 - Access Control Lists (ACL)
Access Control Lists (ACL) execute at the front of the traffic processing pipeline, offering ultra-low overhead filtering to immediately reject known diagnostic endpoints, probe paths, or enforce mandatory request headers. Configure ACLs under protection.acl, or update them dynamically via PUT /api/protection/acl.
Configuration Example
Schema Attributes
| Field | Description |
|---|---|
method | Target HTTP method (e.g., GET, POST); leave empty to match any method |
path_prefix | Matching URI path prefix (e.g., /debug, /actuator) |
header | HTTP header key to evaluate; leave empty if unconstrained |
header_value | Expected or rejected value for the specified header |
action | Action on match: block, log, or challenge |
severity | Threat severity recorded in security logs and audit events |
ACL evaluates enabled rules in declaration order, using case-normalized method checks, literal URI-prefix comparisons, and exact case-insensitive header-value comparisons. For complex regex-based pattern matching, use Custom Regex Rules.
7 - Block Pages & HTML Sanitization
When an inbound request is blocked by IP reputation, ACLs, Bot defense, or the AST semantic engine, CheeseWAF renders a structured block page response. Managed under block_page, templates can be visually previewed, edited, and deployed within the Block Pages view in the Web Console.
Basic Configuration
Template Lifecycle & Sandboxed Previews
- Built-In Modern Designs: Enumerate built-in response templates via
GET /api/block-pages/templates. - Sandboxed Rendering: Preview custom templates safely in an isolated iframe (
POST /api/block-pages/preview) prior to publishing globally. - Custom HTML Uploads: Call
POST /api/block-pages/uploadto upload custom branding, or revert to defaults viaDELETE /api/block-pages/custom.
HTML Sanitization Standards (SanitizeBlockPageHTML)
To prevent custom block pages from introducing Stored XSS or phishing vectors, CheeseWAF enforces strict sanitization on all custom HTML inputs before persistence:
1. Tag Whitelist
Only safe layout and typographic tags are permitted:
- Structure:
html,head,body,title,main,section,header,footer,div,span - Typography:
h1–h6,p,strong,em,b,i,small,pre,code,br,hr - Lists & Tables:
ul,ol,li,table,thead,tbody,tfoot,tr,th,td - Assets & Style:
a,img,style,meta
2. Active Script & Event Stripping
- Zero Scripts: All
<script>elements and HTML comments are completely removed. - Event Handler Neutralization: Attributes prefixed with
on(e.g.,onclick,onload,onerror) are excised. - Form Action Protection:
formaction,action, andmethodattributes are stripped to prevent credential-harvesting forms. - Redirect Prevention:
<meta>elements only permit thecharsetattribute;http-equiv="refresh"and arbitrary header injections are rejected.
3. CSS Style Sanitization
@importrules inside<style>tags or inlinestyleattributes are stripped.- Risky CSS primitives such as
javascript:,vbscript:,expression(,behavior:, and-moz-bindingare removed.
4. URL Scheme Controls
- The
hrefandsrcattributes are strictly restricted tohttp,https,mailto, andtel. <img>elements additionally support embedded Base64 image payloads (data:image/*;base64,...); arbitrary data URIs are discarded.
Traceability & Operational Guidelines
- Global Trace ID Correlation: Block pages dynamically display a unique request
traceId. When users report false positives, operators can correlate the exact rule evaluation chain under Monitoring & Logs. - Information Leakage Prevention: Custom block templates should avoid revealing backend hostnames, private IPs, or internal technology stacks to external clients.