🔧 Django Middleware

Middleware Setup

Learn how to properly configure AIWAF middleware components in your Django application for optimal security protection.

IPAndKeywordBlockMiddleware

The IPAndKeywordBlockMiddleware is a powerful security component that provides real-time protection against malicious requests by analyzing IP addresses and request content for suspicious patterns.

🚀 Key Features

🔒 IP Blocking

Automatically blocks known malicious IP addresses and ranges based on threat intelligence and behavioral analysis.

🔍 Keyword Detection

Scans request content for suspicious keywords and patterns commonly used in attacks like SQL injection and XSS.

⚡ Real-time Processing

Processes requests in real-time with minimal latency impact on your Django application performance.

📊 Detailed Logging

Provides comprehensive logging of blocked requests with detailed analysis for security monitoring.

⚙️ Configuration

Add the middleware to your Django settings:

# settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'aiwaf.middleware.IPAndKeywordBlockMiddleware',  # Add this line
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ... other middleware
]

🔧 How It Works

The middleware operates through a multi-layered security approach:

1. Request Interception

Intercepts all incoming HTTP requests before they reach your Django views, enabling early threat detection.

2. IP Analysis

Checks the client IP address against:

  • Blacklisted IP databases
  • Geographic restrictions
  • Rate limiting rules
  • Behavioral patterns

3. Content Scanning

Analyzes request content including:

  • URL parameters
  • POST data
  • HTTP headers
  • Cookie values

4. Response Generation

When a threat is detected, the middleware:

  • Blocks the request immediately
  • Logs the incident details
  • Returns appropriate HTTP response
  • Updates threat intelligence
Important: Always test the middleware in a development environment first. The blocking behavior can be configured to suit your application's specific needs.

📝 Configuration Options

Customize the middleware behavior through Django settings:

# settings.py
AIWAF_SETTINGS = {
    'IP_BLOCKING': {
        'ENABLED': True,
        'WHITELIST': ['127.0.0.1', '192.168.1.0/24'],
        'BLACKLIST_UPDATE_INTERVAL': 3600,  # seconds
    },
    'KEYWORD_DETECTION': {
        'ENABLED': True,
        'SENSITIVITY_LEVEL': 'medium',  # low, medium, high
        'CUSTOM_PATTERNS': [],
    },
    'LOGGING': {
        'ENABLED': True,
        'LEVEL': 'WARNING',
        'FORMAT': 'detailed',
    }
}

🔍 Monitoring & Alerts

The middleware provides built-in monitoring capabilities:

  • Real-time threat detection alerts
  • Daily security summary reports
  • Integration with Django admin interface
  • Custom webhook notifications

RateLimitMiddleware

The RateLimitMiddleware provides intelligent rate limiting to protect your Django application from abuse, DDoS attacks, and excessive request patterns while maintaining excellent performance for legitimate users.

🚀 Key Features

⚡ Smart Rate Limiting

Two-tier rate limiting with soft limits (429 responses) and hard limits (automatic IP blocking) for flood protection.

🔧 Configurable Thresholds

Fully configurable rate windows, soft limits, and flood detection thresholds via Django settings.

🛡️ Exemption Support

Multiple layers of exemption checking to ensure legitimate traffic and trusted IPs are never blocked.

📊 Memory Efficient

Uses Django's cache framework for efficient memory usage with automatic cleanup of old request data.

⚙️ Configuration

Configure rate limiting behavior through Django settings:

# settings.py
# Rate limiting configuration
AIWAF_RATE_WINDOW = 10      # Time window in seconds
AIWAF_RATE_MAX = 20         # Soft limit (returns 429)
AIWAF_RATE_FLOOD = 40       # Hard limit (blocks IP)

# Add to middleware stack
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'aiwaf.middleware.RateLimitMiddleware',  # Add early for best protection
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ... other middleware
]

🔧 How It Works

1. Request Tracking

Tracks timestamps of requests per IP address within a sliding time window using Django's cache framework.

2. Two-Tier Protection

Implements both soft and hard limits:

  • Soft Limit: Returns HTTP 429 "Too Many Requests"
  • Hard Limit: Automatically blocks IP and returns HTTP 403

3. Exemption Layers

