🔥 Flask Framework
Middleware Setup
Comprehensive guide to configuring AIWAF middleware in your Flask application. Learn about different setup patterns, middleware selection, and advanced configuration options.
🚀 Quick Setup Methods
Method 1: Simple Registration (All Middlewares)
The easiest way to get started with maximum protection:
from flask import Flask
from aiwaf_flask import register_aiwaf_middlewares
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
# Enable all 7 middlewares with default settings
register_aiwaf_middlewares(app)
@app.route('/')
def home():
return "Protected by AIWAF!"
Method 2: AIWAF Class (Recommended)
More control over middleware selection and configuration:
from flask import Flask
from aiwaf_flask import AIWAF
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
# Initialize with all middlewares (default)
aiwaf = AIWAF(app)
# Or specify custom middleware selection
aiwaf = AIWAF(app, middlewares=[
'rate_limit',
'ip_keyword_block',
'ai_anomaly',
'logging'
])
Method 3: Factory Pattern
For Flask application factories:
from flask import Flask
from aiwaf_flask import AIWAF
# Initialize without app
aiwaf = AIWAF()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
# Initialize with app
aiwaf.init_app(app)
return app
🛡️ Middleware Selection Patterns
Enable Specific Middlewares Only
# Custom selection - only enable what you need
aiwaf = AIWAF(app, middlewares=[
'ip_keyword_block', # Core IP/keyword blocking
'rate_limit', # Rate limiting protection
'ai_anomaly', # AI anomaly detection
'logging' # Request logging
])
# ↑ Enables only 4 out of 7 available middlewares
Disable Specific Middlewares
# Enable all 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)
Security Level Presets
🛡️ Minimal Security (Essential Protection)
Best for: Small applications, development environments
aiwaf = AIWAF(app, middlewares=[
'ip_keyword_block', # Core attack prevention
'rate_limit', # Basic rate limiting
'logging' # Security monitoring
])
🚀 Standard Security (Recommended)
Best for: Most production applications
aiwaf = AIWAF(app, middlewares=[
'ip_keyword_block', # Core attack prevention
'rate_limit', # Rate limiting protection
'header_validation', # HTTP header validation
'ai_anomaly', # AI anomaly detection
'logging' # Security monitoring
])
🔥 Maximum Security (Full Protection)
Best for: High-security applications, sensitive data
# Enable all middlewares (default)
aiwaf = AIWAF(app)
🤖 AI-Focused Security
Best for: Applications with complex user patterns
aiwaf = AIWAF(app, middlewares=[
'ai_anomaly', # Machine learning detection
'rate_limit', # Intelligent rate limiting
'ip_keyword_block', # Enhanced keyword learning
'logging' # ML-enhanced logging
])
⚙️ Configuration Options
Complete Configuration Example
from flask import Flask
from aiwaf_flask import AIWAF
app = Flask(__name__)
# Complete AIWAF configuration
app.config.update({
# === Core Settings ===
'SECRET_KEY': 'your-secret-key',
'AIWAF_USE_CSV': True, # Storage: True=CSV, False=Database
'AIWAF_DATA_DIR': 'aiwaf_data', # Data directory (auto-detected)
'AIWAF_LOG_DIR': 'logs', # Log directory (auto-detected)
# === Protection Settings ===
'AIWAF_ENABLE_PROTECTION': True, # Master protection switch
'AIWAF_RATE_LIMIT': 10, # Requests per window
'AIWAF_WINDOW_SECONDS': 60, # Rate limiting window
'AIWAF_RATE_FLOOD': 200, # Auto-block threshold
'AIWAF_HONEYPOT_DELAY': 0.5, # Honeypot timing sensitivity
'AIWAF_MIN_FORM_TIME': 1.0, # Minimum form submission time
# === AI Training Settings ===
'AIWAF_MIN_AI_LOGS': 10000, # Minimum logs for AI training
'AIWAF_FORCE_AI': False, # Force AI training
'AIWAF_DYNAMIC_TOP_N': 10, # Keywords to learn
'AIWAF_AI_CONTAMINATION': 0.05, # AI sensitivity (5%)
# === Logging Settings ===
'AIWAF_ENABLE_LOGGING': True, # Enable request logging
'AIWAF_LOG_FORMAT': 'combined', # Log format: combined, common, csv, json
# === Path Exemptions ===
'AIWAF_EXEMPT_PATHS': [ # Paths to skip protection
'/health', '/status', '/favicon.ico',
'/robots.txt', '/sitemap.xml'
],
})
# Initialize with custom middleware selection
aiwaf = AIWAF(app, middlewares=[
'rate_limit', 'ip_keyword_block', 'ai_anomaly', 'logging'
])
🎯 Route-Level Protection Control
Exemption Decorators
Fine-grained control over which middlewares apply to specific routes:
from aiwaf_flask import aiwaf_exempt, aiwaf_exempt_from, aiwaf_only
# Complete exemption from all AIWAF protection
@app.route('/health')
@aiwaf_exempt
def health_check():
return {'status': 'ok'}
# Exempt from specific middlewares only
@app.route('/api/webhook')
@aiwaf_exempt_from('rate_limit', 'ai_anomaly')
def github_webhook():
return {'received': True}
# Apply only specific middlewares
@app.route('/api/public')
@aiwaf_only('rate_limit')
def public_api():
return {'data': 'public'}
Path-Based Exemptions
Configure exemptions in your application config:
app.config['AIWAF_EXEMPT_PATHS'] = [
'/health', # Health checks
'/metrics', # Monitoring
'/static/*', # Static files
'/api/webhook/*', # Webhook endpoints
'*.css', # CSS files
'*.js', # JavaScript files
]
🗄️ Storage Configuration
CSV Storage Setup
Recommended for smaller applications - no database required:
app.config.update({
'AIWAF_USE_CSV': True,
'AIWAF_DATA_DIR': 'aiwaf_data', # Optional: custom directory
})
# Files created automatically:
# aiwaf_data/
# ├── whitelist.csv # Whitelisted IPs
# ├── blacklist.csv # Blacklisted IPs with reasons
# ├── keywords.csv # Blocked keywords
# ├── rate_limit.csv # Rate limiting data
# └── model.pkl # AI model (if trained)
Database Storage Setup
Recommended for production environments:
from flask_sqlalchemy import SQLAlchemy
app.config.update({
'AIWAF_USE_CSV': False, # Use database storage
'SQLALCHEMY_DATABASE_URI': 'sqlite:///app.db',
'SQLALCHEMY_TRACK_MODIFICATIONS': False
})
db = SQLAlchemy(app)
# Initialize database tables
with app.app_context():
db.create_all()
aiwaf = AIWAF(app)
🚦 Middleware Management
Runtime Middleware Control
# 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}")
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 |
🔧 Advanced Integration Examples
Flask-Login Integration
from flask_login import current_user
from aiwaf_flask import AIWAF
@app.before_request
def aiwaf_user_context():
# Skip protection for authenticated admin users
if current_user.is_authenticated and current_user.is_admin:
request.aiwaf_exempt = True
aiwaf = AIWAF(app)
Webhook Protection
from aiwaf_flask import aiwaf_only
@app.route('/webhooks/github', methods=['POST'])
@aiwaf_only('rate_limit') # High rate limit, minimal protection
def github_webhook():
# Process webhook
return {"status": "received"}
High-Traffic Optimization
app.config.update({
'AIWAF_USE_CSV': False, # Use database for better performance
'AIWAF_RATE_LIMIT': 1000, # Higher rate limits
'AIWAF_WINDOW_SECONDS': 300, # Longer windows
'AIWAF_MAX_RATE_ENTRIES': 10000, # Limit rate limiting entries
'AIWAF_CLEANUP_INTERVAL': 3600, # Cleanup old entries hourly
})
Setup Complete! Your Flask application is now protected by AIWAF. Monitor the logs directory for security events and access patterns.
🚀 Next Steps
After setting up middleware: