🔥 Flask Framework

CLI Commands

Comprehensive command-line interface for managing AIWAF Flask protection. The CLI provides powerful tools for training, monitoring, and maintaining your security system with intelligent auto-configuration.

🚀 Auto-Configuration System

AIWAF Flask includes an intelligent auto-configuration system that automatically detects and manages data and log directories, making commands work from any location.

Smart Directory Detection: The CLI automatically finds your AIWAF data and log directories, regardless of your current working directory. No manual path configuration needed!

How Auto-Detection Works

  1. Environment Variables: Checks AIWAF_DATA_DIR and AIWAF_LOG_DIR
  2. Existing Directories: Scans for directories with actual data/logs
  3. Scoring Algorithm: Ranks directories by content and suitability
  4. Fallback Creation: Creates directories in consistent locations

📋 Command Categories

📊 List Commands

View your protection data and statistics

List All Data

# Show all protection data with auto-configured paths
python -m aiwaf_flask.cli list all

List Specific Data Types

# List whitelisted IPs
python -m aiwaf_flask.cli list whitelist

# List blacklisted IPs with reasons
python -m aiwaf_flask.cli list blacklist

# List blocked keywords
python -m aiwaf_flask.cli list keywords

Show Statistics

# Display comprehensive statistics
python -m aiwaf_flask.cli stats

⚙️ Management Commands

Add and remove protection entries

Add Items

# Add IP to whitelist
python -m aiwaf_flask.cli add whitelist 192.168.1.10

# Add IP to blacklist with reason
python -m aiwaf_flask.cli add blacklist 10.0.0.50 --reason "Malicious scan detected"

# Add suspicious keyword
python -m aiwaf_flask.cli add keyword "wp-admin"

Remove Items

# Remove IP from whitelist
python -m aiwaf_flask.cli remove whitelist 192.168.1.10

# Remove IP from blacklist
python -m aiwaf_flask.cli remove blacklist 10.0.0.50

# Remove keyword
python -m aiwaf_flask.cli remove keyword "old-pattern"

🤖 Training Commands

Train the AI model and learn from log data

Basic Training (Keyword Learning)

# Fast keyword-only training (no AI dependencies needed)
python -m aiwaf_flask.cli train --disable-ai

Full AI Training

# Complete AI training (requires 10k+ log entries)
python -m aiwaf_flask.cli train --verbose

# Force AI training with insufficient data (not recommended)
python -m aiwaf_flask.cli train --force-ai --min-ai-logs 1000

Custom Training Options

# Train from custom log directory
python -m aiwaf_flask.cli train --log-dir /path/to/logs --verbose

# Training with custom AI threshold
python -m aiwaf_flask.cli train --min-ai-logs 5000 --verbose

📈 Log Analysis Commands

Analyze access logs and security events

Comprehensive Log Analysis

# Analyze logs with detailed statistics
python -m aiwaf_flask.cli logs --format combined

Different Log Formats

# Analyze CSV format logs
python -m aiwaf_flask.cli logs --format csv

# Analyze JSON format logs
python -m aiwaf_flask.cli logs --format json

# Custom log directory analysis
python -m aiwaf_flask.cli logs --log-dir /custom/logs --format combined

🔧 Model Management Commands

Manage AI models and dependencies

Model Status

# Check model status and compatibility
python -m aiwaf_flask.cli model --check

# Show detailed model information
python -m aiwaf_flask.cli model --info

Model Operations

# Force retrain model with current dependencies
python -m aiwaf_flask.cli model --retrain

💾 Export/Import Commands

Backup and restore configuration

# Export current configuration
python -m aiwaf_flask.cli export --output aiwaf_backup.json

# Import configuration
python -m aiwaf_flask.cli import --file aiwaf_backup.json

🎯 Training System

Training Requirements

Basic Training (Keyword Learning)

  • Minimum: 50 log entries
  • Functionality: Keyword pattern learning
  • Storage: Updates keyword blacklist
  • Dependencies: None (works with base installation)

AI Training (Anomaly Detection)

  • Minimum: 10,000 log entries
  • Functionality: Machine learning model training
  • Storage: Creates/updates ML model
  • Dependencies: NumPy, Scikit-learn (install with pip install aiwaf-flask[ai])

Supported Log Formats

Apache/Nginx Combined Format

127.0.0.1 - - [16/Sep/2025:10:30:45 +0000] "GET /api/data HTTP/1.1" 200 1234 "http://example.com" "Mozilla/5.0..."

