# AIWAF Flask
AIWAF (AI Web Application Firewall) for Flask provides advanced, self-learning protection for your Flask web applications. It supports IP/keyword blocking, rate limiting, honeypot timing, header validation, anomaly detection, and UUID tampering, with flexible storage options: **database**, **CSV files**, or **in-memory**.
## Features
- IP and keyword blocking
- Rate limiting with burst detection
- Honeypot timing protection
- Header validation
- **AI-powered anomaly detection** - Machine learning to detect suspicious patterns
- UUID tampering detection
- **Path exemptions** - Prevent false positives for legitimate resources
- **Flexible storage**: Database, CSV files, or in-memory
- Zero-dependency protection (works without database)
## Function Names
AIWAF Flask provides two function names for registering middleware:
- **`register_aiwaf_middlewares(app)`** - Current recommended name
- **`register_aiwaf_protection(app)`** - Backward compatibility alias
Both functions work identically and provide the same protection features.
```python
from flask import Flask
from aiwaf_flask import register_aiwaf_middlewares
# OR: from aiwaf_flask import register_aiwaf_protection
app = Flask(__name__)
app.config['AIWAF_USE_CSV'] = True
# Both of these work the same way:
register_aiwaf_middlewares(app)
# register_aiwaf_protection(app) # Alternative
```
## Installation
```bash
# Basic installation (without AI features)
pip install aiwaf-flask
# With AI anomaly detection features
pip install aiwaf-flask[ai]
# Full installation (AI + development tools)
pip install aiwaf-flask[all]
```
### AI Dependencies
The AI anomaly detection middleware requires additional dependencies:
- **NumPy** (`>=1.20.0`) - For numerical computations and feature analysis
- **Scikit-learn** (`>=1.0.0`) - For machine learning model training and prediction
```bash
# Install AI dependencies separately if needed
pip install numpy>=1.20.0 scikit-learn>=1.0.0
```
## Quick Start
### Basic Setup (All Middlewares)
```python
from flask import Flask
from aiwaf_flask import AIWAF
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
# Enable all AIWAF protections (default behavior)
aiwaf = AIWAF(app) # ← Automatically enables ALL 7 middlewares
@app.route('/')
def home():
return 'Hello, AIWAF!'
if __name__ == '__main__':
app.run(debug=True)
```
### Default Behavior
**When you don't specify any middlewares, AIWAF automatically enables ALL available middlewares:**
```python
# These are all equivalent - they all enable ALL middlewares:
aiwaf = AIWAF(app) # ← Default: enables all 7 middlewares
aiwaf = AIWAF(app, middlewares=None) # ← Same as above
aiwaf = AIWAF() # ← Then call aiwaf.init_app(app)
aiwaf.init_app(app) # ← Also enables all middlewares
```
### Customized Middleware Selection
If you want **specific control**, you can selectively enable or disable middlewares:
```python
from flask import Flask
from aiwaf_flask import AIWAF
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
# Option 1: Enable ONLY specific middlewares
aiwaf = AIWAF(app, middlewares=[
'rate_limit', # Rate limiting protection
'header_validation', # HTTP header validation
'ai_anomaly', # AI-powered anomaly detection
'logging' # Request/response logging
])
# Option 2: Enable ALL middlewares EXCEPT specified ones
aiwaf = AIWAF(app, disable_middlewares=[
'honeypot', # Disable honeypot timing
'uuid_tamper' # Disable UUID tampering protection
])
# ↑ Enables 5 out of 7 middlewares (all except the 2 disabled)
# Option 3: Minimal security setup (essentials only)
aiwaf = AIWAF(app, middlewares=[
'ip_keyword_block', # Core IP/keyword blocking
'rate_limit', # Rate limiting
'logging' # Activity logging
])
# ↑ Enables only 3 specific middlewares
```
### Available Middlewares
| Middleware | Name | Description |
|------------|------|-------------|
| **IP & Keyword Block** | `ip_keyword_block` | Blocks malicious IPs and detects attack keywords |
| **Rate Limiting** | `rate_limit` | Protects against brute force and DDoS attacks |
| **Honeypot Timing** | `honeypot` | Detects automated form submissions |
| **Header Validation** | `header_validation` | Validates HTTP headers for security threats |
| **AI Anomaly Detection** | `ai_anomaly` | Machine learning-based pattern analysis |
| **UUID Tampering** | `uuid_tamper` | Protects against UUID manipulation attacks |
| **Request Logging** | `logging` | Comprehensive request/response logging |
### Initialization Patterns
| Pattern | Result | Use Case |
|---------|--------|----------|
| `AIWAF(app)` | **Enables ALL 7 middlewares** | Default - maximum protection |
| `AIWAF(app, middlewares=[...])` | Enables only specified | Custom selection |
| `AIWAF(app, disable_middlewares=[...])` | Enables all except specified | Mostly default with exceptions |
| `AIWAF()` then `init_app(app)` | **Enables ALL 7 middlewares** | Factory pattern |
### Middleware Management
```python
# Check which middlewares are enabled
enabled = aiwaf.get_enabled_middlewares()
print(f"Active protections: {enabled}")
# Check if specific middleware is enabled
if aiwaf.is_middleware_enabled('ai_anomaly'):
print("AI protection is active")
# Get middleware instance for advanced configuration
rate_limiter = aiwaf.get_middleware_instance('rate_limit')
# List all available middlewares
available = AIWAF.list_available_middlewares()
print(f"Available: {available}")
```
## Legacy Compatibility
The old registration method still works with new customization options:
```python
from aiwaf_flask import register_aiwaf_middlewares
# Legacy method with new features
register_aiwaf_middlewares(
app,
middlewares=['rate_limit', 'ai_anomaly'],
disable_middlewares=['honeypot']
)
```
## Storage Options
### 1. **CSV Storage (Recommended for small apps)**
```python
from flask import Flask
from aiwaf_flask import AIWAF
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
# CSV Configuration (no database needed!)
app.config['AIWAF_USE_CSV'] = True
app.config['AIWAF_DATA_DIR'] = 'aiwaf_data' # Optional: custom directory
# AIWAF Settings
app.config['AIWAF_RATE_WINDOW'] = 60
app.config['AIWAF_RATE_MAX'] = 100
# Initialize with custom middleware selection
aiwaf = AIWAF(app, middlewares=['rate_limit', 'ip_keyword_block', 'logging'])
```
### 2. **Database Storage (Recommended for production)**
```python
from flask import Flask
from aiwaf_flask.db_models import db
from aiwaf_flask import AIWAF
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
# Database Configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///aiwaf.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['AIWAF_USE_CSV'] = False # Force database usage
# AIWAF Settings
app.config['AIWAF_RATE_WINDOW'] = 60
app.config['AIWAF_RATE_MAX'] = 100
# Initialize with all middlewares
aiwaf = AIWAF(app, use_database=True)
```
app.config['AIWAF_RATE_MAX'] = 100
db.init_app(app)
with app.app_context():
db.create_all()
register_aiwaf_middlewares(app)
```
### 3. **In-Memory Storage (For testing)**
```python
from flask import Flask
from aiwaf_flask import register_aiwaf_middlewares
app = Flask(__name__)
# Force in-memory storage
app.config['AIWAF_USE_CSV'] = False
register_aiwaf_middlewares(app, use_database=False)
```
## Middleware Selection Guide
### 🛡️ **Minimal Security (Essential Protection)**
Best for: Small applications, development environments, minimal overhead
```python
aiwaf = AIWAF(app, middlewares=[
'ip_keyword_block', # Core attack prevention
'rate_limit', # Basic DDoS protection
'logging' # Security monitoring
])
```
### 🚀 **Standard Security (Recommended)**
Best for: Most production applications, balanced protection
```python
aiwaf = AIWAF(app, middlewares=[
'ip_keyword_block', # Core attack prevention
'rate_limit', # DDoS protection
'header_validation', # HTTP security
'ai_anomaly', # Smart threat detection
'logging' # Security monitoring
])
```
### 🔥 **Maximum Security (Full Protection)**
Best for: High-security applications, sensitive data handling
```python
# Enable all middlewares (default)
aiwaf = AIWAF(app)
```
### 🤖 **AI-Focused Security (Modern Protection)**
Best for: Applications with complex user patterns, advanced threat detection
```python
aiwaf = AIWAF(app, middlewares=[
'ai_anomaly', # Machine learning detection
'rate_limit', # Intelligent rate limiting
'header_validation', # Advanced header analysis
'logging' # ML-enhanced logging
])
```
### 🎯 **Custom Security (Selective Protection)**
Best for: Specific requirements, performance optimization
```python
# Disable specific middlewares you don't need
aiwaf = AIWAF(app, disable_middlewares=[
'honeypot', # If no forms in your app
'uuid_tamper' # If not using UUIDs
])
```
### Performance Impact Guide
| Middleware | Performance Impact | Use Case |
|------------|-------------------|----------|
| `ip_keyword_block` | **Low** | Essential for all apps |
| `rate_limit` | **Low** | Essential for public apps |
| `logging` | **Medium** | Important for monitoring |
| `header_validation` | **Low** | Good for web APIs |
| `ai_anomaly` | **Medium** | Advanced threat detection |
| `honeypot` | **Low** | Only useful with forms |
| `uuid_tamper` | **Very Low** | Only if using UUIDs |
## Configuration Options
```python
# Rate Limiting
app.config['AIWAF_RATE_WINDOW'] = 60 # Time window in seconds
app.config['AIWAF_RATE_MAX'] = 100 # Max requests per window
app.config['AIWAF_RATE_FLOOD'] = 200 # Auto-block threshold
# Honeypot Protection
app.config['AIWAF_MIN_FORM_TIME'] = 2.0 # Minimum form submission time
# AI Anomaly Detection
app.config['AIWAF_WINDOW_SECONDS'] = 60 # Analysis window for behavior patterns
app.config['AIWAF_DYNAMIC_TOP_N'] = 10 # Top N patterns to track
app.config['AIWAF_MODEL_PATH'] = 'aiwaf_flask/resources/model.pkl' # ML model path
# CSV Storage (if enabled)
app.config['AIWAF_USE_CSV'] = True # Enable CSV storage
app.config['AIWAF_DATA_DIR'] = 'aiwaf_data' # CSV files directory
# Logging Configuration
app.config['AIWAF_ENABLE_LOGGING'] = True # Enable request logging
app.config['AIWAF_LOG_DIR'] = 'aiwaf_logs' # Log files directory
app.config['AIWAF_LOG_FORMAT'] = 'combined' # Log format: combined, common, csv, json
# Path Exemptions
app.config['AIWAF_EXEMPT_PATHS'] = { # Paths exempt from AIWAF protection
'/favicon.ico',
'/robots.txt',
'*.css', # Wildcard patterns
'/static/', # Directory patterns
}
```
## Path Exemptions (Prevent False Positives)
AIWAF supports **path-based exemptions** to prevent false positives for legitimate resources that might return 404s or should not be subject to security filtering.
### Default Exempt Paths
AIWAF includes sensible defaults for common legitimate resources:
```python
# SEO and crawlers
'/favicon.ico', '/robots.txt', '/sitemap.xml', '/ads.txt'
# Apple and mobile devices
'/apple-touch-icon.png', '/manifest.json', '/browserconfig.xml'
# Health checks and monitoring
'/health', '/healthcheck', '/ping', '/status'
# Well-known URIs (SSL certificates, security policies)
'/.well-known/'
# Static file extensions (wildcards)
'*.css', '*.js', '*.png', '*.jpg', '*.ico', '*.woff2'
# Static directories
'/static/', '/assets/', '/css/', '/js/', '/images/', '/fonts/'
```
### Custom Path Exemptions
Configure custom exempt paths for your application:
```python
# Override defaults with custom paths
app.config['AIWAF_EXEMPT_PATHS'] = {
# Essential SEO files
'/favicon.ico',
'/robots.txt',
'/sitemap.xml',
# Health monitoring
'/health',
'/api/health',
# Public APIs
'/api/public/',
'/webhook/github',
# Static assets
'*.css', '*.js', '*.png', '*.pdf',
'/static/', '/assets/',
# Custom application paths
'/special-public-endpoint',
'/custom-health-check',
}
```
### Pattern Types
- **Exact paths**: `/favicon.ico` (matches exactly)
- **Wildcard patterns**: `*.css` (matches any .css file)
- **Directory patterns**: `/static/` (matches anything under /static/)
- **Case insensitive**: `/FAVICON.ICO` also matches
### Why Use Path Exemptions?
- **Prevent SEO issues**: Search engines can safely crawl `/robots.txt`, `/sitemap.xml`
- **Avoid blocking legitimate 404s**: `favicon.ico` requests won't trigger blocking
- **Load balancer compatibility**: Health checks always work (`/health`, `/ping`)
- **Static asset safety**: CSS/JS/images load without interference
- **SSL certificate support**: `/.well-known/` URIs for ACME challenges
## AI-Powered Anomaly Detection
AIWAF Flask includes advanced **machine learning-based anomaly detection** that analyzes request patterns and automatically identifies malicious behavior.
### How It Works
The AI anomaly detection middleware:
1. **Analyzes Request Patterns**: Tracks path length, keyword hits, response times, status codes, and burst patterns
2. **Uses Machine Learning**: Employs a trained model to detect anomalous behavior (requires NumPy)
3. **Intelligent Blocking**: Only blocks after analyzing multiple indicators to avoid false positives
4. **Dynamic Learning**: Learns new malicious keywords from scanning attempts
### Key Features
- **Multi-factor Analysis**: Combines ML predictions with behavioral analysis
- **Smart Thresholds**: Distinguishes between legitimate 404s and malicious scanning
- **Contextual Learning**: Only learns keywords from confirmed malicious contexts
- **Pattern Recognition**: Detects common attack patterns (SQLi, XSS, directory traversal)
### Configuration
```python
# AI Anomaly Detection Settings
app.config['AIWAF_WINDOW_SECONDS'] = 60 # Analysis window (seconds)
app.config['AIWAF_DYNAMIC_TOP_N'] = 10 # Top patterns to track
app.config['AIWAF_MODEL_PATH'] = 'path/to/model.pkl' # ML model location
# Install AI dependencies for full functionality
# pip install aiwaf-flask[ai]
# or: pip install numpy>=1.20.0 scikit-learn>=1.0.0
```
**Note**: AI anomaly detection requires NumPy and Scikit-learn. Install with `pip install aiwaf-flask[ai]` for full ML capabilities.
### Detection Criteria
The AI system analyzes multiple factors before blocking:
- **Keyword Density**: Number of malicious keywords in requests
- **Scanning Patterns**: Attempts to access non-existent admin/config files
- **404 Analysis**: Distinguishes scanning vs. legitimate missing pages
- **Burst Behavior**: Rapid successive requests indicating automation
- **Response Time Patterns**: Unusual timing that may indicate probing
### Examples of Detected Patterns
```python
# These patterns trigger AI analysis:
GET /wp-admin/ # WordPress scanning
GET /phpmyadmin/ # Database admin access attempts
GET /.env # Environment file probing
GET /config.php # Configuration file access
GET /backup.sql # Backup file attempts
GET /?cmd=whoami # Command injection attempts
GET /test?union=select # SQL injection patterns
```
### Intelligent Blocking Logic
The AI doesn't block on single suspicious requests. Instead, it analyzes:
- **Recent behavior** (last 5 minutes)
- **Total vs. scanning 404s**
- **Average keyword hits**
- **Burst patterns**
- **Request volume**
Only blocks when multiple indicators suggest malicious intent, preventing false positives for legitimate users.
### AI Dependencies Troubleshooting
#### **Checking AI Dependencies**
```bash
# Check if AI dependencies are available
python -c "
try:
import numpy, sklearn
print('✅ AI dependencies available')
except ImportError as e:
print(f'❌ Missing: {e}')
print('Install with: pip install aiwaf-flask[ai]')
"
```
## 📚 Training the AI Model
AIWAF Flask includes a comprehensive training system that replicates Django's functionality, supporting multiple log formats and intelligent learning from thousands of log entries.
### Basic Training
```python
from aiwaf_flask.trainer import train_from_logs
# Train with your Flask app
train_from_logs(app)
# Or disable AI and use keyword learning only
train_from_logs(app, disable_ai=True)
```
### Standalone Training Script
Use the included training script for easy command-line training:
```bash
# Train with AI model (requires AI dependencies)
python train_aiwaf.py --log-dir /path/to/logs
# Train with keyword learning only (no AI dependencies needed)
python train_aiwaf.py --disable-ai --log-dir /path/to/logs
# Verbose output
python train_aiwaf.py --verbose
```
### CLI Training Command
The easiest way to train is using the built-in CLI command:
```bash
# Simple training with AI (auto-detects log format)
aiwaf train
# Train with keyword learning only
aiwaf train --disable-ai
# Train from custom log directory with verbose output
aiwaf train --log-dir /path/to/logs --verbose
# Show training options
aiwaf train --help
```
### Supported Log Formats
The trainer automatically detects and processes multiple log formats:
1. **Apache/Nginx Access Logs** - Standard combined log format
2. **CSV Logs** - With columns: timestamp, ip, method, path, status_code, user_agent, etc.
3. **JSON/JSONL Logs** - Structured log files with request data
### Training Features
The comprehensive training system includes:
- **Smart Keyword Learning**: Learns suspicious patterns from 404s and errors
- **Context-Aware Filtering**: Distinguishes legitimate vs malicious keywords
- **Flask Route Analysis**: Extracts legitimate keywords from your app's routes
- **AI Anomaly Detection**: Machine learning model for behavior analysis
- **Intelligent IP Blocking**: Blocks based on combined indicators
- **Exemption Handling**: Respects IP exemptions and allowed keywords
### Log Processing
The trainer can handle large datasets efficiently:
```python
# Process 1000+ log entries with intelligent filtering
train_from_logs(app)
```
Training analyzes:
- Request patterns and frequencies
- 404 error clustering
- Response time anomalies
- Burst activity detection
- Keyword context analysis
- Path existence validation
### Configuration
Customize training behavior in your Flask app:
```python
app.config.update({
'AIWAF_LOG_DIR': 'logs/',
'AIWAF_DYNAMIC_TOP_N': 15, # Top keywords to learn
'AIWAF_AI_CONTAMINATION': 0.05, # AI sensitivity
'AIWAF_EXEMPT_KEYWORDS': ['api', 'health'],
'AIWAF_ALLOWED_PATH_KEYWORDS': ['dashboard', 'profile']
})
```
### Training Output Example
```
🚀 Starting AIWAF Flask enhanced training...
📁 Reading logs from: access.log
📊 Total log lines found: 1247
📋 Parsing 1247 log entries...
✅ Successfully parsed 1205 log entries
🚫 Blocked 3 IPs for excessive 404 errors
🤖 Training AI anomaly detection model...
💾 Model saved: aiwaf_flask/resources/model.pkl
📊 Trained on 1205 samples with scikit-learn v1.3.0
🔍 Detected 7 potentially anomalous IPs
🚫 203.0.113.10: Blocked for suspicious behavior
📚 Learning suspicious keywords from logs...
============================================================
🤖 AIWAF FLASK ENHANCED TRAINING COMPLETE
============================================================
📊 Training Data: 1205 log entries processed
🤖 AI Model: Trained with 7 features
🚫 AI Blocked IPs: 1 suspicious IPs blocked
📚 Keywords: 5 new suspicious keywords learned
📝 Keywords: ['xmlrpc', 'wp-config', 'phpmyadmin', 'backup', 'shell']
🛡️ Exemptions: 2 IPs protected from blocking
🚫 404 Blocking: 3 IPs blocked for excessive 404s
✅ Enhanced AI protection now active with context-aware filtering!
============================================================
```
#### **Checking AI Dependencies**
```python
# Check if AI dependencies are available
def check_ai_dependencies():
try:
import numpy as np
import sklearn
print(f"✅ AI Ready: NumPy {np.__version__}, Scikit-learn {sklearn.__version__}")
return True
except ImportError as e:
print(f"❌ AI Missing: {e}")
print("Install with: pip install aiwaf-flask[ai]")
return False
# Use in your application
if check_ai_dependencies():
# Enable AI middleware
aiwaf = AIWAF(app, middlewares=['ai_anomaly', 'rate_limit', 'logging'])
else:
# Fallback to non-AI middlewares
aiwaf = AIWAF(app, middlewares=['rate_limit', 'ip_keyword_block', 'logging'])
```
#### **Installation Options**
| Installation | Command | Features |
|--------------|---------|----------|
| **Basic** | `pip install aiwaf-flask` | Core security (no AI) |
| **AI Enabled** | `pip install aiwaf-flask[ai]` | Full AI capabilities |
| **Development** | `pip install aiwaf-flask[all]` | AI + testing tools |
| **Manual AI** | `pip install numpy scikit-learn` | Add AI to existing install |
#### **Common Issues**
- **"NumPy not available"** → Install with `pip install aiwaf-flask[ai]`
- **"AI anomaly detection disabled"** → Normal when NumPy is missing
- **Slow startup** → Consider disabling AI: `disable_middlewares=['ai_anomaly']`
- **Memory usage** → AI uses ~50MB for ML models, disable if needed
## Web Server Logging
AIWAF Flask includes comprehensive logging that generates **standard web server logs** compatible with tools like Gunicorn, Nginx, and Apache log analyzers.
### Log Formats
#### **Combined Log Format (Default)**
```
127.0.0.1 - - [14/Sep/2025:15:02:41 +0000] "GET /api/data HTTP/1.1" 200 1234 "http://example.com" "Mozilla/5.0" 50ms - "-"
203.0.113.10 - - [14/Sep/2025:15:02:42 +0000] "GET /admin.php HTTP/1.1" 403 0 "-" "BadBot/1.0" 10ms BLOCKED "Malicious keyword: .php"
```
#### **CSV Format (Easy Analysis)**
```csv
timestamp,ip,method,path,status_code,response_time_ms,blocked,block_reason
2025-09-14T15:02:41,127.0.0.1,GET,/api/data,200,50,False,
2025-09-14T15:02:42,203.0.113.10,GET,/admin.php,403,10,True,Malicious keyword: .php
```
#### **JSON Format (Structured)**
```json
{"timestamp": "2025-09-14T15:02:41", "ip": "127.0.0.1", "method": "GET", "path": "/api/data", "status_code": 200, "blocked": false}
{"timestamp": "2025-09-14T15:02:42", "ip": "203.0.113.10", "method": "GET", "path": "/admin.php", "status_code": 403, "blocked": true, "block_reason": "Malicious keyword: .php"}
```
### Log Configuration
```python
app.config['AIWAF_ENABLE_LOGGING'] = True # Enable logging
app.config['AIWAF_LOG_DIR'] = 'logs' # Log directory
app.config['AIWAF_LOG_FORMAT'] = 'combined' # Format: combined, common, csv, json
```
### Generated Log Files
- **`access.log`** - All HTTP requests (main access log)
- **`error.log`** - HTTP errors (4xx, 5xx status codes)
- **`aiwaf.log`** - AIWAF security events and blocks
### Log Analysis
```bash
# Analyze logs with detailed statistics
aiwaf logs --log-dir logs --format combined
# Sample output:
# 📊 AIWAF Access Log Analysis
# Total Requests: 1,250
# Blocked Requests: 45 (3.6%)
# Average Response Time: 85ms
# Top IPs, paths, block reasons, hourly patterns, etc.
```
## Usage Examples
Your routes are automatically protected:
```python
@app.route('/')
def home():
return render_template('home.html') # Protected by AIWAF
@app.route('/api/data')
def api_data():
return jsonify({'data': 'protected'}) # Rate limited & validated
```
## Managing Protection Lists
```python
from aiwaf_flask.storage import add_ip_whitelist, add_ip_blacklist, add_keyword
# Add IPs to whitelist (bypass all protection)
add_ip_whitelist('192.168.1.100')
# Add IPs to blacklist (block completely)
add_ip_blacklist('10.0.0.1', reason='Suspicious activity')
# Add malicious keywords to block
add_keyword('wp-admin')
add_keyword('.env')
```
## CSV Files Structure
When using CSV storage, AIWAF creates these files in your data directory:
- `whitelist.csv` - Whitelisted IP addresses
- `blacklist.csv` - Blacklisted IP addresses with reasons
- `keywords.csv` - Blocked keywords
Example `blacklist.csv`:
```csv
ip,reason,added_date
10.0.0.1,Suspicious activity,2025-09-14T10:30:00
192.168.1.50,Rate limit exceeded,2025-09-14T11:15:00
```
## Command Line Management
AIWAF Flask includes a powerful CLI tool for managing IP exemptions, blacklists, and blocked keywords from the command line. After installation, the CLI is available globally as `aiwaf` or `aiwaf-console`.
### Installation & CLI Access
```bash
# Install AIWAF Flask
pip install aiwaf-flask
# CLI is now available globally - no need to be in project directory!
aiwaf --help
aiwaf-console --help # Alternative command name
# If developing locally:
pip install -e . # Makes CLI available globally
```
### Basic Usage
```bash
# Show help (works from any directory after installation)
aiwaf --help
# Show current statistics
aiwaf stats
# List all data
aiwaf list all
```
### IP Management
```bash
# Add IP to whitelist
aiwaf add whitelist 192.168.1.100
# Add IP to blacklist with reason
aiwaf add blacklist 10.0.0.5 --reason "Brute force attack"
# Remove IP from whitelist
aiwaf remove whitelist 192.168.1.100
# Remove IP from blacklist
aiwaf remove blacklist 10.0.0.5
# List specific data types
aiwaf list whitelist
aiwaf list blacklist
```
### Keyword Management
```bash
# Add blocked keyword
aiwaf add keyword "sql injection"
aiwaf add keyword "script"
# List blocked keywords
aiwaf list keywords
```
### Configuration Backup/Restore
```bash
# Export current configuration
aiwaf export backup.json
# Import configuration from backup
aiwaf import backup.json
```
### Log Analysis
```bash
# Analyze logs with detailed statistics
aiwaf logs --log-dir logs --format combined
```
### AI Model Training
```bash
# Train AI model from access logs (auto-detects log format)
aiwaf train
# Train with keyword learning only (no AI dependencies)
aiwaf train --disable-ai
# Train from custom log directory with verbose output
aiwaf train --log-dir /path/to/logs --verbose
# Train with specific options
aiwaf train --log-dir logs --disable-ai --verbose
```
### Custom Data Directory
```bash
# Use custom data directory
aiwaf --data-dir /path/to/custom/aiwaf_data stats
```
### Example CLI Session
```bash
# Check current status (works from any directory!)
aiwaf stats
# Add some IPs to whitelist
aiwaf add whitelist 192.168.1.100
aiwaf add whitelist 10.0.0.50
# Block a malicious IP
aiwaf add blacklist 203.0.113.10 --reason "SQL injection attempts"
# Add dangerous keywords
aiwaf add keyword "union select"
aiwaf add keyword "drop table"
# Review all settings
aiwaf list all
# Create backup
aiwaf export production_backup.json
```
### Programmatic Management
You can also use the CLI functionality in your Python code:
```python
from aiwaf_flask.cli import AIWAFManager
# Initialize manager
manager = AIWAFManager()
# Add IPs programmatically
manager.add_to_whitelist("192.168.1.100")
manager.add_to_blacklist("10.0.0.5", "Suspicious activity")
# Get current lists
whitelist = manager.list_whitelist()
blacklist = manager.list_blacklist()
keywords = manager.list_keywords()
# Export configuration
manager.export_config("backup.json")
```
## CLI Features & Real-World Examples
AIWAF Flask includes powerful command-line tools for production management. The CLI works independently without requiring Flask to be installed, making it perfect for system administration and automation.
### Quick Setup
```bash
# Show CLI status and help
python aiwaf_setup.py
# Install Flask if needed (optional for CLI-only usage)
python aiwaf_setup.py install-flask
# Run interactive demo
python aiwaf_setup.py demo
```
### Production Management Examples
#### **Emergency IP Blocking**
```bash
# Block attacking IPs immediately (works from any directory!)
aiwaf add blacklist 203.0.113.10 --reason "SQL injection attack detected"
aiwaf add blacklist 198.51.100.5 --reason "Brute force login attempts"
aiwaf add blacklist 10.0.0.1 --reason "Suspicious port scanning"
# Verify blocks are active
aiwaf list blacklist
```
#### **Whitelist Management**
```bash
# Add trusted networks
aiwaf add whitelist 192.168.1.0/24
aiwaf add whitelist 10.0.0.0/8
aiwaf add whitelist 172.16.0.0/12
# Add specific trusted IPs
aiwaf add whitelist 203.0.113.100 # Office IP
aiwaf add whitelist 198.51.100.200 # API partner
```
#### **Security Keywords**
```bash
# Block common attack patterns
aiwaf add keyword "union select"
aiwaf add keyword "drop table"
aiwaf add keyword "<script>"
aiwaf add keyword "javascript:"
aiwaf add keyword "eval("
aiwaf add keyword "base64_decode"
# Review blocked keywords
aiwaf list keywords
```
#### **Daily Operations**
```bash
# Morning security check
aiwaf stats
# Review recent blocks
aiwaf list blacklist
# Create daily backup
aiwaf export "backup-$(date +%Y%m%d).json"
# Clean up test entries
aiwaf remove whitelist 192.168.1.99
aiwaf remove blacklist 10.0.0.99
```
### Automation Scripts
#### **Security Incident Response**
```bash
#!/bin/bash
# incident_response.sh - Block multiple IPs from security incident
MALICIOUS_IPS=(
"203.0.113.10"
"198.51.100.5"
"192.0.2.15"
"198.51.100.25"
)
for ip in "${MALICIOUS_IPS[@]}"; do
aiwaf add blacklist "$ip" --reason "Security incident #2025-001"
done
# Create incident backup
aiwaf export "incident-2025-001-backup.json"
echo "Blocked ${#MALICIOUS_IPS[@]} IPs from security incident"
```
#### **Configuration Deployment**
```bash
#!/bin/bash
# deploy_config.sh - Deploy AIWAF configuration to production
# Backup current config
aiwaf export "backup-before-deploy-$(date +%Y%m%d-%H%M).json"
# Deploy new configuration
aiwaf import "production-config.json"
# Verify deployment
aiwaf stats
aiwaf list all
```
### Real CLI Session Output
```bash
$ aiwaf stats
📁 Using CSV storage: aiwaf_data
📊 AIWAF Statistics
==================================================
Whitelisted IPs: 5
Blacklisted IPs: 3
Blocked Keywords: 8
Storage Mode: CSV
Data Directory: aiwaf_data
$ aiwaf list all
📁 Using CSV storage: aiwaf_data
🟢 Whitelisted IPs (5):
• 192.168.1.100
• 192.168.1.200
• 10.0.0.50
• 203.0.113.100
• 198.51.100.200
🔴 Blacklisted IPs (3):
• 203.0.113.10 - SQL injection attack detected (2025-09-14T09:15:30)
• 198.51.100.5 - Brute force login attempts (2025-09-14T10:22:15)
• 10.0.0.1 - Suspicious port scanning (2025-09-14T11:45:22)
🚫 Blocked Keywords (8):
• union select
• drop table
• <script>
• javascript:
• eval(
• base64_decode
• onload=
• document.cookie
$ aiwaf export production-backup.json
📁 Using CSV storage: aiwaf_data
✅ Configuration exported to production-backup.json
```
### Configuration Format
The exported JSON configuration contains all security settings:
```json
{
"whitelist": [
"192.168.1.100",
"192.168.1.200",
"10.0.0.50"
],
"blacklist": {
"203.0.113.10": {
"timestamp": "2025-09-14T09:15:30.123456",
"reason": "SQL injection attack detected"
},
"198.51.100.5": {
"timestamp": "2025-09-14T10:22:15.789012",
"reason": "Brute force login attempts"
}
},
"keywords": [
"union select",
"drop table",
"<script>",
"eval("
],
"exported_at": "2025-09-14T14:30:00.000000",
"storage_mode": "CSV"
}
```
### Integration with Monitoring
```bash
# Add to crontab for daily reports
0 9 * * * /path/to/aiwaf stats >> /var/log/aiwaf-daily.log
# Add to monitoring script
aiwaf stats | grep -E "(Blacklisted|Keywords)" | \
awk '{if($3 > 100) print "ALERT: High security blocks detected"}'
```
## Production Deployment
```python
# config.py
import os
class ProductionConfig:
# Use PostgreSQL in production
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
# Stricter limits for production
AIWAF_RATE_MAX = 50
AIWAF_RATE_FLOOD = 100
AIWAF_MIN_FORM_TIME = 3.0
# app.py
app.config.from_object(ProductionConfig)
```
## Dependencies Summary
### Core Dependencies (Always Required)
- **Flask** (`>=2.0.0`) - Web framework
- **Flask-SQLAlchemy** (`>=3.0.0`) - Database ORM (optional for CSV mode)
### AI Dependencies (Optional for Enhanced Security)
- **NumPy** (`>=1.20.0`) - Numerical computations for ML features
- **Scikit-learn** (`>=1.0.0`) - Machine learning model training and prediction
### Installation Matrix
| Feature Set | Command | Dependencies Installed |
|-------------|---------|----------------------|
| **Basic Security** | `pip install aiwaf-flask` | Flask, Flask-SQLAlchemy |
| **AI Enhanced** | `pip install aiwaf-flask[ai]` | Basic + NumPy, Scikit-learn |
| **Development** | `pip install aiwaf-flask[all]` | AI + pytest, coverage tools |
### Middleware Dependency Requirements
| Middleware | Dependencies | Notes |
|------------|-------------|-------|
| `ip_keyword_block` | Core only | Always available |
| `rate_limit` | Core only | Always available |
| `header_validation` | Core only | Always available |
| `honeypot` | Core only | Always available |
| `uuid_tamper` | Core only | Always available |
| `logging` | Core only | Always available |
| **`ai_anomaly`** | **NumPy + Scikit-learn** | **Requires AI dependencies** |
## License
MIT
Raw data
{
"_id": null,
"home_page": "https://github.com/aayushgauba/aiwaf_flask",
"name": "aiwaf-flask",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": "Aayush Gauba <gauba.aayush@gmail.com>",
"keywords": "flask, security, firewall, web, protection, middleware, rate-limiting, ip-blocking, ddos, waf",
"author": "Aayush Gauba",
"author_email": "Aayush Gauba <gauba.aayush@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/6d/35/0efa9e52eb59c3c24a449a203bf8e788e21d0638085622a6b62bde39fe6b/aiwaf_flask-0.1.7b0.tar.gz",
"platform": null,
"description": "# AIWAF Flask\n\nAIWAF (AI Web Application Firewall) for Flask provides advanced, self-learning protection for your Flask web applications. It supports IP/keyword blocking, rate limiting, honeypot timing, header validation, anomaly detection, and UUID tampering, with flexible storage options: **database**, **CSV files**, or **in-memory**.\n\n## Features\n- IP and keyword blocking\n- Rate limiting with burst detection\n- Honeypot timing protection\n- Header validation\n- **AI-powered anomaly detection** - Machine learning to detect suspicious patterns\n- UUID tampering detection\n- **Path exemptions** - Prevent false positives for legitimate resources\n- **Flexible storage**: Database, CSV files, or in-memory\n- Zero-dependency protection (works without database)\n\n## Function Names\n\nAIWAF Flask provides two function names for registering middleware:\n\n- **`register_aiwaf_middlewares(app)`** - Current recommended name\n- **`register_aiwaf_protection(app)`** - Backward compatibility alias\n\nBoth functions work identically and provide the same protection features.\n\n```python\nfrom flask import Flask\nfrom aiwaf_flask import register_aiwaf_middlewares\n# OR: from aiwaf_flask import register_aiwaf_protection\n\napp = Flask(__name__)\napp.config['AIWAF_USE_CSV'] = True\n\n# Both of these work the same way:\nregister_aiwaf_middlewares(app)\n# register_aiwaf_protection(app) # Alternative\n```\n\n## Installation\n\n```bash\n# Basic installation (without AI features)\npip install aiwaf-flask\n\n# With AI anomaly detection features\npip install aiwaf-flask[ai]\n\n# Full installation (AI + development tools)\npip install aiwaf-flask[all]\n```\n\n### AI Dependencies\n\nThe AI anomaly detection middleware requires additional dependencies:\n- **NumPy** (`>=1.20.0`) - For numerical computations and feature analysis\n- **Scikit-learn** (`>=1.0.0`) - For machine learning model training and prediction\n\n```bash\n# Install AI dependencies separately if needed\npip install numpy>=1.20.0 scikit-learn>=1.0.0\n```\n\n## Quick Start\n\n### Basic Setup (All Middlewares)\n\n```python\nfrom flask import Flask\nfrom aiwaf_flask import AIWAF\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your-secret-key'\n\n# Enable all AIWAF protections (default behavior)\naiwaf = AIWAF(app) # \u2190 Automatically enables ALL 7 middlewares\n\n@app.route('/')\ndef home():\n return 'Hello, AIWAF!'\n\nif __name__ == '__main__':\n app.run(debug=True)\n```\n\n### Default Behavior\n\n**When you don't specify any middlewares, AIWAF automatically enables ALL available middlewares:**\n\n```python\n# These are all equivalent - they all enable ALL middlewares:\naiwaf = AIWAF(app) # \u2190 Default: enables all 7 middlewares\naiwaf = AIWAF(app, middlewares=None) # \u2190 Same as above\naiwaf = AIWAF() # \u2190 Then call aiwaf.init_app(app)\naiwaf.init_app(app) # \u2190 Also enables all middlewares\n```\n\n### Customized Middleware Selection\n\nIf you want **specific control**, you can selectively enable or disable middlewares:\n\n```python\nfrom flask import Flask\nfrom aiwaf_flask import AIWAF\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your-secret-key'\n\n# Option 1: Enable ONLY specific middlewares\naiwaf = AIWAF(app, middlewares=[\n 'rate_limit', # Rate limiting protection\n 'header_validation', # HTTP header validation \n 'ai_anomaly', # AI-powered anomaly detection\n 'logging' # Request/response logging\n])\n\n# Option 2: Enable ALL middlewares EXCEPT specified ones\naiwaf = AIWAF(app, disable_middlewares=[\n 'honeypot', # Disable honeypot timing\n 'uuid_tamper' # Disable UUID tampering protection\n])\n# \u2191 Enables 5 out of 7 middlewares (all except the 2 disabled)\n\n# Option 3: Minimal security setup (essentials only)\naiwaf = AIWAF(app, middlewares=[\n 'ip_keyword_block', # Core IP/keyword blocking\n 'rate_limit', # Rate limiting\n 'logging' # Activity logging\n])\n# \u2191 Enables only 3 specific middlewares\n```\n\n### Available Middlewares\n\n| Middleware | Name | Description |\n|------------|------|-------------|\n| **IP & Keyword Block** | `ip_keyword_block` | Blocks malicious IPs and detects attack keywords |\n| **Rate Limiting** | `rate_limit` | Protects against brute force and DDoS attacks |\n| **Honeypot Timing** | `honeypot` | Detects automated form submissions |\n| **Header Validation** | `header_validation` | Validates HTTP headers for security threats |\n| **AI Anomaly Detection** | `ai_anomaly` | Machine learning-based pattern analysis |\n| **UUID Tampering** | `uuid_tamper` | Protects against UUID manipulation attacks |\n| **Request Logging** | `logging` | Comprehensive request/response logging |\n\n### Initialization Patterns\n\n| Pattern | Result | Use Case |\n|---------|--------|----------|\n| `AIWAF(app)` | **Enables ALL 7 middlewares** | Default - maximum protection |\n| `AIWAF(app, middlewares=[...])` | Enables only specified | Custom selection |\n| `AIWAF(app, disable_middlewares=[...])` | Enables all except specified | Mostly default with exceptions |\n| `AIWAF()` then `init_app(app)` | **Enables ALL 7 middlewares** | Factory pattern |\n\n### Middleware Management\n\n```python\n# Check which middlewares are enabled\nenabled = aiwaf.get_enabled_middlewares()\nprint(f\"Active protections: {enabled}\")\n\n# Check if specific middleware is enabled\nif aiwaf.is_middleware_enabled('ai_anomaly'):\n print(\"AI protection is active\")\n\n# Get middleware instance for advanced configuration\nrate_limiter = aiwaf.get_middleware_instance('rate_limit')\n\n# List all available middlewares\navailable = AIWAF.list_available_middlewares()\nprint(f\"Available: {available}\")\n```\n\n## Legacy Compatibility\n\nThe old registration method still works with new customization options:\n\n```python\nfrom aiwaf_flask import register_aiwaf_middlewares\n\n# Legacy method with new features\nregister_aiwaf_middlewares(\n app, \n middlewares=['rate_limit', 'ai_anomaly'],\n disable_middlewares=['honeypot']\n)\n```\n\n## Storage Options\n\n### 1. **CSV Storage (Recommended for small apps)**\n```python\nfrom flask import Flask\nfrom aiwaf_flask import AIWAF\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your-secret-key'\n\n# CSV Configuration (no database needed!)\napp.config['AIWAF_USE_CSV'] = True\napp.config['AIWAF_DATA_DIR'] = 'aiwaf_data' # Optional: custom directory\n\n# AIWAF Settings\napp.config['AIWAF_RATE_WINDOW'] = 60\napp.config['AIWAF_RATE_MAX'] = 100\n\n# Initialize with custom middleware selection\naiwaf = AIWAF(app, middlewares=['rate_limit', 'ip_keyword_block', 'logging'])\n```\n\n### 2. **Database Storage (Recommended for production)**\n```python\nfrom flask import Flask\nfrom aiwaf_flask.db_models import db\nfrom aiwaf_flask import AIWAF\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'your-secret-key'\n\n# Database Configuration\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///aiwaf.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['AIWAF_USE_CSV'] = False # Force database usage\n\n# AIWAF Settings\napp.config['AIWAF_RATE_WINDOW'] = 60\napp.config['AIWAF_RATE_MAX'] = 100\n\n# Initialize with all middlewares\naiwaf = AIWAF(app, use_database=True)\n```\napp.config['AIWAF_RATE_MAX'] = 100\n\ndb.init_app(app)\nwith app.app_context():\n db.create_all()\n\nregister_aiwaf_middlewares(app)\n```\n\n### 3. **In-Memory Storage (For testing)**\n```python\nfrom flask import Flask\nfrom aiwaf_flask import register_aiwaf_middlewares\n\napp = Flask(__name__)\n\n# Force in-memory storage\napp.config['AIWAF_USE_CSV'] = False\n\nregister_aiwaf_middlewares(app, use_database=False)\n```\n\n## Middleware Selection Guide\n\n### \ud83d\udee1\ufe0f **Minimal Security (Essential Protection)**\nBest for: Small applications, development environments, minimal overhead\n\n```python\naiwaf = AIWAF(app, middlewares=[\n 'ip_keyword_block', # Core attack prevention\n 'rate_limit', # Basic DDoS protection \n 'logging' # Security monitoring\n])\n```\n\n### \ud83d\ude80 **Standard Security (Recommended)**\nBest for: Most production applications, balanced protection\n\n```python\naiwaf = AIWAF(app, middlewares=[\n 'ip_keyword_block', # Core attack prevention\n 'rate_limit', # DDoS protection\n 'header_validation', # HTTP security\n 'ai_anomaly', # Smart threat detection\n 'logging' # Security monitoring\n])\n```\n\n### \ud83d\udd25 **Maximum Security (Full Protection)**\nBest for: High-security applications, sensitive data handling\n\n```python\n# Enable all middlewares (default)\naiwaf = AIWAF(app)\n```\n\n### \ud83e\udd16 **AI-Focused Security (Modern Protection)**\nBest for: Applications with complex user patterns, advanced threat detection\n\n```python\naiwaf = AIWAF(app, middlewares=[\n 'ai_anomaly', # Machine learning detection\n 'rate_limit', # Intelligent rate limiting\n 'header_validation', # Advanced header analysis\n 'logging' # ML-enhanced logging\n])\n```\n\n### \ud83c\udfaf **Custom Security (Selective Protection)**\nBest for: Specific requirements, performance optimization\n\n```python\n# Disable specific middlewares you don't need\naiwaf = AIWAF(app, disable_middlewares=[\n 'honeypot', # If no forms in your app\n 'uuid_tamper' # If not using UUIDs\n])\n```\n\n### Performance Impact Guide\n\n| Middleware | Performance Impact | Use Case |\n|------------|-------------------|----------|\n| `ip_keyword_block` | **Low** | Essential for all apps |\n| `rate_limit` | **Low** | Essential for public apps |\n| `logging` | **Medium** | Important for monitoring |\n| `header_validation` | **Low** | Good for web APIs |\n| `ai_anomaly` | **Medium** | Advanced threat detection |\n| `honeypot` | **Low** | Only useful with forms |\n| `uuid_tamper` | **Very Low** | Only if using UUIDs |\n\n## Configuration Options\n\n```python\n# Rate Limiting\napp.config['AIWAF_RATE_WINDOW'] = 60 # Time window in seconds\napp.config['AIWAF_RATE_MAX'] = 100 # Max requests per window\napp.config['AIWAF_RATE_FLOOD'] = 200 # Auto-block threshold\n\n# Honeypot Protection\napp.config['AIWAF_MIN_FORM_TIME'] = 2.0 # Minimum form submission time\n\n# AI Anomaly Detection\napp.config['AIWAF_WINDOW_SECONDS'] = 60 # Analysis window for behavior patterns\napp.config['AIWAF_DYNAMIC_TOP_N'] = 10 # Top N patterns to track\napp.config['AIWAF_MODEL_PATH'] = 'aiwaf_flask/resources/model.pkl' # ML model path\n\n# CSV Storage (if enabled)\napp.config['AIWAF_USE_CSV'] = True # Enable CSV storage\napp.config['AIWAF_DATA_DIR'] = 'aiwaf_data' # CSV files directory\n\n# Logging Configuration\napp.config['AIWAF_ENABLE_LOGGING'] = True # Enable request logging\napp.config['AIWAF_LOG_DIR'] = 'aiwaf_logs' # Log files directory\napp.config['AIWAF_LOG_FORMAT'] = 'combined' # Log format: combined, common, csv, json\n\n# Path Exemptions\napp.config['AIWAF_EXEMPT_PATHS'] = { # Paths exempt from AIWAF protection\n '/favicon.ico',\n '/robots.txt', \n '*.css', # Wildcard patterns\n '/static/', # Directory patterns\n}\n```\n\n## Path Exemptions (Prevent False Positives)\n\nAIWAF supports **path-based exemptions** to prevent false positives for legitimate resources that might return 404s or should not be subject to security filtering.\n\n### Default Exempt Paths\n\nAIWAF includes sensible defaults for common legitimate resources:\n\n```python\n# SEO and crawlers\n'/favicon.ico', '/robots.txt', '/sitemap.xml', '/ads.txt'\n\n# Apple and mobile devices \n'/apple-touch-icon.png', '/manifest.json', '/browserconfig.xml'\n\n# Health checks and monitoring\n'/health', '/healthcheck', '/ping', '/status'\n\n# Well-known URIs (SSL certificates, security policies)\n'/.well-known/'\n\n# Static file extensions (wildcards)\n'*.css', '*.js', '*.png', '*.jpg', '*.ico', '*.woff2'\n\n# Static directories\n'/static/', '/assets/', '/css/', '/js/', '/images/', '/fonts/'\n```\n\n### Custom Path Exemptions\n\nConfigure custom exempt paths for your application:\n\n```python\n# Override defaults with custom paths\napp.config['AIWAF_EXEMPT_PATHS'] = {\n # Essential SEO files\n '/favicon.ico',\n '/robots.txt',\n '/sitemap.xml',\n \n # Health monitoring \n '/health',\n '/api/health',\n \n # Public APIs\n '/api/public/',\n '/webhook/github',\n \n # Static assets\n '*.css', '*.js', '*.png', '*.pdf',\n '/static/', '/assets/',\n \n # Custom application paths\n '/special-public-endpoint',\n '/custom-health-check',\n}\n```\n\n### Pattern Types\n\n- **Exact paths**: `/favicon.ico` (matches exactly)\n- **Wildcard patterns**: `*.css` (matches any .css file) \n- **Directory patterns**: `/static/` (matches anything under /static/)\n- **Case insensitive**: `/FAVICON.ICO` also matches\n\n### Why Use Path Exemptions?\n\n- **Prevent SEO issues**: Search engines can safely crawl `/robots.txt`, `/sitemap.xml`\n- **Avoid blocking legitimate 404s**: `favicon.ico` requests won't trigger blocking\n- **Load balancer compatibility**: Health checks always work (`/health`, `/ping`)\n- **Static asset safety**: CSS/JS/images load without interference\n- **SSL certificate support**: `/.well-known/` URIs for ACME challenges\n\n## AI-Powered Anomaly Detection\n\nAIWAF Flask includes advanced **machine learning-based anomaly detection** that analyzes request patterns and automatically identifies malicious behavior.\n\n### How It Works\n\nThe AI anomaly detection middleware:\n\n1. **Analyzes Request Patterns**: Tracks path length, keyword hits, response times, status codes, and burst patterns\n2. **Uses Machine Learning**: Employs a trained model to detect anomalous behavior (requires NumPy)\n3. **Intelligent Blocking**: Only blocks after analyzing multiple indicators to avoid false positives\n4. **Dynamic Learning**: Learns new malicious keywords from scanning attempts\n\n### Key Features\n\n- **Multi-factor Analysis**: Combines ML predictions with behavioral analysis\n- **Smart Thresholds**: Distinguishes between legitimate 404s and malicious scanning\n- **Contextual Learning**: Only learns keywords from confirmed malicious contexts\n- **Pattern Recognition**: Detects common attack patterns (SQLi, XSS, directory traversal)\n\n### Configuration\n\n```python\n# AI Anomaly Detection Settings\napp.config['AIWAF_WINDOW_SECONDS'] = 60 # Analysis window (seconds)\napp.config['AIWAF_DYNAMIC_TOP_N'] = 10 # Top patterns to track \napp.config['AIWAF_MODEL_PATH'] = 'path/to/model.pkl' # ML model location\n\n# Install AI dependencies for full functionality\n# pip install aiwaf-flask[ai]\n# or: pip install numpy>=1.20.0 scikit-learn>=1.0.0\n```\n\n**Note**: AI anomaly detection requires NumPy and Scikit-learn. Install with `pip install aiwaf-flask[ai]` for full ML capabilities.\n\n### Detection Criteria\n\nThe AI system analyzes multiple factors before blocking:\n\n- **Keyword Density**: Number of malicious keywords in requests\n- **Scanning Patterns**: Attempts to access non-existent admin/config files\n- **404 Analysis**: Distinguishes scanning vs. legitimate missing pages\n- **Burst Behavior**: Rapid successive requests indicating automation\n- **Response Time Patterns**: Unusual timing that may indicate probing\n\n### Examples of Detected Patterns\n\n```python\n# These patterns trigger AI analysis:\nGET /wp-admin/ # WordPress scanning\nGET /phpmyadmin/ # Database admin access attempts\nGET /.env # Environment file probing\nGET /config.php # Configuration file access\nGET /backup.sql # Backup file attempts\nGET /?cmd=whoami # Command injection attempts\nGET /test?union=select # SQL injection patterns\n```\n\n### Intelligent Blocking Logic\n\nThe AI doesn't block on single suspicious requests. Instead, it analyzes:\n\n- **Recent behavior** (last 5 minutes)\n- **Total vs. scanning 404s**\n- **Average keyword hits**\n- **Burst patterns**\n- **Request volume**\n\nOnly blocks when multiple indicators suggest malicious intent, preventing false positives for legitimate users.\n\n### AI Dependencies Troubleshooting\n\n#### **Checking AI Dependencies**\n\n```bash\n# Check if AI dependencies are available\npython -c \"\ntry:\n import numpy, sklearn\n print('\u2705 AI dependencies available')\nexcept ImportError as e:\n print(f'\u274c Missing: {e}')\n print('Install with: pip install aiwaf-flask[ai]')\n\"\n```\n\n## \ud83d\udcda Training the AI Model\n\nAIWAF Flask includes a comprehensive training system that replicates Django's functionality, supporting multiple log formats and intelligent learning from thousands of log entries.\n\n### Basic Training\n\n```python\nfrom aiwaf_flask.trainer import train_from_logs\n\n# Train with your Flask app\ntrain_from_logs(app)\n\n# Or disable AI and use keyword learning only\ntrain_from_logs(app, disable_ai=True)\n```\n\n### Standalone Training Script\n\nUse the included training script for easy command-line training:\n\n```bash\n# Train with AI model (requires AI dependencies)\npython train_aiwaf.py --log-dir /path/to/logs\n\n# Train with keyword learning only (no AI dependencies needed)\npython train_aiwaf.py --disable-ai --log-dir /path/to/logs\n\n# Verbose output\npython train_aiwaf.py --verbose\n```\n\n### CLI Training Command\n\nThe easiest way to train is using the built-in CLI command:\n\n```bash\n# Simple training with AI (auto-detects log format)\naiwaf train\n\n# Train with keyword learning only\naiwaf train --disable-ai\n\n# Train from custom log directory with verbose output\naiwaf train --log-dir /path/to/logs --verbose\n\n# Show training options\naiwaf train --help\n```\n\n### Supported Log Formats\n\nThe trainer automatically detects and processes multiple log formats:\n\n1. **Apache/Nginx Access Logs** - Standard combined log format\n2. **CSV Logs** - With columns: timestamp, ip, method, path, status_code, user_agent, etc.\n3. **JSON/JSONL Logs** - Structured log files with request data\n\n### Training Features\n\nThe comprehensive training system includes:\n\n- **Smart Keyword Learning**: Learns suspicious patterns from 404s and errors\n- **Context-Aware Filtering**: Distinguishes legitimate vs malicious keywords\n- **Flask Route Analysis**: Extracts legitimate keywords from your app's routes\n- **AI Anomaly Detection**: Machine learning model for behavior analysis\n- **Intelligent IP Blocking**: Blocks based on combined indicators\n- **Exemption Handling**: Respects IP exemptions and allowed keywords\n\n### Log Processing\n\nThe trainer can handle large datasets efficiently:\n\n```python\n# Process 1000+ log entries with intelligent filtering\ntrain_from_logs(app)\n```\n\nTraining analyzes:\n- Request patterns and frequencies\n- 404 error clustering\n- Response time anomalies \n- Burst activity detection\n- Keyword context analysis\n- Path existence validation\n\n### Configuration\n\nCustomize training behavior in your Flask app:\n\n```python\napp.config.update({\n 'AIWAF_LOG_DIR': 'logs/',\n 'AIWAF_DYNAMIC_TOP_N': 15, # Top keywords to learn\n 'AIWAF_AI_CONTAMINATION': 0.05, # AI sensitivity\n 'AIWAF_EXEMPT_KEYWORDS': ['api', 'health'],\n 'AIWAF_ALLOWED_PATH_KEYWORDS': ['dashboard', 'profile']\n})\n```\n\n### Training Output Example\n\n```\n\ud83d\ude80 Starting AIWAF Flask enhanced training...\n\ud83d\udcc1 Reading logs from: access.log\n\ud83d\udcca Total log lines found: 1247\n\ud83d\udccb Parsing 1247 log entries...\n\u2705 Successfully parsed 1205 log entries\n\ud83d\udeab Blocked 3 IPs for excessive 404 errors\n\ud83e\udd16 Training AI anomaly detection model...\n\ud83d\udcbe Model saved: aiwaf_flask/resources/model.pkl\n\ud83d\udcca Trained on 1205 samples with scikit-learn v1.3.0\n\ud83d\udd0d Detected 7 potentially anomalous IPs\n \ud83d\udeab 203.0.113.10: Blocked for suspicious behavior\n\ud83d\udcda Learning suspicious keywords from logs...\n\n============================================================\n\ud83e\udd16 AIWAF FLASK ENHANCED TRAINING COMPLETE\n============================================================\n\ud83d\udcca Training Data: 1205 log entries processed\n\ud83e\udd16 AI Model: Trained with 7 features\n\ud83d\udeab AI Blocked IPs: 1 suspicious IPs blocked\n\ud83d\udcda Keywords: 5 new suspicious keywords learned\n \ud83d\udcdd Keywords: ['xmlrpc', 'wp-config', 'phpmyadmin', 'backup', 'shell']\n\ud83d\udee1\ufe0f Exemptions: 2 IPs protected from blocking\n\ud83d\udeab 404 Blocking: 3 IPs blocked for excessive 404s\n\u2705 Enhanced AI protection now active with context-aware filtering!\n============================================================\n```\n\n#### **Checking AI Dependencies**\n\n```python\n# Check if AI dependencies are available\ndef check_ai_dependencies():\n try:\n import numpy as np\n import sklearn\n print(f\"\u2705 AI Ready: NumPy {np.__version__}, Scikit-learn {sklearn.__version__}\")\n return True\n except ImportError as e:\n print(f\"\u274c AI Missing: {e}\")\n print(\"Install with: pip install aiwaf-flask[ai]\")\n return False\n\n# Use in your application\nif check_ai_dependencies():\n # Enable AI middleware\n aiwaf = AIWAF(app, middlewares=['ai_anomaly', 'rate_limit', 'logging'])\nelse:\n # Fallback to non-AI middlewares\n aiwaf = AIWAF(app, middlewares=['rate_limit', 'ip_keyword_block', 'logging'])\n```\n\n#### **Installation Options**\n\n| Installation | Command | Features |\n|--------------|---------|----------|\n| **Basic** | `pip install aiwaf-flask` | Core security (no AI) |\n| **AI Enabled** | `pip install aiwaf-flask[ai]` | Full AI capabilities |\n| **Development** | `pip install aiwaf-flask[all]` | AI + testing tools |\n| **Manual AI** | `pip install numpy scikit-learn` | Add AI to existing install |\n\n#### **Common Issues**\n\n- **\"NumPy not available\"** \u2192 Install with `pip install aiwaf-flask[ai]`\n- **\"AI anomaly detection disabled\"** \u2192 Normal when NumPy is missing\n- **Slow startup** \u2192 Consider disabling AI: `disable_middlewares=['ai_anomaly']`\n- **Memory usage** \u2192 AI uses ~50MB for ML models, disable if needed\n\n## Web Server Logging\n\nAIWAF Flask includes comprehensive logging that generates **standard web server logs** compatible with tools like Gunicorn, Nginx, and Apache log analyzers.\n\n### Log Formats\n\n#### **Combined Log Format (Default)**\n```\n127.0.0.1 - - [14/Sep/2025:15:02:41 +0000] \"GET /api/data HTTP/1.1\" 200 1234 \"http://example.com\" \"Mozilla/5.0\" 50ms - \"-\"\n203.0.113.10 - - [14/Sep/2025:15:02:42 +0000] \"GET /admin.php HTTP/1.1\" 403 0 \"-\" \"BadBot/1.0\" 10ms BLOCKED \"Malicious keyword: .php\"\n```\n\n#### **CSV Format (Easy Analysis)**\n```csv\ntimestamp,ip,method,path,status_code,response_time_ms,blocked,block_reason\n2025-09-14T15:02:41,127.0.0.1,GET,/api/data,200,50,False,\n2025-09-14T15:02:42,203.0.113.10,GET,/admin.php,403,10,True,Malicious keyword: .php\n```\n\n#### **JSON Format (Structured)**\n```json\n{\"timestamp\": \"2025-09-14T15:02:41\", \"ip\": \"127.0.0.1\", \"method\": \"GET\", \"path\": \"/api/data\", \"status_code\": 200, \"blocked\": false}\n{\"timestamp\": \"2025-09-14T15:02:42\", \"ip\": \"203.0.113.10\", \"method\": \"GET\", \"path\": \"/admin.php\", \"status_code\": 403, \"blocked\": true, \"block_reason\": \"Malicious keyword: .php\"}\n```\n\n### Log Configuration\n\n```python\napp.config['AIWAF_ENABLE_LOGGING'] = True # Enable logging\napp.config['AIWAF_LOG_DIR'] = 'logs' # Log directory\napp.config['AIWAF_LOG_FORMAT'] = 'combined' # Format: combined, common, csv, json\n```\n\n### Generated Log Files\n\n- **`access.log`** - All HTTP requests (main access log)\n- **`error.log`** - HTTP errors (4xx, 5xx status codes)\n- **`aiwaf.log`** - AIWAF security events and blocks\n\n### Log Analysis\n\n```bash\n# Analyze logs with detailed statistics\naiwaf logs --log-dir logs --format combined\n\n# Sample output:\n# \ud83d\udcca AIWAF Access Log Analysis\n# Total Requests: 1,250\n# Blocked Requests: 45 (3.6%)\n# Average Response Time: 85ms\n# Top IPs, paths, block reasons, hourly patterns, etc.\n```\n\n## Usage Examples\n\nYour routes are automatically protected:\n\n```python\n@app.route('/')\ndef home():\n return render_template('home.html') # Protected by AIWAF\n\n@app.route('/api/data')\ndef api_data():\n return jsonify({'data': 'protected'}) # Rate limited & validated\n```\n\n## Managing Protection Lists\n\n```python\nfrom aiwaf_flask.storage import add_ip_whitelist, add_ip_blacklist, add_keyword\n\n# Add IPs to whitelist (bypass all protection)\nadd_ip_whitelist('192.168.1.100')\n\n# Add IPs to blacklist (block completely)\nadd_ip_blacklist('10.0.0.1', reason='Suspicious activity')\n\n# Add malicious keywords to block\nadd_keyword('wp-admin')\nadd_keyword('.env')\n```\n\n## CSV Files Structure\n\nWhen using CSV storage, AIWAF creates these files in your data directory:\n\n- `whitelist.csv` - Whitelisted IP addresses\n- `blacklist.csv` - Blacklisted IP addresses with reasons\n- `keywords.csv` - Blocked keywords\n\nExample `blacklist.csv`:\n```csv\nip,reason,added_date\n10.0.0.1,Suspicious activity,2025-09-14T10:30:00\n192.168.1.50,Rate limit exceeded,2025-09-14T11:15:00\n```\n\n## Command Line Management\n\nAIWAF Flask includes a powerful CLI tool for managing IP exemptions, blacklists, and blocked keywords from the command line. After installation, the CLI is available globally as `aiwaf` or `aiwaf-console`.\n\n### Installation & CLI Access\n\n```bash\n# Install AIWAF Flask\npip install aiwaf-flask\n\n# CLI is now available globally - no need to be in project directory!\naiwaf --help\naiwaf-console --help # Alternative command name\n\n# If developing locally:\npip install -e . # Makes CLI available globally\n```\n\n### Basic Usage\n\n```bash\n# Show help (works from any directory after installation)\naiwaf --help\n\n# Show current statistics\naiwaf stats\n\n# List all data\naiwaf list all\n```\n\n### IP Management\n\n```bash\n# Add IP to whitelist\naiwaf add whitelist 192.168.1.100\n\n# Add IP to blacklist with reason\naiwaf add blacklist 10.0.0.5 --reason \"Brute force attack\"\n\n# Remove IP from whitelist\naiwaf remove whitelist 192.168.1.100\n\n# Remove IP from blacklist\naiwaf remove blacklist 10.0.0.5\n\n# List specific data types\naiwaf list whitelist\naiwaf list blacklist\n```\n\n### Keyword Management\n\n```bash\n# Add blocked keyword\naiwaf add keyword \"sql injection\"\naiwaf add keyword \"script\"\n\n# List blocked keywords\naiwaf list keywords\n```\n\n### Configuration Backup/Restore\n\n```bash\n# Export current configuration\naiwaf export backup.json\n\n# Import configuration from backup\naiwaf import backup.json\n```\n\n### Log Analysis\n\n```bash\n# Analyze logs with detailed statistics\naiwaf logs --log-dir logs --format combined\n```\n\n### AI Model Training\n\n```bash\n# Train AI model from access logs (auto-detects log format)\naiwaf train\n\n# Train with keyword learning only (no AI dependencies)\naiwaf train --disable-ai\n\n# Train from custom log directory with verbose output\naiwaf train --log-dir /path/to/logs --verbose\n\n# Train with specific options\naiwaf train --log-dir logs --disable-ai --verbose\n```\n\n### Custom Data Directory\n\n```bash\n# Use custom data directory\naiwaf --data-dir /path/to/custom/aiwaf_data stats\n```\n\n### Example CLI Session\n\n```bash\n# Check current status (works from any directory!)\naiwaf stats\n\n# Add some IPs to whitelist\naiwaf add whitelist 192.168.1.100\naiwaf add whitelist 10.0.0.50\n\n# Block a malicious IP\naiwaf add blacklist 203.0.113.10 --reason \"SQL injection attempts\"\n\n# Add dangerous keywords\naiwaf add keyword \"union select\"\naiwaf add keyword \"drop table\"\n\n# Review all settings\naiwaf list all\n\n# Create backup\naiwaf export production_backup.json\n```\n\n### Programmatic Management\n\nYou can also use the CLI functionality in your Python code:\n\n```python\nfrom aiwaf_flask.cli import AIWAFManager\n\n# Initialize manager\nmanager = AIWAFManager()\n\n# Add IPs programmatically\nmanager.add_to_whitelist(\"192.168.1.100\")\nmanager.add_to_blacklist(\"10.0.0.5\", \"Suspicious activity\")\n\n# Get current lists\nwhitelist = manager.list_whitelist()\nblacklist = manager.list_blacklist()\nkeywords = manager.list_keywords()\n\n# Export configuration\nmanager.export_config(\"backup.json\")\n```\n\n## CLI Features & Real-World Examples\n\nAIWAF Flask includes powerful command-line tools for production management. The CLI works independently without requiring Flask to be installed, making it perfect for system administration and automation.\n\n### Quick Setup\n\n```bash\n# Show CLI status and help\npython aiwaf_setup.py\n\n# Install Flask if needed (optional for CLI-only usage)\npython aiwaf_setup.py install-flask\n\n# Run interactive demo\npython aiwaf_setup.py demo\n```\n\n### Production Management Examples\n\n#### **Emergency IP Blocking**\n```bash\n# Block attacking IPs immediately (works from any directory!)\naiwaf add blacklist 203.0.113.10 --reason \"SQL injection attack detected\"\naiwaf add blacklist 198.51.100.5 --reason \"Brute force login attempts\"\naiwaf add blacklist 10.0.0.1 --reason \"Suspicious port scanning\"\n\n# Verify blocks are active\naiwaf list blacklist\n```\n\n#### **Whitelist Management**\n```bash\n# Add trusted networks\naiwaf add whitelist 192.168.1.0/24\naiwaf add whitelist 10.0.0.0/8\naiwaf add whitelist 172.16.0.0/12\n\n# Add specific trusted IPs\naiwaf add whitelist 203.0.113.100 # Office IP\naiwaf add whitelist 198.51.100.200 # API partner\n```\n\n#### **Security Keywords**\n```bash\n# Block common attack patterns\naiwaf add keyword \"union select\"\naiwaf add keyword \"drop table\"\naiwaf add keyword \"<script>\"\naiwaf add keyword \"javascript:\"\naiwaf add keyword \"eval(\"\naiwaf add keyword \"base64_decode\"\n\n# Review blocked keywords\naiwaf list keywords\n```\n\n#### **Daily Operations**\n```bash\n# Morning security check\naiwaf stats\n\n# Review recent blocks\naiwaf list blacklist\n\n# Create daily backup\naiwaf export \"backup-$(date +%Y%m%d).json\"\n\n# Clean up test entries\naiwaf remove whitelist 192.168.1.99\naiwaf remove blacklist 10.0.0.99\n```\n\n### Automation Scripts\n\n#### **Security Incident Response**\n```bash\n#!/bin/bash\n# incident_response.sh - Block multiple IPs from security incident\n\nMALICIOUS_IPS=(\n \"203.0.113.10\"\n \"198.51.100.5\" \n \"192.0.2.15\"\n \"198.51.100.25\"\n)\n\nfor ip in \"${MALICIOUS_IPS[@]}\"; do\n aiwaf add blacklist \"$ip\" --reason \"Security incident #2025-001\"\ndone\n\n# Create incident backup\naiwaf export \"incident-2025-001-backup.json\"\necho \"Blocked ${#MALICIOUS_IPS[@]} IPs from security incident\"\n```\n\n#### **Configuration Deployment**\n```bash\n#!/bin/bash\n# deploy_config.sh - Deploy AIWAF configuration to production\n\n# Backup current config\naiwaf export \"backup-before-deploy-$(date +%Y%m%d-%H%M).json\"\n\n# Deploy new configuration\naiwaf import \"production-config.json\"\n\n# Verify deployment\naiwaf stats\naiwaf list all\n```\n\n### Real CLI Session Output\n\n```bash\n$ aiwaf stats\n\ud83d\udcc1 Using CSV storage: aiwaf_data\n\n\ud83d\udcca AIWAF Statistics\n==================================================\nWhitelisted IPs: 5\nBlacklisted IPs: 3\nBlocked Keywords: 8\nStorage Mode: CSV\nData Directory: aiwaf_data\n\n$ aiwaf list all\n\ud83d\udcc1 Using CSV storage: aiwaf_data\n\n\ud83d\udfe2 Whitelisted IPs (5):\n \u2022 192.168.1.100\n \u2022 192.168.1.200\n \u2022 10.0.0.50\n \u2022 203.0.113.100\n \u2022 198.51.100.200\n\n\ud83d\udd34 Blacklisted IPs (3):\n \u2022 203.0.113.10 - SQL injection attack detected (2025-09-14T09:15:30)\n \u2022 198.51.100.5 - Brute force login attempts (2025-09-14T10:22:15)\n \u2022 10.0.0.1 - Suspicious port scanning (2025-09-14T11:45:22)\n\n\ud83d\udeab Blocked Keywords (8):\n \u2022 union select\n \u2022 drop table\n \u2022 <script>\n \u2022 javascript:\n \u2022 eval(\n \u2022 base64_decode\n \u2022 onload=\n \u2022 document.cookie\n\n$ aiwaf export production-backup.json\n\ud83d\udcc1 Using CSV storage: aiwaf_data\n\u2705 Configuration exported to production-backup.json\n```\n\n### Configuration Format\n\nThe exported JSON configuration contains all security settings:\n\n```json\n{\n \"whitelist\": [\n \"192.168.1.100\",\n \"192.168.1.200\",\n \"10.0.0.50\"\n ],\n \"blacklist\": {\n \"203.0.113.10\": {\n \"timestamp\": \"2025-09-14T09:15:30.123456\",\n \"reason\": \"SQL injection attack detected\"\n },\n \"198.51.100.5\": {\n \"timestamp\": \"2025-09-14T10:22:15.789012\", \n \"reason\": \"Brute force login attempts\"\n }\n },\n \"keywords\": [\n \"union select\",\n \"drop table\",\n \"<script>\",\n \"eval(\"\n ],\n \"exported_at\": \"2025-09-14T14:30:00.000000\",\n \"storage_mode\": \"CSV\"\n}\n```\n\n### Integration with Monitoring\n\n```bash\n# Add to crontab for daily reports\n0 9 * * * /path/to/aiwaf stats >> /var/log/aiwaf-daily.log\n\n# Add to monitoring script\naiwaf stats | grep -E \"(Blacklisted|Keywords)\" | \\\n awk '{if($3 > 100) print \"ALERT: High security blocks detected\"}'\n```\n\n## Production Deployment\n\n```python\n# config.py\nimport os\n\nclass ProductionConfig:\n # Use PostgreSQL in production\n SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')\n \n # Stricter limits for production\n AIWAF_RATE_MAX = 50\n AIWAF_RATE_FLOOD = 100\n AIWAF_MIN_FORM_TIME = 3.0\n\n# app.py\napp.config.from_object(ProductionConfig)\n```\n\n## Dependencies Summary\n\n### Core Dependencies (Always Required)\n- **Flask** (`>=2.0.0`) - Web framework\n- **Flask-SQLAlchemy** (`>=3.0.0`) - Database ORM (optional for CSV mode)\n\n### AI Dependencies (Optional for Enhanced Security)\n- **NumPy** (`>=1.20.0`) - Numerical computations for ML features\n- **Scikit-learn** (`>=1.0.0`) - Machine learning model training and prediction\n\n### Installation Matrix\n\n| Feature Set | Command | Dependencies Installed |\n|-------------|---------|----------------------|\n| **Basic Security** | `pip install aiwaf-flask` | Flask, Flask-SQLAlchemy |\n| **AI Enhanced** | `pip install aiwaf-flask[ai]` | Basic + NumPy, Scikit-learn |\n| **Development** | `pip install aiwaf-flask[all]` | AI + pytest, coverage tools |\n\n### Middleware Dependency Requirements\n\n| Middleware | Dependencies | Notes |\n|------------|-------------|-------|\n| `ip_keyword_block` | Core only | Always available |\n| `rate_limit` | Core only | Always available |\n| `header_validation` | Core only | Always available |\n| `honeypot` | Core only | Always available |\n| `uuid_tamper` | Core only | Always available |\n| `logging` | Core only | Always available |\n| **`ai_anomaly`** | **NumPy + Scikit-learn** | **Requires AI dependencies** |\n\n## License\nMIT\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Advanced AI-powered Web Application Firewall for Flask with intelligent threat detection, rate limiting, IP blocking, and real-time protection against web attacks",
"version": "0.1.7b0",
"project_urls": {
"Bug Tracker": "https://github.com/aayushgauba/aiwaf-flask/issues",
"Documentation": "https://github.com/aayushgauba/aiwaf-flask#readme",
"Homepage": "https://github.com/aayushgauba/aiwaf-flask",
"Repository": "https://github.com/aayushgauba/aiwaf-flask.git"
},
"split_keywords": [
"flask",
" security",
" firewall",
" web",
" protection",
" middleware",
" rate-limiting",
" ip-blocking",
" ddos",
" waf"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "823236be30bdd52d9702631089f2620af033e14ed5bcd096932a564b7c8eb574",
"md5": "2ec54aa45dfbac42a2c756e0b9fa3589",
"sha256": "ca0a2781d895cb0147820fea42dc60a838b95ac2f32bd356c11dee08e0893a7c"
},
"downloads": -1,
"filename": "aiwaf_flask-0.1.7b0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "2ec54aa45dfbac42a2c756e0b9fa3589",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 58749,
"upload_time": "2025-09-15T18:35:30",
"upload_time_iso_8601": "2025-09-15T18:35:30.435783Z",
"url": "https://files.pythonhosted.org/packages/82/32/36be30bdd52d9702631089f2620af033e14ed5bcd096932a564b7c8eb574/aiwaf_flask-0.1.7b0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "6d350efa9e52eb59c3c24a449a203bf8e788e21d0638085622a6b62bde39fe6b",
"md5": "556542150593b24e49312eaf2bac6df9",
"sha256": "46443a98d3167e50f53b3224e7ac732ea95bafc3c448e532b9ed55f14e96ee37"
},
"downloads": -1,
"filename": "aiwaf_flask-0.1.7b0.tar.gz",
"has_sig": false,
"md5_digest": "556542150593b24e49312eaf2bac6df9",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 415140,
"upload_time": "2025-09-15T18:35:32",
"upload_time_iso_8601": "2025-09-15T18:35:32.137852Z",
"url": "https://files.pythonhosted.org/packages/6d/35/0efa9e52eb59c3c24a449a203bf8e788e21d0638085622a6b62bde39fe6b/aiwaf_flask-0.1.7b0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-09-15 18:35:32",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "aayushgauba",
"github_project": "aiwaf_flask",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "aiwaf-flask"
}