hisn-waf 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hisn_waf-1.0.0/LICENSE +21 -0
- hisn_waf-1.0.0/PACKAGE_README.md +58 -0
- hisn_waf-1.0.0/PKG-INFO +84 -0
- hisn_waf-1.0.0/README.md +445 -0
- hisn_waf-1.0.0/hisn_waf.egg-info/PKG-INFO +84 -0
- hisn_waf-1.0.0/hisn_waf.egg-info/SOURCES.txt +22 -0
- hisn_waf-1.0.0/hisn_waf.egg-info/dependency_links.txt +1 -0
- hisn_waf-1.0.0/hisn_waf.egg-info/entry_points.txt +2 -0
- hisn_waf-1.0.0/hisn_waf.egg-info/requires.txt +4 -0
- hisn_waf-1.0.0/hisn_waf.egg-info/top_level.txt +1 -0
- hisn_waf-1.0.0/pyproject.toml +42 -0
- hisn_waf-1.0.0/setup.cfg +4 -0
- hisn_waf-1.0.0/waf/__init__.py +1 -0
- hisn_waf-1.0.0/waf/data/default_rules.json +175 -0
- hisn_waf-1.0.0/waf/database.py +91 -0
- hisn_waf-1.0.0/waf/engine.py +237 -0
- hisn_waf-1.0.0/waf/errors.py +13 -0
- hisn_waf-1.0.0/waf/inspection.py +233 -0
- hisn_waf-1.0.0/waf/metrics.py +100 -0
- hisn_waf-1.0.0/waf/middleware.py +276 -0
- hisn_waf-1.0.0/waf/models.py +225 -0
- hisn_waf-1.0.0/waf/normalization.py +182 -0
- hisn_waf-1.0.0/waf/proxy.py +209 -0
- hisn_waf-1.0.0/waf/repository.py +81 -0
hisn_waf-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ahmed Abuelmagd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# hisn-waf (حصن)
|
|
2
|
+
|
|
3
|
+
A lightweight web application firewall for Python. It runs either as **WSGI
|
|
4
|
+
middleware** inside any WSGI app (Flask, Django, ...) or as a **standalone
|
|
5
|
+
reverse proxy** in front of an HTTP backend written in any language.
|
|
6
|
+
|
|
7
|
+
* 9 rules / 55 regex patterns for SQL injection, XSS, path traversal, command
|
|
8
|
+
injection, XXE, SSRF and NoSQL injection, in an editable JSON file.
|
|
9
|
+
* Decodes evasions before matching: repeated URL encoding, Base64, hex, HTML
|
|
10
|
+
entities, `\uXXXX`, SQL comments.
|
|
11
|
+
* Fail-closed limits and per-pattern regex timeouts against oversized or
|
|
12
|
+
pathological input.
|
|
13
|
+
* `block` or `detect` (log only) mode, optional anomaly scoring.
|
|
14
|
+
* Every request and detection is logged to SQLite with a correlation ID
|
|
15
|
+
(`X-WAF-Request-ID`).
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install hisn-waf # middleware only
|
|
21
|
+
pip install "hisn-waf[proxy]" # adds the reverse proxy server
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The import name is `waf`.
|
|
25
|
+
|
|
26
|
+
## Reverse proxy
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
waf-proxy --backend http://127.0.0.1:3000 --listen 0.0.0.0:8080 --mode detect
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Run in `detect` mode first to see what would be blocked, then switch to
|
|
33
|
+
`--mode block`. Settings can also come from environment variables
|
|
34
|
+
(`WAF_PROXY_BACKEND`, `WAF_PROXY_LISTEN`, `WAF_MODE`, `WAF_RULES_PATH`, ...).
|
|
35
|
+
Redirects from the backend are passed through, not followed, and the backend
|
|
36
|
+
address cannot be influenced by a request.
|
|
37
|
+
|
|
38
|
+
## WSGI middleware
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from waf.database import initialize_database
|
|
42
|
+
from waf.middleware import WAFMiddleware
|
|
43
|
+
|
|
44
|
+
initialize_database("waf.sqlite3")
|
|
45
|
+
app.wsgi_app = WAFMiddleware(app.wsgi_app, "waf.sqlite3", "X-WAF-Test-Block", "1", 1_048_576,
|
|
46
|
+
deep_percent_decode=True)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Honest limits
|
|
50
|
+
|
|
51
|
+
This is a signature (regex) WAF. It reduces risk but is not a substitute for
|
|
52
|
+
secure code, and it is not a replacement for a mature product such as
|
|
53
|
+
ModSecurity with the OWASP Core Rule Set. Its detection rates are measured on
|
|
54
|
+
the project's own corpus (see the repository), not on all real-world attacks.
|
|
55
|
+
No WebSocket upgrade support in proxy mode; request paths are forwarded after
|
|
56
|
+
decoding and re-encoding.
|
|
57
|
+
|
|
58
|
+
Source, benchmark and dashboard: https://github.com/abuelmagd1/waf-exploitation-test-suite
|
hisn_waf-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hisn-waf
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Lightweight regex-based WAF for Python: WSGI middleware and standalone reverse proxy with decoding of URL/Base64/hex/entity evasions, SQLite logging and a built-in benchmark.
|
|
5
|
+
Author: Ahmed Abuelmagd
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/abuelmagd1/waf-exploitation-test-suite
|
|
8
|
+
Project-URL: Issues, https://github.com/abuelmagd1/waf-exploitation-test-suite/issues
|
|
9
|
+
Keywords: waf,security,wsgi,middleware,reverse-proxy,sql-injection,xss,owasp
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Topic :: Security
|
|
13
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: regex>=2024.11.6
|
|
23
|
+
Provides-Extra: proxy
|
|
24
|
+
Requires-Dist: waitress<4.0,>=3.0; extra == "proxy"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# hisn-waf (حصن)
|
|
28
|
+
|
|
29
|
+
A lightweight web application firewall for Python. It runs either as **WSGI
|
|
30
|
+
middleware** inside any WSGI app (Flask, Django, ...) or as a **standalone
|
|
31
|
+
reverse proxy** in front of an HTTP backend written in any language.
|
|
32
|
+
|
|
33
|
+
* 9 rules / 55 regex patterns for SQL injection, XSS, path traversal, command
|
|
34
|
+
injection, XXE, SSRF and NoSQL injection, in an editable JSON file.
|
|
35
|
+
* Decodes evasions before matching: repeated URL encoding, Base64, hex, HTML
|
|
36
|
+
entities, `\uXXXX`, SQL comments.
|
|
37
|
+
* Fail-closed limits and per-pattern regex timeouts against oversized or
|
|
38
|
+
pathological input.
|
|
39
|
+
* `block` or `detect` (log only) mode, optional anomaly scoring.
|
|
40
|
+
* Every request and detection is logged to SQLite with a correlation ID
|
|
41
|
+
(`X-WAF-Request-ID`).
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install hisn-waf # middleware only
|
|
47
|
+
pip install "hisn-waf[proxy]" # adds the reverse proxy server
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The import name is `waf`.
|
|
51
|
+
|
|
52
|
+
## Reverse proxy
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
waf-proxy --backend http://127.0.0.1:3000 --listen 0.0.0.0:8080 --mode detect
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Run in `detect` mode first to see what would be blocked, then switch to
|
|
59
|
+
`--mode block`. Settings can also come from environment variables
|
|
60
|
+
(`WAF_PROXY_BACKEND`, `WAF_PROXY_LISTEN`, `WAF_MODE`, `WAF_RULES_PATH`, ...).
|
|
61
|
+
Redirects from the backend are passed through, not followed, and the backend
|
|
62
|
+
address cannot be influenced by a request.
|
|
63
|
+
|
|
64
|
+
## WSGI middleware
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from waf.database import initialize_database
|
|
68
|
+
from waf.middleware import WAFMiddleware
|
|
69
|
+
|
|
70
|
+
initialize_database("waf.sqlite3")
|
|
71
|
+
app.wsgi_app = WAFMiddleware(app.wsgi_app, "waf.sqlite3", "X-WAF-Test-Block", "1", 1_048_576,
|
|
72
|
+
deep_percent_decode=True)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Honest limits
|
|
76
|
+
|
|
77
|
+
This is a signature (regex) WAF. It reduces risk but is not a substitute for
|
|
78
|
+
secure code, and it is not a replacement for a mature product such as
|
|
79
|
+
ModSecurity with the OWASP Core Rule Set. Its detection rates are measured on
|
|
80
|
+
the project's own corpus (see the repository), not on all real-world attacks.
|
|
81
|
+
No WebSocket upgrade support in proxy mode; request paths are forwarded after
|
|
82
|
+
decoding and re-encoding.
|
|
83
|
+
|
|
84
|
+
Source, benchmark and dashboard: https://github.com/abuelmagd1/waf-exploitation-test-suite
|
hisn_waf-1.0.0/README.md
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
# Local WAF Demonstration, Test Suite, and Monitoring Dashboard
|
|
2
|
+
|
|
3
|
+
A Flask application behind WSGI middleware, with a separate payload variation
|
|
4
|
+
and evaluation tool. Phases 1 and 2 demonstrate request capture, configurable
|
|
5
|
+
regex inspection, a test blocking decision, HTTP 403 responses, and SQLite
|
|
6
|
+
request/detection logging. Phase 3 generates labeled harmless test inputs,
|
|
7
|
+
sends them only to the local demo's `/echo` endpoint, and evaluates results
|
|
8
|
+
against correlated WAF request and detection records. This is an academic
|
|
9
|
+
demonstration, not a complete security control.
|
|
10
|
+
|
|
11
|
+
## Requirements and installation
|
|
12
|
+
|
|
13
|
+
Python 3.10 or newer is recommended. From the project directory, create and
|
|
14
|
+
activate a virtual environment, then install dependencies:
|
|
15
|
+
|
|
16
|
+
```powershell
|
|
17
|
+
python -m venv .venv
|
|
18
|
+
.venv\Scripts\Activate.ps1
|
|
19
|
+
python -m pip install -r requirements.txt
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Run locally
|
|
23
|
+
|
|
24
|
+
Dashboard authentication is always enabled. Set a generated session-signing key
|
|
25
|
+
and create a password hash before starting the app. These PowerShell commands
|
|
26
|
+
generate values without placing a password or fixed secret in the source:
|
|
27
|
+
|
|
28
|
+
```powershell
|
|
29
|
+
$env:WAF_DASHBOARD_SECRET_KEY = python -c "import secrets; print(secrets.token_urlsafe(48))"
|
|
30
|
+
$env:WAF_DASHBOARD_PASSWORD_HASH = python -c "from getpass import getpass; from werkzeug.security import generate_password_hash; print(generate_password_hash(getpass('Dashboard password: ')))"
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The password prompt is hidden; keep the printed hash and generated key in your
|
|
34
|
+
local environment or a deployment secret store. The app fails to start if
|
|
35
|
+
either setting is missing or invalid. No unauthenticated mode is provided.
|
|
36
|
+
|
|
37
|
+
Dashboard login throttling defaults to 5 failed attempts per client address in
|
|
38
|
+
a 300-second window. Further attempts receive HTTP 429 with the same generic
|
|
39
|
+
sign-in message; password-hash verification is skipped while throttled. The
|
|
40
|
+
limit counts attempts currently being checked as well, preventing concurrent
|
|
41
|
+
requests from exceeding the configured hash-work cap. A successful login
|
|
42
|
+
clears that address's failure state. Configure the policy with
|
|
43
|
+
`WAF_DASHBOARD_LOGIN_MAX_FAILURES` (1–100),
|
|
44
|
+
`WAF_DASHBOARD_LOGIN_WINDOW_SECONDS` (1–86400), and
|
|
45
|
+
`WAF_DASHBOARD_LOGIN_MAX_CLIENTS` (16–65536; default 4096). State is held in a
|
|
46
|
+
thread-safe, bounded in-memory table and expired entries are removed on later
|
|
47
|
+
login attempts. When the address table is full, new addresses share one
|
|
48
|
+
bounded overflow bucket rather than evicting active limits. The limiter keys
|
|
49
|
+
only on the server-observed remote address and ignores `X-Forwarded-For` and
|
|
50
|
+
other client-supplied identity headers. This can group users behind NAT or a
|
|
51
|
+
reverse proxy; configure trusted proxy address handling carefully. The state
|
|
52
|
+
is local to one application process, so multiple WSGI worker processes do not
|
|
53
|
+
share counts. This is a bounded demonstration safeguard, not production-grade
|
|
54
|
+
distributed brute-force protection; deployments should also enforce rate
|
|
55
|
+
limits at a trusted reverse proxy or shared service.
|
|
56
|
+
|
|
57
|
+
```powershell
|
|
58
|
+
python app.py
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The development server listens on `127.0.0.1:5000`. The SQLite database is
|
|
62
|
+
created at `data/waf.sqlite3` by default. Open
|
|
63
|
+
`http://127.0.0.1:5000/dashboard/` and enter the password used to create the
|
|
64
|
+
configured hash. Set `WAF_DATABASE_PATH` to change the database location,
|
|
65
|
+
`WAF_LOG_LEVEL` to configure logging, or `WAF_MAX_BODY_BYTES` to change the
|
|
66
|
+
inspected body size limit (default: 1 MiB). Authentication remains required
|
|
67
|
+
even when the development server binds to loopback.
|
|
68
|
+
|
|
69
|
+
## Exercise allowed and blocked requests
|
|
70
|
+
|
|
71
|
+
Allowed request:
|
|
72
|
+
|
|
73
|
+
```powershell
|
|
74
|
+
curl.exe "http://127.0.0.1:5000/echo?item=one&item=two"
|
|
75
|
+
curl.exe -X POST "http://127.0.0.1:5000/echo" -H "Content-Type: text/plain" --data "hello"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Blocked test request (the default configured decision):
|
|
79
|
+
|
|
80
|
+
```powershell
|
|
81
|
+
curl.exe -i "http://127.0.0.1:5000/echo" -H "X-WAF-Test-Block: 1"
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The blocked request returns HTTP 403. Configure the header name and exact value
|
|
85
|
+
with `WAF_BLOCK_HEADER` and `WAF_BLOCK_HEADER_VALUE`. This deterministic trigger
|
|
86
|
+
is retained for middleware testing alongside the Phase 2 regex rules.
|
|
87
|
+
|
|
88
|
+
## Configure inspection rules
|
|
89
|
+
|
|
90
|
+
Default rules are in `waf/data/default_rules.json`. Each entry defines a unique
|
|
91
|
+
`id`, `description`, `category`, `severity`, regex `pattern`, and inspected
|
|
92
|
+
`components` (`path`, `query`, `headers`, and/or `body`). Set `WAF_RULES_PATH` to
|
|
93
|
+
use another JSON rule list. A matching rule blocks the request and writes its
|
|
94
|
+
ID, category, severity, inspected component, and reason to `detection_events`.
|
|
95
|
+
Rules may provide one `pattern` or a bounded `patterns` list. SQLI-001 uses
|
|
96
|
+
separately compiled indicator patterns so a no-match search does not repeatedly
|
|
97
|
+
evaluate one large alternative expression; each regex still has the existing
|
|
98
|
+
10 ms timeout, and all searches share the existing request-wide budget.
|
|
99
|
+
Percent decoding is bounded to three total passes for query names and values:
|
|
100
|
+
`parse_qs` decodes once, and the WAF normalization engine uses at most the
|
|
101
|
+
remaining two passes. Both decoded query parameter names and values are
|
|
102
|
+
inspected. `PATH_INFO` is provided by the WSGI server and may already reflect
|
|
103
|
+
server-side URL decoding; the WAF applies up to three further passes to that
|
|
104
|
+
value. Header values and UTF-8-decoded request bodies receive up to three WAF
|
|
105
|
+
normalization passes. Malformed percent escapes remain literal, and invalid
|
|
106
|
+
query UTF-8 is replaced safely during parsing.
|
|
107
|
+
|
|
108
|
+
The engine inspects each complete component value, up to the configured
|
|
109
|
+
`WAF_MAX_INSPECTED_VALUE_CHARS` limit (default: 1 MiB). Values exceeding that
|
|
110
|
+
limit are rejected with HTTP 413 before regex matching; they are never silently
|
|
111
|
+
truncated and allowed. This cap is bounded at 1 MiB. The body byte limit and
|
|
112
|
+
the per-value character limit both apply; valid request values within those
|
|
113
|
+
limits are inspected completely. Regex timeouts and the 250 ms request-wide
|
|
114
|
+
budget remain fail-closed, so a value can still be rejected when matching
|
|
115
|
+
cannot finish within those budgets.
|
|
116
|
+
|
|
117
|
+
The SQLI-001 block-comment indicator supports `/* ... */` comments with up to
|
|
118
|
+
256 content characters (260 characters including the delimiters). Internal
|
|
119
|
+
asterisks are allowed unless they begin the closing `*/`. Longer or unterminated
|
|
120
|
+
comments do not match this indicator; the normal regex timeout and per-request
|
|
121
|
+
matching budget remain in force.
|
|
122
|
+
|
|
123
|
+
The initial SQL injection and XSS patterns are demonstration rules. SQL line
|
|
124
|
+
comments require statement context such as `SELECT ... FROM ... --`; block
|
|
125
|
+
comments require SQL syntax on both sides, such as `UNION/*...*/SELECT`. A
|
|
126
|
+
standalone comment or partial prose like `SELECT a plan -- sale` is not
|
|
127
|
+
sufficient. Scriptable URI detection requires a `javascript:` scheme in an
|
|
128
|
+
`href`, `src`, `action`, or `formaction` attribute; a plain documentation
|
|
129
|
+
mention, including a `javascript:alert(1)` example, is not sufficient. Script
|
|
130
|
+
elements and executable event-handler indicators remain separate XSS signals.
|
|
131
|
+
The rules can still miss attacks and can also match benign input. They do not
|
|
132
|
+
establish security effectiveness or replace application-level validation and
|
|
133
|
+
output encoding.
|
|
134
|
+
|
|
135
|
+
Custom patterns use the timeout-capable `regex` package. The engine caps the
|
|
136
|
+
configuration at 100 rules, 512 characters per pattern, and 16,384 total pattern
|
|
137
|
+
characters; each match has a 10 ms timeout and each request has a 250 ms regex
|
|
138
|
+
budget. A timeout fails closed with HTTP 403 and a `rule_evaluation_timeout`
|
|
139
|
+
decision. These limits reduce, but cannot eliminate, resource risks from custom
|
|
140
|
+
rules and unusually high request volume.
|
|
141
|
+
|
|
142
|
+
Request inspection defaults to an 8 KiB query string, 128 query fields, 100
|
|
143
|
+
headers, an 8 KiB individual header field line, 32 KiB aggregate header field
|
|
144
|
+
lines, an 8 KiB request path, the configured body cap, and a 1 MiB maximum
|
|
145
|
+
inspected component value. Override these with
|
|
146
|
+
`WAF_MAX_QUERY_BYTES`, `WAF_MAX_QUERY_FIELDS`, `WAF_MAX_HEADERS`,
|
|
147
|
+
`WAF_MAX_HEADER_BYTES`, `WAF_MAX_TOTAL_HEADER_BYTES`, and `WAF_MAX_PATH_BYTES`.
|
|
148
|
+
Set `WAF_MAX_INSPECTED_VALUE_CHARS` to lower the per-value character cap; it
|
|
149
|
+
cannot exceed 1 MiB. A body whose decoded text exceeds this cap receives HTTP
|
|
150
|
+
413 even if `WAF_MAX_BODY_BYTES` is configured higher.
|
|
151
|
+
Header sizes count UTF-8 bytes in `Name: Value`; aggregate size is the sum of
|
|
152
|
+
those field lines. The WSGI middleware rejects oversized paths, headers, query
|
|
153
|
+
strings, and bodies with HTTP 413 before rule inspection. A WSGI server or
|
|
154
|
+
reverse proxy may impose its own request-line or header limits before the
|
|
155
|
+
request reaches this middleware; these application checks cannot recover
|
|
156
|
+
resources already consumed upstream.
|
|
157
|
+
|
|
158
|
+
## Extended rules and decoded views
|
|
159
|
+
|
|
160
|
+
The default rule set has nine rules (52 patterns): `SQLI-001`, `SQLI-002`
|
|
161
|
+
(stacked queries, `SLEEP`/`WAITFOR`, `information_schema`, `LOAD_FILE`,
|
|
162
|
+
`xp_cmdshell`, unbalanced-quote boolean strings), `XSS-001`, `XSS-002` (any HTML
|
|
163
|
+
event-handler attribute, `iframe`/`object`/`embed`, `data:text/html`,
|
|
164
|
+
`document.cookie`), `PATH-001` (`../` traversal, sensitive files, `php://` style
|
|
165
|
+
wrappers) and `CMDI-001` (`; cmd`, `| cmd`, `&& cmd`, `$(...)`, backticks,
|
|
166
|
+
`${jndi:`), plus `XXE-001` (DOCTYPE/ENTITY declarations, XInclude),
|
|
167
|
+
`SSRF-001` (loopback, private-range and cloud-metadata URLs) and `NOSQL-001`
|
|
168
|
+
(MongoDB-style `$ne`/`$where` operators). Rules run in file order and the first match wins, so keep the
|
|
169
|
+
original rules first. `PATH-001` and `CMDI-001` skip headers to avoid noisy
|
|
170
|
+
matches on `Referer`/`User-Agent`. A context-free `javascript:alert(1)` in prose
|
|
171
|
+
is intentionally allowed.
|
|
172
|
+
|
|
173
|
+
Each value is matched in up to three forms: original, percent-normalized, and
|
|
174
|
+
"decoded" views built by `waf.normalization.decoded_views`:
|
|
175
|
+
|
|
176
|
+
- Base64 and URL-safe Base64 tokens of at least 12 characters, and hex tokens
|
|
177
|
+
(optionally `0x`-prefixed) of at least 12 hex characters;
|
|
178
|
+
- HTML entities (`<`, `<`) and `\uXXXX` / `\xNN` escapes;
|
|
179
|
+
- SQL block comments replaced by a space, so `UNION/**/SELECT` is seen as
|
|
180
|
+
`UNION SELECT`.
|
|
181
|
+
|
|
182
|
+
Decoding can be chained at most twice (for example Base64 inside Base64), a
|
|
183
|
+
token is used only when it decodes to printable UTF-8, at most 12 views are
|
|
184
|
+
tried per value, and each view obeys the same size limits and regex time
|
|
185
|
+
budgets as the original. Percent-decoding itself is still capped at three total
|
|
186
|
+
passes by design (see `tests/integration/test_middleware.py`) in the bare
|
|
187
|
+
middleware class; the application enables the extra `WAF_DEEP_PERCENT_DECODE`
|
|
188
|
+
view by default (described below). Matches on a
|
|
189
|
+
decoded view are recorded as `matched decoded <component> input`. Each pattern
|
|
190
|
+
of a rule should start with a literal character or word: patterns that begin
|
|
191
|
+
with a multi-word alternation are noticeably slower on very large values and
|
|
192
|
+
can hit the 10 ms per-regex timeout, which fails closed with HTTP 403.
|
|
193
|
+
|
|
194
|
+
## Evasion test catalog and results
|
|
195
|
+
|
|
196
|
+
The tester catalog holds 26 cases (SQL injection, XSS, path traversal, command
|
|
197
|
+
injection, XXE, SSRF, NoSQL injection and benign prose) mutated by 14 transformations: `original`, `url`,
|
|
198
|
+
`double_url`, `triple_url`, `quad_url`, `base64`, `double_base64`, `hex`,
|
|
199
|
+
`html_entity`, `unicode_escape`, `sql_comment_space`, `uppercase`, `lowercase`
|
|
200
|
+
and `alternating_case` (364 requests per run; hard caps are 400 tests and 450
|
|
201
|
+
requests). Note that the HTTP client adds one more percent-encoding layer when it
|
|
202
|
+
sends a value, so `triple_url` reaches the WAF with four layers.
|
|
203
|
+
|
|
204
|
+
Measured on the local demo before and after the Phase 4 hardening
|
|
205
|
+
(see [docs/REPORT.md](docs/REPORT.md) for details and screenshots):
|
|
206
|
+
|
|
207
|
+
| Run | Detection | Bypass rate | False positives | Filter efficiency |
|
|
208
|
+
|---|---|---|---|---|
|
|
209
|
+
| Baseline | 62.8% (123/196) | 37.2% | 0 / 84 | 73.9% |
|
|
210
|
+
| After hardening (default) | 86.7% (170/196) | 13.3% | 0 / 84 | 90.7% |
|
|
211
|
+
| With `WAF_DEEP_PERCENT_DECODE=true` | 100% (196/196) | 0% | 0 / 84 | 100% |
|
|
212
|
+
|
|
213
|
+
The three rows above were measured on the original 20-case catalog with deep
|
|
214
|
+
decode off or on. The extended 26-case catalog (364 requests) gives 86.5%
|
|
215
|
+
(230/266) with deep decode off and 100% (266/266) with it on, 0 / 98 false
|
|
216
|
+
positives in both cases.
|
|
217
|
+
|
|
218
|
+
`WAF_DEEP_PERCENT_DECODE` is **on by default** in the application: besides the
|
|
219
|
+
three normal percent-decoding passes, rules also run on a view decoded up to six
|
|
220
|
+
more times, so triple/quad URL encoding is detected in its real category and
|
|
221
|
+
benign over-encoded text is not flagged. Set `WAF_DEEP_PERCENT_DECODE=false` to
|
|
222
|
+
restore the strict three-pass behavior. Values encoded more than nine times in
|
|
223
|
+
total still pass; the cap keeps the work per request bounded.
|
|
224
|
+
|
|
225
|
+
## Modes, anomaly scoring and the benchmark
|
|
226
|
+
|
|
227
|
+
- `WAF_MODE=block` (default) rejects matching requests with 403.
|
|
228
|
+
`WAF_MODE=detect` only records the detection (`detected_only:<rule>` in the
|
|
229
|
+
request log) and lets the request through, which is useful for tuning rules
|
|
230
|
+
on real traffic before blocking.
|
|
231
|
+
- `WAF_ANOMALY_THRESHOLD=0` (default) blocks on the first matching rule.
|
|
232
|
+
A positive value evaluates every rule, adds a score per match (low 2, medium 3,
|
|
233
|
+
high 4, critical 5) and blocks only when the total reaches the threshold, e.g.
|
|
234
|
+
`5` lets a single high-severity match through but blocks two matches.
|
|
235
|
+
- The live suite expects blocking behavior, so run it with `WAF_MODE=block`.
|
|
236
|
+
|
|
237
|
+
The in-process benchmark needs no server and runs in a couple of seconds:
|
|
238
|
+
|
|
239
|
+
```powershell
|
|
240
|
+
python -m tester.benchmark
|
|
241
|
+
python -m tester.benchmark --out docs/BENCHMARK.md --json data/benchmark.json
|
|
242
|
+
python -m tester.benchmark --no-deep --misses 20
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
It sends 101 attack strings in 7 families (SQL injection, XSS, path traversal,
|
|
246
|
+
command injection, XXE, SSRF, NoSQL injection) and 72 benign strings through 21
|
|
247
|
+
techniques (the 14 single transformations plus 7 chained ones such as
|
|
248
|
+
`base64+url`), prints detection by category and by technique, lists false
|
|
249
|
+
positives and the strings that slipped through, and can fail a CI job with
|
|
250
|
+
`--min-detection` and `--max-false-positives`. Current result with default
|
|
251
|
+
settings: 99.8% detection (2117/2121), 0 false positives (0 / 1368); the only
|
|
252
|
+
misses are Base64 of a 4-character payload, which is shorter than the 8-character
|
|
253
|
+
minimum token. With `--no-deep` detection is 90.3%. See `docs/BENCHMARK.md`.
|
|
254
|
+
`.github/workflows/ci.yml` runs the tests and this quality gate on every push.
|
|
255
|
+
|
|
256
|
+
### Comparing against another WAF (for example OWASP CRS)
|
|
257
|
+
|
|
258
|
+
`tester.compare` scores any WAF that is reachable on loopback with the same
|
|
259
|
+
corpus and prints a side-by-side table:
|
|
260
|
+
|
|
261
|
+
```powershell
|
|
262
|
+
python -m tester.compare --target http://127.0.0.1:8080/ --name "OWASP CRS" --builtin
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
Each variant is sent as `GET <path>?q=<value>` and a 403 (change it with
|
|
266
|
+
`--block-status`) counts as blocked. Only loopback HTTP targets are accepted,
|
|
267
|
+
and proxy variables, redirects and credentials are ignored. Pointing it at this
|
|
268
|
+
project's own app (`--target http://127.0.0.1:5000/echo`) gives the same numbers
|
|
269
|
+
as the in-process benchmark, which confirms the middleware sees the requests
|
|
270
|
+
exactly as the benchmark models them. `deploy/crs/docker-compose.yml` starts
|
|
271
|
+
ModSecurity with the OWASP Core Rule Set on `127.0.0.1:8080`; it needs Docker
|
|
272
|
+
and was **not** run in the development environment, so check the image names and
|
|
273
|
+
variables against the current OWASP documentation. No CRS numbers are quoted in
|
|
274
|
+
this repository because they have not been measured.
|
|
275
|
+
|
|
276
|
+
## Packaging and reverse-proxy mode
|
|
277
|
+
|
|
278
|
+
The WAF can run as a **standalone reverse proxy** in front of any HTTP backend,
|
|
279
|
+
in any language:
|
|
280
|
+
|
|
281
|
+
```powershell
|
|
282
|
+
python -m pip install -r requirements.txt
|
|
283
|
+
python -m waf.proxy --backend http://127.0.0.1:3000 --listen 127.0.0.1:8080 --mode detect
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
Every request is inspected first; blocked requests never reach the backend, and
|
|
287
|
+
the backend address comes only from configuration. Redirects are passed through,
|
|
288
|
+
the `X-Forwarded-*` headers are set by the proxy (client values are replaced),
|
|
289
|
+
and backend failures return 502/504. Logs go to the same SQLite schema, so the
|
|
290
|
+
dashboard can read them by pointing `WAF_DATABASE_PATH` at the proxy's database.
|
|
291
|
+
Limits: no WebSocket upgrades; paths are decoded and re-encoded before being
|
|
292
|
+
forwarded.
|
|
293
|
+
|
|
294
|
+
* **PyPI:** `pyproject.toml` builds the distribution `hisn-waf`
|
|
295
|
+
(`python -m build`, then `twine check dist/*`). It ships the `waf` package and
|
|
296
|
+
the `waf-proxy` command: `pip install "hisn-waf[proxy]"`. The built wheel
|
|
297
|
+
was installed in a clean virtual environment and run against a local backend.
|
|
298
|
+
`PACKAGE_README.md` is the page shown on PyPI.
|
|
299
|
+
* **Docker:** `Dockerfile` and `deploy/docker-compose.proxy.yml` run the proxy
|
|
300
|
+
as a non-root user. They were **not built** in the development environment
|
|
301
|
+
(no Docker daemon), so run `docker build -t waf-proxy .` once to confirm.
|
|
302
|
+
* **Releases:** `.github/workflows/publish.yml` publishes to PyPI (trusted
|
|
303
|
+
publishing) and to GitHub Container Registry when a GitHub release is
|
|
304
|
+
published. It has not been run; see its header comments for the one-time setup.
|
|
305
|
+
|
|
306
|
+
## Run tests
|
|
307
|
+
|
|
308
|
+
```powershell
|
|
309
|
+
python -m pytest -q
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
The tests use Flask's in-process test client, local loopback servers, and
|
|
313
|
+
temporary SQLite files. The runner rejects non-loopback destinations, pins
|
|
314
|
+
connections to validated loopback addresses, ignores proxy environment
|
|
315
|
+
variables, disables automatic redirects, and revalidates each redirect before
|
|
316
|
+
connecting. HTTPS is intentionally unsupported by this local HTTP demo.
|
|
317
|
+
|
|
318
|
+
## Run the Phase 3 local test suite
|
|
319
|
+
|
|
320
|
+
Start the application in one terminal:
|
|
321
|
+
|
|
322
|
+
```powershell
|
|
323
|
+
python app.py
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
In another terminal, run the pre-defined local cases and transformations:
|
|
327
|
+
|
|
328
|
+
```powershell
|
|
329
|
+
python -c "from tester.runner import run_suite; run = run_suite('http://127.0.0.1:5000', 'data/waf.sqlite3'); print(run)"
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
The suite sends GET requests only to the demo's `/echo` route. It includes
|
|
333
|
+
benign examples and clearly labeled SQL injection/XSS test patterns. Variants
|
|
334
|
+
include the original, URL and double URL encoding, Base64, hexadecimal, and
|
|
335
|
+
case changes. The request count, total duration, network timeouts, response
|
|
336
|
+
size, and redirect count have hard caps; these may be lowered through
|
|
337
|
+
`run_suite` arguments. There are no third-party targets or exploit actions.
|
|
338
|
+
|
|
339
|
+
Results are stored separately from ordinary request logs in `test_runs` and
|
|
340
|
+
`test_results` in the selected SQLite database. Each request has a
|
|
341
|
+
`X-WAF-Request-ID`; the runner checks that ID against the persisted request and
|
|
342
|
+
detection event. A bare HTTP 403 is not treated as a true positive. Ambiguous,
|
|
343
|
+
missing, timed out, network-error, oversized, redirected-out, and skipped cases
|
|
344
|
+
are excluded from the effectiveness denominators.
|
|
345
|
+
|
|
346
|
+
Metrics use only verified eligible outcomes: detection rate is `TP / (TP +
|
|
347
|
+
FN)` and false-positive rate is `FP / (FP + TN)`. Rates with a zero denominator
|
|
348
|
+
are stored as `null` (Python `None`). These measurements describe only this
|
|
349
|
+
small payload catalog and current rule configuration; they do not establish
|
|
350
|
+
general SQL injection or XSS protection.
|
|
351
|
+
|
|
352
|
+
## Monitoring dashboard
|
|
353
|
+
|
|
354
|
+
With the app running and authentication configured, open
|
|
355
|
+
`http://127.0.0.1:5000/dashboard/` and sign in. The dashboard
|
|
356
|
+
provides an overview of request and detection counts, daily request activity,
|
|
357
|
+
and categories present in actual detection records. The Request Logs page
|
|
358
|
+
supports pagination, text search, decision/method filters, and metadata-only
|
|
359
|
+
request details. Detection Events supports category, severity, and date
|
|
360
|
+
filters. Test Suite lists persisted Phase 3 runs and individual outcomes, while
|
|
361
|
+
Metrics recomputes the latest run's confusion matrix using `waf/metrics.py` and
|
|
362
|
+
adds the bypass rate (FN / (TP + FN)), filter efficiency ((TP + TN) / all) and
|
|
363
|
+
bypass breakdowns per transformation technique and per attack category. The
|
|
364
|
+
Overview shows the latest run's bypass rate and filter efficiency next to the
|
|
365
|
+
blocked and allowed counters.
|
|
366
|
+
|
|
367
|
+

|
|
368
|
+
|
|
369
|
+
Dashboard reads use parameterized SQLite statements, bounded pagination and
|
|
370
|
+
filters, and Jinja's automatic HTML escaping. Every dashboard page, detail
|
|
371
|
+
route, and static asset requires a signed authenticated session. Sessions use
|
|
372
|
+
HttpOnly, SameSite=Lax cookies, CSRF tokens on login and logout, and a 30-minute
|
|
373
|
+
sliding expiration by default (`WAF_DASHBOARD_SESSION_LIFETIME_SECONDS`, allowed
|
|
374
|
+
range 60–86400). Cookies are Secure for HTTPS requests; set
|
|
375
|
+
`WAF_DASHBOARD_COOKIE_SECURE=true` when TLS terminates at a proxy and Flask sees
|
|
376
|
+
plain HTTP. Configure trusted proxy scheme handling carefully. Request bodies
|
|
377
|
+
and headers are not rendered. Detection categories and severity filter choices
|
|
378
|
+
come from stored events. Dashboard charts use local JavaScript and canvas; no
|
|
379
|
+
external fonts, chart libraries, URLs, or remote data sources are loaded. The
|
|
380
|
+
dashboard uses the existing SQLite database and does not add or migrate tables.
|
|
381
|
+
|
|
382
|
+
## Current scope and limitations
|
|
383
|
+
|
|
384
|
+
- The middleware records method, path, query parameters, headers, request body,
|
|
385
|
+
allow/block decision, reason, and response status.
|
|
386
|
+
- Request bodies above the configured inspection limit receive HTTP 413.
|
|
387
|
+
- Bodies with a valid `Content-Length` are read into a bounded snapshot and
|
|
388
|
+
restored for Flask. Invalid framing returns HTTP 400; oversized bodies return
|
|
389
|
+
413. A seekable WSGI input stream is probed by at most one byte and restored
|
|
390
|
+
when neither a length nor a server-terminated marker is present; detected
|
|
391
|
+
unframed body bytes are rejected (HTTP 400 for uncommon methods, HTTP 411
|
|
392
|
+
for POST/PUT/PATCH/DELETE). If the stream cannot be safely probed,
|
|
393
|
+
body-capable methods without framing receive HTTP 411. A verified empty
|
|
394
|
+
stream is accepted, and explicit `Content-Length: 0` is the portable way to
|
|
395
|
+
express an empty body on methods that may carry one. GET and HEAD with a
|
|
396
|
+
non-seekable stream and no length are treated as bodyless. HTTP/1.1 framing
|
|
397
|
+
defines the request body length as zero when neither `Content-Length` nor
|
|
398
|
+
`Transfer-Encoding` is present (RFC 9112, Section 6.3). Core WSGI allows
|
|
399
|
+
`CONTENT_LENGTH` to be absent and does not provide a portable non-blocking
|
|
400
|
+
way for middleware to test a non-seekable input stream for EOF. The
|
|
401
|
+
middleware therefore does not probe or consume these streams; the HTTP
|
|
402
|
+
server or gateway must enforce message boundaries and must not expose
|
|
403
|
+
unframed bytes as the body. Gateways translating protocols with different
|
|
404
|
+
body framing must set a valid `CONTENT_LENGTH` or the server-specific
|
|
405
|
+
`wsgi.input_terminated` extension for safely readable bodies. If a gateway
|
|
406
|
+
violates this contract, middleware cannot distinguish hidden body bytes
|
|
407
|
+
from a valid empty stream without risking a blocking read or consuming data.
|
|
408
|
+
- Chunked bodies are inspected only when the WSGI server marks the decoded input
|
|
409
|
+
with `wsgi.input_terminated`; the middleware reads at most the body limit plus
|
|
410
|
+
one byte. Werkzeug's development server provides this marker for chunked
|
|
411
|
+
requests. Other servers must provide the same WSGI extension or the request
|
|
412
|
+
is rejected for body-capable methods. The test suite exercises both the
|
|
413
|
+
marker-based middleware path and an end-to-end chunked request to the local
|
|
414
|
+
Werkzeug server.
|
|
415
|
+
- Request logs redact supported sensitive header and field values. Unsupported
|
|
416
|
+
body formats are omitted; still avoid using real credentials or sensitive
|
|
417
|
+
data with the demo.
|
|
418
|
+
- The test blocking header remains available for deterministic middleware
|
|
419
|
+
testing. Rule matches are also blocked and logged with their rule details.
|
|
420
|
+
- Detection uses the submitted values before persistence redaction. Authorization,
|
|
421
|
+
cookie, password, token, API-key, session, and credential-like names are
|
|
422
|
+
normalized and redacted in headers, query fields, JSON bodies, and
|
|
423
|
+
URL-encoded form bodies. Other non-empty body content types are omitted from
|
|
424
|
+
stored logs because their secrets cannot be safely identified generically.
|
|
425
|
+
- SQLite `:memory:` paths are rejected because this app uses short-lived
|
|
426
|
+
connections; use a file database, including a temporary file for tests.
|
|
427
|
+
- The runner allows only plain HTTP to numeric loopback or hostnames whose
|
|
428
|
+
complete DNS answer set is loopback. It uses the validated numeric address
|
|
429
|
+
for the socket connection to prevent a second DNS lookup from redirecting
|
|
430
|
+
traffic. Redirects must remain on the same validated origin and approved demo
|
|
431
|
+
routes. DNS resolution itself is bounded, but Python cannot forcibly stop a
|
|
432
|
+
resolver thread that is stuck inside the operating system resolver; timed-out
|
|
433
|
+
resolver workers are abandoned and limited by a semaphore.
|
|
434
|
+
- The test catalog and rule set are intentionally small. Nested or chained
|
|
435
|
+
encodings, tokens below the minimum length, and obfuscation outside the
|
|
436
|
+
supported views can still evade the demonstration rules, and harmless-looking content can trigger
|
|
437
|
+
false positives. The reported metrics are not a security certification.
|
|
438
|
+
- Dashboard data is read from the current SQLite database. A single configured
|
|
439
|
+
password protects all dashboard routes; role-based access control is not
|
|
440
|
+
included. Failed-login throttling uses bounded, process-local counters keyed
|
|
441
|
+
by the server-observed client IP. Users sharing an IP also share its limit,
|
|
442
|
+
and counters are not distributed across multiple workers. Use HTTPS, a strong
|
|
443
|
+
generated session key, and a deployment secret store when exposing the app
|
|
444
|
+
beyond local development; deployments needing coordinated throttling should
|
|
445
|
+
enforce it at a trusted proxy or shared service.
|