Skip to content

A rule-based Web Application Firewall (WAF) built with FastAPI and Python - v1. Detects and blocks XSS, SQL injection, path traversal, and other common web attacks. Learning project exploring cybersecurity concepts. Foundation for future adaptive ML-based detection.

License

Notifications You must be signed in to change notification settings

SomeFoxDeveloper/adaptivewaf

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

3 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Adaptive Web Application Firewall (WAF) - v1 Rule-Based

Warning

This is a hobby project created for educational purposes.

It is not intended for use in a production environment. Please use it responsibly and at your own risk.

Note

Security Note While this project implements several security features, it is essential that you conduct your own security testing and validation. Do not rely solely on the protections provided here.

A hobby project: A Web Application Firewall built with FastAPI and Python to detect and block common web attacks like XSS, SQL injection, path traversal, and more. This is a learning project for exploring cybersecurity concepts and Python web development.

Note: This is currently a rule-based WAF implementation (v1). Future versions will include adaptive/machine learning capabilities for dynamic threat detection.

๐Ÿ›ก๏ธ Features

What It Blocks

The WAF is designed to protect your web application from a variety of common attacks, including:

  • Cross-Site Scripting (XSS): Prevents attackers from injecting malicious scripts into web pages viewed by other users. It detects script tags, event handlers (onload, onerror), and other XSS vectors.
  • SQL Injection (SQLi): Protects against attempts to manipulate backend databases by inserting malicious SQL queries into input fields. It blocks common SQL keywords (SELECT, UNION, DROP) and patterns.
  • Path Traversal: Blocks attempts to access files and directories stored outside the web root folder by using sequences like ../.
  • Command Injection: Prevents attackers from executing arbitrary commands on the host operating system. It blocks suspicious keywords such as exec, shell, system, and whoami.
  • Header Injection: Validates incoming HTTP headers to prevent attacks like HTTP Response Splitting and cache poisoning.
  • Buffer Overflow: Protects against denial-of-service (DoS) attacks by enforcing limits on the size of request payloads, URLs, and headers.
  • Encoding and Obfuscation Attacks: Detects various encoding techniques (e.g., URL, Base64) used to hide malicious payloads from basic filters.
  • Suspicious User-Agents: Blocks requests from known malicious or suspicious user-agents.

Advanced Features

  • Circuit Breaker Pattern: Protects backend services from cascade failures
  • SYN Flood Protection: Rate limiting and connection monitoring
  • Honeypot Data Collection: Logs detailed attack information
  • CAPTCHA Integration: Challenge-response for suspicious traffic
  • Compression Support: Gzip compression for responses
  • Security Headers: Automatic security header injection
  • Input Validation: Comprehensive request validation

Logging & Monitoring

  • Structured JSON Logging: Complete audit trails
  • Honeypot Logs: Detailed attack forensics
  • Real-time Monitoring: Request/response tracking
  • Configurable Log Levels: Debug to production modes

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.8+
  • pip package manager

Installation

  1. Clone the repository:

    git clone https://github.com/yourusername/adaptivewaf.git
    cd adaptivewaf
  2. Install dependencies:

    pip install -r requirements.txt
  3. Configure the firewall:

    cp config.conf.example config.conf
    # Edit config.conf with your settings
  4. Generate SSL certificates (optional):

    ./generate_ssl_certs.sh
  5. Start the WAF:

    python main.py

The WAF will start on http://localhost:8080 (and https://localhost:8443 if SSL enabled).

๐Ÿ“‹ Configuration

Edit config.conf to customize:

Backend Configuration

[proxy]
backend_url = http://your-backend-server:port/
host = 0.0.0.0
http_enabled = true
https_enabled = true

Security Settings

[waf]
enabled = true
block_xss = true
block_sql_injection = true
block_path_traversal = true
# ... many more options

Rate Limiting

[syn_protection]
enabled = true
max_connections_per_ip = 100
time_window = 60
block_duration = 300