Multiple exemption checks ensure legitimate traffic flows:

  • Early exemption check via is_exempt(request)
  • IP-level exemption via exemption store
  • Double-check before blocking
Important: The middleware automatically handles exempted IPs and will never block them, even if they exceed flood limits.

AIAnomalyMiddleware

The AIAnomalyMiddleware uses machine learning to detect anomalous behavior patterns and automatically learns from attack attempts to improve protection over time.

🚀 Key Features

🤖 AI-Powered Detection

Uses machine learning models to identify anomalous request patterns that don't match normal user behavior.

📚 Self-Learning System

Automatically learns malicious keywords from 404 responses and suspicious request patterns.

🎯 Context-Aware Analysis

Analyzes request context to avoid false positives, only learning from truly malicious behavior.

📊 Behavioral Analytics

Tracks comprehensive request metrics including response times, status codes, and burst patterns.

⚙️ Configuration

Configure AI anomaly detection through Django settings:

# settings.py
# AI Anomaly Detection configuration  
AIWAF_WINDOW_SECONDS = 60   # Analysis window in seconds
AIWAF_DYNAMIC_TOP_N = 10    # Top learned keywords to use

# Add to middleware stack
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'aiwaf.middleware.AIAnomalyMiddleware',  # AI-powered protection
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ... other middleware
]

🔧 How It Works

1. Request Analysis

Analyzes multiple request features:

  • Path length and complexity
  • Malicious keyword hits
  • Response time patterns
  • HTTP status codes
  • Burst request patterns
  • 404 error frequency

2. AI Model Prediction

Uses trained machine learning model to identify anomalous patterns based on feature analysis and behavioral metrics.

3. Intelligent Blocking

When anomalies are detected, analyzes recent behavior patterns:

  • Average malicious keyword hits
  • 404 error patterns
  • Request burst behavior
  • Total request volume

4. Smart Learning

Only learns keywords from truly malicious contexts:

  • 404 responses on non-existent paths
  • Requests with multiple malicious indicators
  • Common attack patterns (directory traversal, etc.)
  • Suspicious query parameters

🧠 Malicious Context Detection

The middleware identifies malicious context through multiple indicators:

# Strong malicious indicators include:
- Multiple consecutive suspicious segments
- Common attack patterns (../, wp-admin, .env)
- Suspicious query parameters (cmd, exec, system)
- Multiple directory traversal attempts
- Encoded attack patterns (%2e%2e, %252e)
Smart Protection: The AI middleware is designed to be conservative, erring on the side of allowing traffic rather than blocking legitimate users. It only blocks when strong malicious indicators are present.

HoneypotTimingMiddleware

The HoneypotTimingMiddleware detects automated attacks by analyzing timing patterns and HTTP method usage. It identifies bots that submit forms too quickly or use inappropriate HTTP methods.

🚀 Key Features

⏱️ Form Timing Analysis

Detects forms submitted too quickly (faster than humanly possible) to identify automated attacks and bots.

🔍 HTTP Method Validation

Automatically detects whether views support specific HTTP methods and blocks inappropriate requests.

⏳ Page Session Timeout

Detects stale sessions and forces page reloads for security, preventing replay attacks on old forms.

🎯 Smart Login Detection

Uses shorter timing thresholds for login forms since users can authenticate quickly with password managers.

⚙️ Configuration

Configure timing thresholds through Django settings:

# settings.py
# Honeypot timing configuration
AIWAF_MIN_FORM_TIME = 1.0    # Minimum seconds for form submission
AIWAF_MAX_PAGE_TIME = 240    # Maximum page session time (4 minutes)

# Add to middleware stack
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'aiwaf.middleware.HoneypotTimingMiddleware',  # Timing-based protection
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ... other middleware
]

🔧 How It Works

1. HTTP Method Detection

Automatically determines if views support specific HTTP methods by:

  • Analyzing class-based view method handlers
  • Inspecting function-based view source code
  • Checking URL pattern names for method hints
  • Using Django's http_method_names attribute

2. Timing Validation

Tracks GET request timestamps and validates POST timing:

  • Records timestamp on GET requests
  • Validates POST submission timing
  • Special handling for login forms (0.1s threshold)
  • Blocks submissions faster than human capability