CSV Format

timestamp,ip,method,path,status_code,user_agent,size
2025-09-16T10:30:45,127.0.0.1,GET,/api/data,200,Mozilla/5.0...,1234

JSON/JSONL Format

{"timestamp": "2025-09-16T10:30:45", "ip": "127.0.0.1", "method": "GET", "path": "/api/data", "status": 200}

📊 Example Training Output

$ python -m aiwaf_flask.cli train --verbose

🚀 AIWAF Flask Training Tool
========================================
📁 Auto-configured data directory: C:\Users\username\aiwaf_data
🔍 Detection method: Selected data directory with most existing data
📁 Auto-configured log directory: C:\Users\username\logs
Log directory: C:\Users\username\logs
AI training: enabled
Min AI logs threshold: 10000
========================================

📁 Reading logs from: C:\Users\username\logs\access.log
📊 Total log lines found: 15,247
📋 Parsing 15,247 log entries...
✅ Successfully parsed 14,892 log entries
🔢 Generated 14,892 feature vectors for training
🤖 Training AI anomaly detection model...
📚 Learning suspicious keywords from logs...

============================================================
🤖 AIWAF FLASK TRAINING COMPLETE
============================================================
📊 Training Data: 14,892 log entries processed
🤖 AI Model: Successfully trained with 99.7% feature retention
🚫 AI Blocked IPs: 0 (training mode)
📚 Keywords: 23 new suspicious keywords learned
🛡️  Exemptions: 5 IPs protected from blocking
🚫 404 Blocking: 3 IPs blocked for excessive 404s
✅ Enhanced protection is now active!

📈 Example Log Analysis Output

$ python -m aiwaf_flask.cli logs --format combined

📁 Auto-configured log directory: C:\Users\username\logs

📊 AIWAF Access Log Analysis
==================================================
Total Requests: 15,247
Blocked Requests: 423
Unique IPs: 1,892
Block Rate: 2.8%

📈 Status Code Distribution:
  • 200: 12,456 (81.7%)
  • 403: 423 (2.8%) 
  • 404: 1,234 (8.1%)
  • 429: 892 (5.9%)
  • 500: 242 (1.6%)

🌐 Top Client IPs:
  • 192.168.1.100: 2,345 requests (15.4%)
  • 10.0.0.25: 1,234 requests (8.1%)
  • 172.16.0.50: 987 requests (6.5%)

📊 Most Requested Paths:
  • /api/data: 3,456 requests
  • /health: 2,134 requests  
  • /dashboard: 1,876 requests
  • /api/users: 1,234 requests

🚫 Block Reasons:
  • Rate limit exceeded: 234 blocks
  • IP blacklisted: 123 blocks
  • Malicious keyword: 45 blocks
  • AI anomaly detected: 21 blocks

🛠️ Troubleshooting

Common Issues

"No log lines found" Error:
# Check log directory
python -m aiwaf_flask.cli logs --log-dir /path/to/logs

# Verify auto-detection
python -m aiwaf_flask.cli train --verbose
# Look for: "📁 Auto-configured log directory: ..."
"Need at least 10000 for AI training":
# Use keyword-only training
python -m aiwaf_flask.cli train --disable-ai

# Or force AI training (not recommended)
python -m aiwaf_flask.cli train --force-ai --min-ai-logs 100
Directory Inconsistency:
# Check auto-configuration
python -m aiwaf_flask.cli list all
# Should show same data directory regardless of working directory

# Set explicit paths if needed
export AIWAF_DATA_DIR=/app/data
export AIWAF_LOG_DIR=/app/logs

AI Dependencies Check

# 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]')
"

🚀 Quick Reference

Essential Commands:
# Setup and basic usage
pip install aiwaf-flask[ai]
python -m aiwaf_flask.cli list all
python -m aiwaf_flask.cli train --verbose

# Management
python -m aiwaf_flask.cli add blacklist 10.0.0.1 --reason "Malicious"
python -m aiwaf_flask.cli logs --format combined
python -m aiwaf_flask.cli model --check

# Monitoring
python -m aiwaf_flask.cli stats
python -m aiwaf_flask.cli export --output backup.json
Remember: AIWAF learns and adapts to your application's traffic patterns. Regular training with fresh log data improves protection effectiveness. The auto-configuration system ensures commands work consistently across different environments.