Skip to main content

AI-Based-WAF

AI-Based-WAF is a lightweight machine learning–powered Web Application Firewall for Python web applications. It combines deterministic rule-based detection with statistical classification to identify and block common web attacks while maintaining low request latency.

It currently supports:

  • FastAPI
  • Flask
  • Django

Features

  • Hybrid rule-based and machine learning detection
  • SQL injection detection
  • Cross-site scripting (XSS) detection
  • Command injection detection
  • Path traversal detection
  • CRLF injection
  • Parameter Tampering
  • Scanner user-agent detection
  • Automatic pretrained model download
  • Support for custom Scikit-Learn models
  • JSONL request logging
  • Configurable confidence threshold
  • Dry-run mode
  • Request whitelisting
  • FastAPI, Flask, and Django middleware

Installation

Install the package:

pip install ai-based-waf

Framework-specific extras:

pip install ai-based-waf[fastapi]

pip install ai-based-waf[flask]

pip install ai-based-waf[django]

pip install ai-based-waf[all]

The pretrained model is downloaded automatically the first time AIWAF is initialized.


Quick Start

FastAPI

from fastapi import FastAPI
from aiwaf import AIWAFMiddleware

app = FastAPI()

app.add_middleware(AIWAFMiddleware)

@app.get("/")
def home():
    return {"message": "Protected by AIWAF"}

Run the application:

uvicorn main:app --reload

Flask

from flask import Flask
from aiwaf import flask_waf

app = Flask(__name__)

flask_waf(app)

@app.route("/")
def home():
    return "Protected by AIWAF"

app.run()

Django

Add the middleware to settings.py:

MIDDLEWARE = [
    ...
    "aiwaf.django_middleware.DjangoAIWAFMiddleware",
]

Optional configuration:

AIWAF_MODEL_PATH = None
AIWAF_BLOCK_THRESHOLD = 0.5
AIWAF_DRY_RUN = False
AIWAF_LOG_PATH = "logs/aiwaf.jsonl"

AIWAF_WHITELIST_PATHS = [
    "/health",
]

Detection Pipeline

Every incoming request passes through three stages:

Incoming Request
       │
       ▼

Rule Engine
    │
    ├── SQL Injection
    ├── Cross-Site Scripting
    ├── Command Injection
    ├── Path Traversal
    ├── ....
    └── Scanner Detection
    

       │
       ▼

Safe Passthrough

       │

Clean traffic bypasses the ML model.

       │
       ▼

Machine Learning

Feature Extraction

↓

Classification

↓

Allow or Block

The rule engine immediately blocks well-known attack patterns. Requests that are clearly benign bypass machine learning inference. Remaining traffic is evaluated using the trained classification model.


Supported Attacks

Attack Example
SQL Injection ' OR 1=1 --
Cross-Site Scripting <script>alert(1)</script>
Command Injection ; cat /etc/passwd
Path Traversal ../../etc/passwd
Scanner Detection sqlmap, Nikto, Burp Suite, Nuclei

etc


Configuration

FastAPI

app.add_middleware(
    AIWAFMiddleware,
    block_threshold=0.5,
    dry_run=False,
    whitelist_paths=["/health"],
)

Flask

flask_waf(
    app,
    block_threshold=0.5,
    dry_run=False,
)

Django

AIWAF_BLOCK_THRESHOLD = 0.5
AIWAF_DRY_RUN = False

Using a Custom Model

AIWAF can load any Scikit-Learn pipeline that implements both predict() and predict_proba().

FastAPI

app.add_middleware(
    AIWAFMiddleware,
    model_path="models/random_forest.pkl",
)

Flask

flask_waf(
    app,
    model_path="models/random_forest.pkl",
)

Django

AIWAF_MODEL_PATH = "models/random_forest.pkl"

Automatic Model Download

If no local model is provided, AIWAF automatically downloads the pretrained model from the official model repository and stores it in:

~/.aiwaf/models/

Downloaded models are cached locally and verified using SHA-256 checksums before being loaded.


Response Headers

Successful responses include:

X-AIWAF-Decision
X-AIWAF-Confidence
X-AIWAF-Latency-ms

Blocked requests return:

HTTP 403 Forbidden

Example response:

{
    "error": "Request blocked by AIWAF",
    "request_id": "7af3d2e1",
    "reason": "Attack pattern detected: SQL Injection"
}

Logging

AIWAF records requests in JSON Lines format.

This format is compatible with:

  • Elasticsearch
  • Splunk
  • Grafana Loki
  • Datadog
  • Azure Monitor

Performance

AIWAF reduces inference overhead by combining rule-based detection with selective machine learning classification.

  1. Known attack patterns are blocked immediately.
  2. Clearly benign requests bypass model inference.
  3. Only uncertain requests are evaluated by the machine learning model.

This architecture minimizes latency while maintaining accurate detection of malicious traffic.


Examples

Example applications are available in the examples/ directory.

examples/
├── fastapi_app.py
├── flask_app.py
└── custom_model.py

Roadmap

  • Express.js middleware
  • Spring Boot integration
  • ASP.NET middleware
  • Laravel middleware
  • ONNX Runtime support
  • Docker deployment

Contributing

Contributions are welcome. Please open an issue to discuss major changes before submitting a pull request.


License

This project is licensed under the MIT License.

Metadata

Release files for ai-based-waf 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ai-based-waf 1.0.0
File Size Uploaded Provenance Actions
ai_based_waf-1.0.0.tar.gz 15.3 MB Without provenance Details for ai_based_waf-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ai-based-waf 1.0.0
File Interpreter ABI Platform Actions
ai_based_waf-1.0.0-py3-none-any.whl Python 3 none any Details for ai_based_waf-1.0.0-py3-none-any.whl

Total release size: 32.9 MB

Release files / ai_based_waf-1.0.0.tar.gz

Download URL ai_based_waf-1.0.0.tar.gz
Size 15.3 MB
Tags Source
SHA-256 checksum
How to use checksums
ea8789d589a90e601be253ae3f837f384922507a42d619e56298dd56651ab9b8
BLAKE2b-256 checksum
How to use checksums
1ad1b679125556ea55a5ec4d4056fe831d0eca8c824889f2c621bdf7741cb73c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / ai_based_waf-1.0.0-py3-none-any.whl

Download URL ai_based_waf-1.0.0-py3-none-any.whl
Size 17.6 MB
Tags Python 3
SHA-256 checksum
How to use checksums
6c83c66843b588428c3211347f9a333f7382e4224616ac41398d24e249ab66d7
BLAKE2b-256 checksum
How to use checksums
8a20a66de59ba4123ca3df7b27c03338d6f04df5c3c0fc6c88c1fef27434b974
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for ai-based-waf 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page