Metadata-Version: 2.4
Name: ai-based-waf
Version: 1.0.0
Summary: AI-Based Web Application Firewall (AIWAF) - ML-powered middleware for FastAPI, Flask, and Django
License: MIT
Project-URL: Homepage, https://github.com/Farooquekk/AI-Based-WAF
Project-URL: Repository, https://github.com/Farooquekk/AI-Based-WAF
Project-URL: Issues, https://github.com/Farooquekk/AI-Based-WAF/issues
Project-URL: Documentation, https://github.com/Farooquekk/AI-Based-WAF
Project-URL: ModelRepository, https://github.com/Farooquekk/ai-based-waf-models
Keywords: waf,web application firewall,security,machine learning,fastapi,flask,django,middleware,intrusion detection,sql injection,xss
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Security
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Framework :: Django
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: joblib>=1.5.3
Requires-Dist: numpy>=2.5.1
Requires-Dist: pandas>=3.0.3
Requires-Dist: scikit-learn>=1.7.2
Requires-Dist: xgboost>=3.3.0
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.139.2; extra == "fastapi"
Requires-Dist: starlette>=0.47.0; extra == "fastapi"
Provides-Extra: flask
Requires-Dist: flask>=3.1.3; extra == "flask"
Provides-Extra: django
Requires-Dist: django>=5.2; extra == "django"
Provides-Extra: all
Requires-Dist: fastapi>=0.139.2; extra == "all"
Requires-Dist: starlette>=0.47.0; extra == "all"
Requires-Dist: flask>=3.1.3; extra == "all"
Requires-Dist: django>=5.2; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Dynamic: license-file

# 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:

```bash
pip install ai-based-waf
```

Framework-specific extras:

```bash
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

```python
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:

```bash
uvicorn main:app --reload
```

---

### Flask

```python
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`:

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

Optional configuration:

```python
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:

```text
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

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

### Flask

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

### Django

```python
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

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

### Flask

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

### Django

```python
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:

```text
~/.aiwaf/models/
```

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

---

## Response Headers

Successful responses include:

```text
X-AIWAF-Decision
X-AIWAF-Confidence
X-AIWAF-Latency-ms
```

Blocked requests return:

```text
HTTP 403 Forbidden
```

Example response:

```json
{
    "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.

```text
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.