3. Session Management

Prevents stale form attacks and session hijacking:

  • Detects pages open longer than 4 minutes
  • Forces fresh page loads for expired sessions
  • Returns 409 Conflict for expired forms
  • Prevents replay attacks on old forms
Login Optimization: The middleware automatically uses shorter timing thresholds (0.1 seconds) for login paths to accommodate password managers and fast user authentication.

UUIDTamperMiddleware

The UUIDTamperMiddleware protects against UUID enumeration attacks by validating that UUID parameters in URLs correspond to actual database records.

🚀 Key Features

🔒 UUID Validation

Automatically validates UUID parameters against actual database records to prevent enumeration attacks.

🎯 Smart Model Detection

Automatically discovers models with UUID primary keys across all Django apps without manual configuration.

⚡ Efficient Checking

Uses optimized database queries with exists() to minimize performance impact on legitimate requests.

🛡️ Immediate Blocking

Instantly blocks IPs attempting to access non-existent UUIDs, preventing enumeration attacks.

⚙️ Configuration

No additional configuration required - works automatically:

# settings.py
# Add to middleware stack
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'aiwaf.middleware.UUIDTamperMiddleware',  # UUID protection
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ... other middleware
]

# Works automatically with UUID models like:
class MyModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)
    # ... other fields

🔧 How It Works

1. URL Parameter Extraction

Automatically extracts UUID parameters from Django URL patterns using view_kwargs.

2. Model Discovery

Dynamically discovers all models with UUID primary keys:

  • Analyzes Django app configurations
  • Identifies models with UUIDField primary keys
  • Builds validation logic automatically

3. Database Validation

Efficiently validates UUID existence:

  • Uses optimized exists() queries
  • Handles malformed UUIDs gracefully
  • Validates against all relevant models
Performance Note: The middleware uses efficient database exists() queries and handles exceptions gracefully to minimize impact on application performance.

HeaderValidationMiddleware

The HeaderValidationMiddleware analyzes HTTP headers to detect bots, scrapers, and malicious automated requests by examining header patterns and quality.

🚀 Key Features

🕵️ Header Quality Analysis

Calculates quality scores based on header completeness and realistic browser-like patterns.

🤖 Bot Detection

Identifies suspicious user agents while whitelisting legitimate crawlers like Google, Bing, and social media bots.

🔍 Pattern Recognition

Detects suspicious header combinations that indicate automated tools or malicious requests.

⚡ Static File Skip

Automatically skips validation for static files (CSS, JS, images) to optimize performance.

⚙️ Configuration

Works out of the box with intelligent defaults:

# settings.py
# Add to middleware stack
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'aiwaf.middleware.HeaderValidationMiddleware',  # Header analysis
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ... other middleware
]

🔧 Detection Methods

1. Required Header Validation

Ensures essential headers are present:

  • User-Agent: Must be present and realistic
  • Accept: Must indicate content preferences

2. User-Agent Analysis

Detects suspicious patterns while allowing legitimate bots:

  • Blocks common bot/scraper signatures
  • Whitelists Google, Bing, social media crawlers
  • Validates user-agent length and format
  • Detects programming language HTTP clients

3. Header Quality Scoring

Calculates quality score (threshold: 3 points):

  • User-Agent + Accept headers: 4 points
  • Browser headers (language, encoding): +1 each
  • Realistic combinations: bonus points
  • Low scores indicate automation

4. Suspicious Combinations

Detects inconsistent header patterns:

  • HTTP/2 with old browser user-agents
  • Generic Accept headers without language
  • Missing browser-standard headers
  • Protocol version mismatches

🤖 Legitimate Bot Whitelist

Automatically allows legitimate crawlers:

# Whitelisted bots include:
- Google (Googlebot)
- Bing (Bingbot)  
- Yahoo (Slurp)
- DuckDuckGo (DuckDuckBot)
- Social media crawlers (Facebook, Twitter, LinkedIn)
- Messaging apps (WhatsApp, Telegram)
- Monitoring services (Pingdom, UptimeRobot)
Balance Protection: The middleware is designed to block obvious automation while allowing legitimate tools and crawlers that benefit your site's SEO and monitoring.