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.
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, andwhoami. - 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.
- 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
- Structured JSON Logging: Complete audit trails
- Honeypot Logs: Detailed attack forensics
- Real-time Monitoring: Request/response tracking
- Configurable Log Levels: Debug to production modes
- Python 3.8+
- pip package manager
-
Clone the repository:
git clone https://github.com/yourusername/adaptivewaf.git cd adaptivewaf -
Install dependencies:
pip install -r requirements.txt
-
Configure the firewall:
cp config.conf.example config.conf # Edit config.conf with your settings -
Generate SSL certificates (optional):
./generate_ssl_certs.sh
-
Start the WAF:
python main.py
The WAF will start on http://localhost:8080 (and https://localhost:8443 if SSL enabled).
Edit config.conf to customize:
[proxy]
backend_url = http://your-backend-server:port/
host = 0.0.0.0
http_enabled = true
https_enabled = true[waf]
enabled = true
block_xss = true
block_sql_injection = true
block_path_traversal = true
# ... many more options[syn_protection]
enabled = true
max_connections_per_ip = 100
time_window = 60
block_duration = 300GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD /*- Proxied requests to backendGET /__captcha_verify- CAPTCHA verification endpoint
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.
python -m pytest tests/logs/waf.log- Main application logslogs/honeypot.log- Detailed attack forensics
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
}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
- Pattern Matching: Regex-based attack detection
- Keyword Analysis: Suspicious parameter detection
- Encoding Validation: Obfuscated attack prevention
- Length Limits: Buffer overflow prevention
- Header Validation: Injection attack prevention
- URL Similarity: Known attack pattern matching
- Circuit Breaker: Backend failure protection
- Rate Limiting: SYN flood prevention
- Fallback Responses: Graceful error handling
- Timeout Management: Request timeout controls
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.
- Fork the repository
- Create a feature branch
- Add tests for new features
- Ensure all tests pass
- Submit a pull request
MIT License - see LICENSE file for details.