Skip to content
0587f5a40b7c513a98ec5bcacd3e65e995fa6ce3

0587f5a40b7c513a98ec5bcacd3e65e995fa6ce3

github.com • November 29, 2026

A Flask application behind WSGI middleware, with a separate payload variation and evaluation tool. Phases 1 and 2 demonstrate request capture, configurable regex inspection, a test blocking decision, HTTP 403 responses, and SQLite request/detection logging. Phase 3 generates labeled harmless test inputs, sends them only to the local demo's /echo endpoint, and evaluates results against correlated WAF request and detection records. This is an academic demonstration, not a complete security control.

Requirements and installation

Python 3.10 or newer is recommended. From the project directory, create and activate a virtual environment, then install dependencies:

Dashboard authentication is always enabled. Set a generated session-signing key and create a password hash before starting the app. These PowerShell commands generate values without placing a password or fixed secret in the source:

The password prompt is hidden; keep the printed hash and generated key in your local environment or a deployment secret store. The app fails to start if either setting is missing or invalid. No unauthenticated mode is provided.

Dashboard login throttling defaults to 5 failed attempts per client address in a 300-second window. Further attempts receive HTTP 429 with the same generic sign-in message; password-hash verification is skipped while throttled. The limit counts attempts currently being checked as well, preventing concurrent requests from exceeding the configured hash-work cap. A successful login clears that address's failure state. Configure the policy with WAF_DASHBOARD_LOGIN_MAX_FAILURES (1–100), WAF_DASHBOARD_LOGIN_WINDOW_SECONDS (1–86400), and WAF_DASHBOARD_LOGIN_MAX_CLIENTS (16–65536; default 4096). State is held in a thread-safe, bounded in-memory table and expired entries are removed on later login attempts. When the address table is full, new addresses one bounded overflow bucket rather than evicting active limits. The limiter keys only on the server-observed remote address and ignores X-Forwarded-For and other client-supplied identity headers. This can group users behind NAT or a reverse proxy; configure trusted proxy address handling carefully. The state is local to one application process, so multiple WSGI worker processes do not counts. This is a bounded demonstration safeguard, not production-grade distributed brute-force protection; deployments should also enforce rate limits at a trusted reverse proxy or shared service.

The development server listens on 127.0.0.1:5000 . The SQLite database is created at data/waf.sqlite3 by default. Open and enter the password used to create the configured hash. Set WAF_DATABASE_PATH to change the database location, WAF_LOG_LEVEL to configure logging, or WAF_MAX_BODY_BYTES to change the inspected body size limit (default: 1 MiB). Authentication remains required even when the development server binds to loopback.

Exercise allowed and blocked requests

Blocked test request (the default configured decision):

The blocked request returns HTTP 403. Configure the header name and exact value with WAF_BLOCK_HEADER and WAF_BLOCK_HEADER_VALUE . This deterministic trigger is retained for middleware testing alongside the Phase 2 regex rules.

Configure inspection rules

Default rules are in waf/data/default_rules.json . Each entry defines a unique id , description , category , severity , regex pattern , and inspected components ( path , query , headers , and/or body ). Set WAF_RULES_PATH to use another JSON rule list. A matching rule blocks the request and writes its ID, category, severity, inspected component, and reason to detection_events . Rules may provide one pattern or a bounded patterns list. SQLI-001 uses separately compiled indicator patterns so a no-match does not repeatedly evaluate one large alternative expression; each regex still has the existing 10 ms timeout, and all searches the existing request-wide budget. Percent decoding is bounded to three total passes for query names and values: parse_qs decodes once, and the WAF normalization engine uses at most the remaining two passes. Both decoded query parameter names and values are inspected. PATH_INFO is provided by the WSGI server and may already reflect server-side URL decoding; the WAF applies up to three further passes to that value. Header values and UTF-8-decoded request bodies receive up to three WAF normalization passes. Malformed percent escapes remain literal, and invalid query UTF-8 is replaced safely during parsing.

The engine inspects each complete component value, up to the configured WAF_MAX_INSPECTED_VALUE_CHARS limit (default: 1 MiB). Values exceeding that limit are rejected with HTTP 413 before regex matching; they are never silently truncated and allowed. This cap is bounded at 1 MiB. The body byte limit and the per-value character limit both apply; valid request values within those limits are inspected completely. Regex timeouts and the 250 ms request-wide budget remain fail-closed, so a value can still be rejected when matching cannot finish within those budgets.

The SQLI-001 block- indicator supports /* ... */ with up to 256 content characters (260 characters including the delimiters). Internal asterisks are allowed unless they begin the closing */ . Longer or unterminated do not match this indicator; the normal regex timeout and per-request matching budget remain in force.

The initial SQL injection and XSS patterns are demonstration rules. SQL line require statement context such as SELECT ... FROM ... -- ; block require SQL syntax on both sides, such as UNION/*...*/SELECT . A standalone or partial prose like SELECT a plan -- sale is not sufficient. Scriptable URI detection requires a javascript: scheme in an href , src , action , or formaction attribute; a plain documentation mention, including a javascript:alert(1) example, is not sufficient. Script elements and executable event-handler indicators remain separate XSS signals. The rules can still miss attacks and can also match benign input. They do not establish security effectiveness or replace application-level validation and output encoding.

Custom patterns use the timeout-capable regex package. The engine caps the configuration at 100 rules, 512 characters per pattern, and 16,384 total pattern characters; each match has a 10 ms timeout and each request has a 250 ms regex budget. A timeout fails closed with HTTP 403 and a rule_evaluation_timeout decision. These limits reduce, but cannot eliminate, resource risks from custom rules and unusually high request volume.

Request inspection defaults to an 8 KiB query string, 128 query fields, 100 headers, an 8 KiB individual header field line, 32 KiB aggregate header field lines, an 8 KiB request path, the configured body cap, and a 1 MiB maximum inspected component value. Override these with WAF_MAX_QUERY_BYTES , WAF_MAX_QUERY_FIELDS , WAF_MAX_HEADERS , WAF_MAX_HEADER_BYTES , WAF_MAX_TOTAL_HEADER_BYTES , and WAF_MAX_PATH_BYTES . Set WAF_MAX_INSPECTED_VALUE_CHARS to lower the per-value character cap; it cannot exceed 1 MiB. A body whose decoded text exceeds this cap receives HTTP 413 even if WAF_MAX_BODY_BYTES is configured higher. Header sizes count UTF-8 bytes in Name: Value ; aggregate size is the sum of those field lines. The WSGI middleware rejects oversized paths, headers, query strings, and bodies with HTTP 413 before rule inspection. A WSGI server or reverse proxy may impose its own request-line or header limits before the request reaches this middleware; these application checks cannot recover resources already consumed upstream.

Extended rules and decoded views

The default rule set has nine rules (52 patterns): SQLI-001 , SQLI-002 (stacked queries, SLEEP / WAITFOR , information_schema , LOAD_FILE , xp_cmdshell , unbalanced-quote boolean strings), XSS-001 , XSS-002 (any HTML event-handler attribute, iframe / object / embed , data:text/html , document.cookie ), PATH-001 ( ../ traversal, sensitive files, php:// style wrappers) and CMDI-001 ( ; cmd , | cmd , && cmd , $(...) , backticks, ${jndi: ), plus XXE-001 (DOCTYPE/ENTITY declarations, XInclude), SSRF-001 (loopback, private-range and cloud-metadata URLs) and NOSQL-001 (MongoDB-style $ne / $where operators). Rules run in file order and the first match wins, so keep the original rules first. PATH-001 and CMDI-001 skip headers to avoid noisy matches on Referer / User-Agent . A context-free javascript:alert(1) in prose is intentionally allowed.

Each value is matched in up to three forms: original, percent-normalized, and "decoded" views built by waf.normalization.decoded_views :

Base64 and URL-safe Base64 tokens of at least 12 characters, and hex tokens (optionally 0x -prefixed) of at least 12 hex characters;

HTML entities ( input . Each pattern of a rule should start with a literal character or word: patterns that begin with a multi-word alternation are noticeably slower on very large values and can hit the 10 ms per-regex timeout, which fails closed with HTTP 403.

Evasion test catalog and results

The tester catalog holds 26 cases (SQL injection, XSS, path traversal, command injection, XXE, SSRF, NoSQL injection and benign prose) mutated by 14 transformations: original , url , double_url , triple_url , quad_url , base64 , double_base64 , hex , html_entity , unicode_escape , sql_comment_space , uppercase , lowercase and alternating_case (364 requests per run; hard caps are 400 tests and 450 requests). Note that the HTTP client adds one more percent-encoding layer when it sends a value, so triple_url reaches the WAF with four layers.

Measured on the local demo before and after the Phase 4 hardening (see docs/REPORT.md for details and screenshots):

The three rows above were measured on the original 20-case catalog with deep decode off or on. The extended 26-case catalog (364 requests) gives 86.5% (230/266) with deep decode off and 100% (266/266) with it on, 0 / 98 false positives in both cases.

WAF_DEEP_PERCENT_DECODE is on by default in the application: besides the three normal percent-decoding passes, rules also run on a view decoded up to six more times, so triple/quad URL encoding is detected in its real category and benign over-encoded text is not flagged. Set WAF_DEEP_PERCENT_DECODE=false to restore the strict three-pass behavior. Values encoded more than nine times in total still pass; the cap keeps the work per request bounded.

Modes, anomaly scoring and the benchmark

WAF_MODE=block (default) rejects matching requests with 403. WAF_MODE=detect only records the detection ( detected_only: in the request log) and lets the request through, which is useful for tuning rules on real traffic before blocking.

WAF_ANOMALY_THRESHOLD=0 (default) blocks on the first matching rule. A positive value evaluates every rule, adds a score per match (low 2, medium 3, high 4, critical 5) and blocks only when the total reaches the threshold, e.g. 5 lets a single high-severity match through but blocks two matches.

The live suite expects blocking behavior, so run it with WAF_MODE=block .

The in-process benchmark needs no server and runs in a couple of seconds:

It sends 101 attack strings in 7 families (SQL injection, XSS, path traversal, command injection, XXE, SSRF, NoSQL injection) and 72 benign strings through 21 techniques (the 14 single transformations plus 7 chained ones such as base64+url ), prints detection by category and by technique, lists false positives and the strings that slipped through, and can fail a CI job with --min-detection and --max-false-positives . Current result with default settings: 99.8% detection (2117/2121), 0 false positives (0 / 1368); the only misses are Base64 of a 4-character payload, which is shorter than the 8-character minimum token. With --no-deep detection is 90.3%. See docs/BENCHMARK.md . .github/workflows/ci.yml runs the tests and this quality gate on every push.

Comparing against another WAF (for example OWASP CRS)

tester.compare scores any WAF that is reachable on loopback with the same corpus and prints a side-by-side table:

Each variant is sent as GET ?q= and a 403 (change it with --block-status ) counts as blocked. Only loopback HTTP targets are accepted, and proxy variables, redirects and credentials are ignored. Pointing it at this project's own app ( --target ) gives the same numbers as the in-process benchmark, which confirms the middleware sees the requests exactly as the benchmark models them. deploy/crs/docker-compose.yml starts ModSecurity with the OWASP Core Rule Set on 127.0.0.1:8080 ; it needs Docker and was not run in the development environment, so check the image names and variables against the current OWASP documentation. No CRS numbers are quoted in this repository because they have not been measured.

Packaging and reverse-proxy mode

The WAF can run as a standalone reverse proxy in front of any HTTP backend, in any language:

Every request is inspected first; blocked requests never reach the backend, and the backend address comes only from configuration. Redirects are passed through, the X-Forwarded-* headers are set by the proxy (client values are replaced), and backend failures return 502/504. Logs go to the same SQLite schema, so the dashboard can read them by pointing WAF_DATABASE_PATH at the proxy's database. Limits: no WebSocket upgrades; paths are decoded and re-encoded before being forwarded.

PyPI: pyproject.toml builds the distribution hisn-waf ( python -m build , then twine check dist/* ). It ships the waf package and the waf-proxy command: pip install "hisn-waf[proxy]" . The built wheel was installed in a clean virtual environment and run against a local backend. PACKAGE_README.md is the page shown on PyPI.

Docker: Dockerfile and deploy/docker-compose.proxy.yml run the proxy as a non-root user. They were not built in the development environment (no Docker daemon), so run docker build -t waf-proxy . once to confirm.

Releases: .github/workflows/publish.yml publishes to PyPI (trusted publishing) and to GitHub Container Registry when a GitHub release is published. It has not been run; see its header for the one-time setup.

The tests use Flask's in-process test client, local loopback servers, and temporary SQLite files. The runner rejects non-loopback destinations, pins connections to validated loopback addresses, ignores proxy environment variables, disables automatic redirects, and revalidates each redirect before connecting. HTTPS is intentionally unsupported by this local HTTP demo.

Run the Phase 3 local test suite

Start the application in one terminal:

In another terminal, run the pre-defined local cases and transformations:

The suite sends GET requests only to the demo's /echo route. It includes benign examples and clearly labeled SQL injection/XSS test patterns. Variants include the original, URL and double URL encoding, Base64, hexadecimal, and case changes. The request count, total duration, network timeouts, response size, and redirect count have hard caps; these may be lowered through run_suite arguments. There are no third-party targets or exploit actions.

Results are stored separately from ordinary request logs in test_runs and test_results in the selected SQLite database. Each request has a X-WAF-Request-ID ; the runner checks that ID against the persisted request and detection event. A bare HTTP 403 is not treated as a true positive. Ambiguous, missing, timed out, network-error, oversized, redirected-out, and skipped cases are excluded from the effectiveness denominators.

Metrics use only verified eligible outcomes: detection rate is TP / (TP + FN) and false-positive rate is FP / (FP + TN) . Rates with a zero denominator are stored as null (Python None ). These measurements describe only this small payload catalog and current rule configuration; they do not establish general SQL injection or XSS protection.

With the app running and authentication configured, open and sign in. The dashboard provides an overview of request and detection counts, daily request activity, and categories present in actual detection records. The Request Logs page supports pagination, text , decision/method filters, and metadata-only request details. Detection Events supports category, severity, and date filters. Test Suite lists persisted Phase 3 runs and individual outcomes, while Metrics recomputes the latest run's confusion matrix using waf/metrics.py and adds the bypass rate (FN / (TP + FN)), filter efficiency ((TP + TN) / all) and bypass breakdowns per transformation technique and per attack category. The Overview shows the latest run's bypass rate and filter efficiency to the blocked and allowed counters.

Dashboard reads use parameterized SQLite statements, bounded pagination and filters, and Jinja's automatic HTML escaping. Every dashboard page, detail route, and static asset requires a signed authenticated session. Sessions use HttpOnly, SameSite=Lax cookies, CSRF tokens on login and logout, and a 30-minute sliding expiration by default ( WAF_DASHBOARD_SESSION_LIFETIME_SECONDS , allowed range 60–86400). Cookies are Secure for HTTPS requests; set WAF_DASHBOARD_COOKIE_SECURE=true when TLS terminates at a proxy and Flask sees plain HTTP. Configure trusted proxy scheme handling carefully. Request bodies and headers are not rendered. Detection categories and severity filter choices come from stored events. Dashboard charts use local JavaScript and canvas; no external fonts, chart libraries, URLs, or remote data sources are loaded. The dashboard uses the existing SQLite database and does not add or migrate tables.

Current scope and limitations

The middleware records method, path, query parameters, headers, request body, allow/block decision, reason, and response status.

Request bodies above the configured inspection limit receive HTTP 413.

Bodies with a valid Content-Length are read into a bounded snapshot and restored for Flask. Invalid framing returns HTTP 400; oversized bodies return 413. A seekable WSGI input stream is probed by at most one byte and restored when neither a length nor a server-terminated marker is present; detected unframed body bytes are rejected (HTTP 400 for uncommon methods, HTTP 411 for POST/PUT/PATCH/DELETE). If the stream cannot be safely probed, body-capable methods without framing receive HTTP 411. A verified empty stream is accepted, and explicit Content-Length: 0 is the portable way to express an empty body on methods that may carry one. GET and HEAD with a non-seekable stream and no length are treated as bodyless. HTTP/1.1 framing defines the request body length as zero when neither Content-Length nor Transfer-Encoding is present (RFC 9112, Section 6.3). Core WSGI allows CONTENT_LENGTH to be absent and does not provide a portable non-blocking way for middleware to test a non-seekable input stream for EOF. The middleware therefore does not probe or consume these streams; the HTTP server or gateway must enforce message boundaries and must not expose unframed bytes as the body. Gateways translating protocols with different body framing must set a valid CONTENT_LENGTH or the server-specific wsgi.input_terminated extension for safely readable bodies. If a gateway violates this contract, middleware cannot distinguish hidden body bytes from a valid empty stream without risking a blocking read or consuming data.

Chunked bodies are inspected only when the WSGI server marks the decoded input with wsgi.input_terminated ; the middleware reads at most the body limit plus one byte. Werkzeug's development server provides this marker for chunked requests. Other servers must provide the same WSGI extension or the request is rejected for body-capable methods. The test suite exercises both the marker-based middleware path and an end-to-end chunked request to the local Werkzeug server.

Request logs redact supported sensitive header and field values. Unsupported body formats are omitted; still avoid using real credentials or sensitive data with the demo.

The test blocking header remains available for deterministic middleware testing. Rule matches are also blocked and logged with their rule details.

Detection uses the submitted values before persistence redaction. Authorization, cookie, password, token, API-key, session, and credential-like names are normalized and redacted in headers, query fields, JSON bodies, and URL-encoded form bodies. Other non-empty body content types are omitted from stored logs because their secrets cannot be safely identified generically.

SQLite :memory: paths are rejected because this app uses short-lived connections; use a file database, including a temporary file for tests.

The runner allows only plain HTTP to numeric loopback or hostnames whose complete DNS answer set is loopback. It uses the validated numeric address for the socket connection to prevent a second DNS lookup from redirecting traffic. Redirects must remain on the same validated origin and approved demo routes. DNS resolution itself is bounded, but Python cannot forcibly stop a resolver thread that is stuck inside the operating system resolver; timed-out resolver workers are abandoned and limited by a semaphore.

The test catalog and rule set are intentionally small. Nested or chained encodings, tokens below the minimum length, and obfuscation outside the supported views can still evade the demonstration rules, and harmless-looking content can trigger false positives. The reported metrics are not a security certification.

Dashboard data is read from the current SQLite database. A single configured password protects all dashboard routes; role-based access control is not included. Failed-login throttling uses bounded, process-local counters keyed by the server-observed client IP. Users sharing an IP also its limit, and counters are not distributed across multiple workers. Use HTTPS, a strong generated session key, and a deployment secret store when exposing the app beyond local development; deployments needing coordinated throttling should enforce it at a trusted proxy or shared service.