๐Ÿ”ง API Endpoints

  • GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD /* - Proxied requests to backend
  • GET /__captcha_verify - CAPTCHA verification endpoint

๐Ÿงช Testing

Penetration Testing

The WAF has been tested agai ---nst common attack vectors:

# XSS Attack
curl "http://localhost:8080/?search=<script>alert('xss')</script>"

# SQL Injection
curl "http://localhost:8080/?id=1%20UNION%20SELECT%20username,password%20FROM%20users"

# Path Traversal
curl "http://localhost:8080/../../../etc/passwd"

# Command Injection
curl "http://localhost:8080/?cmd=whoami;id"

All attacks are properly blocked with detailed logging.

Unit Testing

python -m pytest tests/

๐Ÿ“Š Monitoring

Log Files

  • logs/waf.log - Main application logs
  • logs/honeypot.log - Detailed attack forensics

Log Format

Security violations are logged in structured JSON:

{
  "timestamp": "2025-11-09T16:21:39.729428+00:00",
  "level": "ERROR",
  "source_ip": "127.0.0.1",
  "http_method": "GET",
  "request_path": "?search=<script>alert('xss')</script>",
  "user_agent": "curl/8.16.0",
  "message": "Security policy violation: Potential XSS attack blocked",
  "waf_details": {
    "rule_triggered": "XSS_Pattern_Search_Query",
    "param_name": "search",
    "param_value": "<script>alert('xss')</script>"
  },
  "headers": {...},
  "body": null
}

๐Ÿ—๏ธ Architecture

Adaptive WAF
โ”œโ”€โ”€ main.py                 # Main application
โ”œโ”€โ”€ module/                 # Security modules
โ”‚   โ”œโ”€โ”€ rule_engine.py      # Pattern matching
โ”‚   โ”œโ”€โ”€ keyword_detection.py# Suspicious keywords
โ”‚   โ”œโ”€โ”€ encoding_detection.py# Encoding attacks
โ”‚   โ”œโ”€โ”€ path_traversal_detection.py
โ”‚   โ”œโ”€โ”€ overflow_detection.py
โ”‚   โ”œโ”€โ”€ circuit_breaker.py  # Resilience
โ”‚   โ”œโ”€โ”€ captcha_challenge.py# CAPTCHA system
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ templates/              # HTML templates
โ”œโ”€โ”€ certs/                  # SSL certificates
โ”œโ”€โ”€ logs/                   # Log files
โ”œโ”€โ”€ config.conf             # Configuration
โ””โ”€โ”€ requirements.txt        # Dependencies

๐Ÿ”’ Security Features

Detection Methods

  1. Pattern Matching: Regex-based attack detection
  2. Keyword Analysis: Suspicious parameter detection
  3. Encoding Validation: Obfuscated attack prevention
  4. Length Limits: Buffer overflow prevention
  5. Header Validation: Injection attack prevention
  6. URL Similarity: Known attack pattern matching

Resilience Features

  • Circuit Breaker: Backend failure protection
  • Rate Limiting: SYN flood prevention
  • Fallback Responses: Graceful error handling
  • Timeout Management: Request timeout controls

๐Ÿ”ฎ Future Development

This project is continuously evolving. Future versions aim to incorporate advanced features, including:

  • Machine Learning Integration: An adaptive learning system that analyzes attack patterns and automatically updates the ML model to recognize new and evolving threats.
  • Zero-Day Threat Detection: Proactive identification of unknown vulnerabilities by analyzing request behavior and anomalies.
  • Advanced Analytics Dashboard: A comprehensive interface for visualizing security events, traffic patterns, and threat intelligence.

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new features
  4. Ensure all tests pass
  5. Submit a pull request

๐Ÿ“„ License

MIT License - see LICENSE file for details.

About

A rule-based Web Application Firewall (WAF) built with FastAPI and Python - v1. Detects and blocks XSS, SQL injection, path traversal, and other common web attacks. Learning project exploring cybersecurity concepts. Foundation for future adaptive ML-based detection.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •