Simple DDoS/DoS Protection Firewall
A lightweight, educational firewall that demonstrates basic network attack detection and blocking mechanisms for Linux systems.
⚠️ Important Notice: This is an educational/proof-of-concept project. It provides basic protection against simple attacks but should NOT be used as a primary security solution in production environments.
Project Approach
This firewall uses a threshold-based detection approach:
- Packet Capture: Uses Scapy to monitor network packets in real-time
- Pattern Analysis: Counts packets, connections, and ports per IP address over time windows
- Threshold Comparison: Blocks IPs when activity exceeds predefined limits
- Automatic Blocking: Uses Linux iptables to drop traffic from malicious IPs
- Time-based Recovery: Automatically unblocks IPs after a timeout period
Detection Methods
- SYN Flood: Counts TCP SYN packets per IP per minute
- Port Scanning: Tracks unique ports accessed by each IP
- ICMP Flood: Monitors ICMP packet rates per IP
- Connection Flooding: Counts connection attempts per IP
- General Rate Limiting: Monitors overall packet rates per IP
Basic Features
🛡️ Simple Attack Detection:
- Basic SYN flood detection
- Elementary port scan detection
- ICMP flood monitoring
- Connection rate limiting
- Packet rate monitoring
🚫 Basic Protection:
- IP blocking via iptables (Linux only)
- Configurable detection thresholds
- Temporary blocking with auto-unblock
- IP whitelist support
- Basic logging
📊 Simple Monitoring:
- Real-time attack alerts
- Basic statistics display
- Simple log file output
Quick Start
Install dependencies:
pip install -r requirements.txt
Create configuration file:
python3 main.py --create-config
Start the firewall:
sudo python3 main.py
Note on Virtual Environments: When using a virtual environment (like venv), sudo does not use your virtual environment's path. You must provide the full path to the Python executable inside your venv folder. For example:
sudo ./venv/bin/python3 main.py
Test the firewall (in another terminal):
python3 test_attacks.py 127.0.0.1
🏃 Running on Windows
This program uses netsh to manage firewall rules, which requires administrative privileges.
Open as Administrator: Right-click on Command Prompt or Windows PowerShell and select "Run as administrator".
Navigate to Folder: Change to the project directory:
cd path\to\simple_firewall
(Optional) Activate Virtual Environment: If you use a virtual environment:
.\venv\Scripts\activate
Install Requirements: Install the main requirements and the Windows-specific ones:
pip install -r requirements.txt
pip install -r requirements-windows.txt
Run the Program:
python main.py -i "Your Interface Name"
# Example:
python main.py -i "Ethernet"
🍎 Running on macOS
This program uses pfctl (Packet Filter Control) to manage firewall rules, which requires administrative privileges.
Prerequisites
- macOS 10.5+
- Administrator privileges
- Python 3.6+
Setup Instructions
Open Terminal: Open the Terminal application (found in Applications > Utilities)
Navigate to Project Directory:
cd path/to/simple_firewall
(Optional) Create Virtual Environment:
python3 -m venv venv
source venv/bin/activate
Install Requirements:
pip install -r requirements.txt
Create Configuration File:
python3 main.py --create-config
Run the Firewall:
sudo python3 main.py
Or specify an interface:
sudo python3 main.py -i en0
macOS Firewall Management
The firewall uses pfctl to manage blocking rules:
Automatic Setup: On first run, the firewall automatically:
- Creates a
blocked_ips table in pfctl
- Enables pfctl if not already enabled
- Loads blocking rules from a temporary configuration file
Blocking Mechanism: IPs are added to a pfctl table, and rules block all traffic from/to those IPs
Automatic Cleanup: When the firewall stops, all blocked IPs are automatically removed
Managing pfctl Manually
If you need to manually manage the firewall:
# View currently blocked IPs
sudo pfctl -t blocked_ips -T show
# Remove a specific IP manually
sudo pfctl -t blocked_ips -T delete <IP_ADDRESS>
# Flush all blocked IPs
sudo pfctl -t blocked_ips -T flush
# Check pfctl status
sudo pfctl -s info
# View current rules
sudo pfctl -s rules
Troubleshooting macOS
Issue: "pfctl: command not found"
- This shouldn't happen on macOS, but if it does, ensure you're running a supported macOS version
Issue: "pfctl: Permission denied"
- Make sure you're running with
sudo
- Some macOS versions may require additional permissions
Issue: "pfctl: cannot enable"
- macOS System Preferences may have the built-in firewall enabled
- You may need to disable it in System Preferences > Security & Privacy > Firewall
- Or allow pfctl to run by granting Full Disk Access in System Preferences
Issue: Interface not found
- List available interfaces:
ifconfig or networksetup -listallhardwareports
- Common macOS interfaces:
en0 (Ethernet), en1 (Wi-Fi), en2 (USB Ethernet)
Issue: Blocks not working
- Check if pfctl is enabled:
sudo pfctl -s info
- Verify rules are loaded:
sudo pfctl -s rules
- Check if IPs are in the table:
sudo pfctl -t blocked_ips -T show
macOS-Specific Notes
- System Firewall: macOS has a built-in firewall in System Preferences. The Simple Firewall works alongside it but uses pfctl directly
- Interface Names: macOS uses names like
en0, en1, etc. (not eth0 like Linux)
- Root Access: Always run with
sudo for firewall operations
- Temporary Rules: The firewall creates temporary pf.conf files that are automatically managed
Usage
Basic Commands
# Show help and usage
python3 main.py --help
# Start firewall with default settings
sudo python3 main.py
# Monitor specific network interface
sudo python3 main.py -i eth0
# Use custom configuration file
sudo python3 main.py -c my_config.json
# Show network statistics
python3 main.py --stats
# Create sample configuration
python3 main.py --create-config
# Run with verbose logging
sudo python3 main.py -v
🐳 Running with Docker
Using Docker is the recommended way to run the firewall, as it automatically manages all dependencies and network permissions.
✅ Prerequisites
Make sure you have the following installed:
- Docker
- Docker Compose
(Docker Desktop for Windows/macOS includes both.)
1. Build and Run
Open your terminal in the project’s root directory and run:
docker-compose run --rm firewall
The image will build the first time you run this command.
--rm ensures the container is automatically removed when it stops.
2. Select Network Interface
After the container starts, you will be prompted to choose the interface:
Select an interface (0–2): 2
✅ To Stop
Press: Ctrl + C
Configuration
Edit firewall_config.json to customize thresholds:
{
"thresholds": {
"syn_flood_threshold": 100, // SYN packets per minute
"connection_threshold": 50, // Connections per IP per minute
"packet_rate_threshold": 1000, // Total packets per IP per minute
"port_scan_threshold": 20, // Different ports accessed per minute
"icmp_flood_threshold": 100 // ICMP packets per minute
},
"whitelist": [
"127.0.0.1", // Always allow localhost
"192.168.1.1" // Add trusted IPs here
],
"block_duration": 300, // Block duration in seconds (5 minutes)
"log_level": "INFO" // Logging level
}
Architecture & Implementation
New Modular Architecture (v2.0)
The firewall has been completely restructured into a modular, maintainable architecture:
🏗️ Key Benefits:
- ✅ Cross-Platform Ready: Framework for Windows/macOS support
- ✅ Testable: Comprehensive unit test coverage
- ✅ Maintainable: Single responsibility principle
- ✅ Extensible: Easy to add new features
- ✅ GUI-Ready: Clean separation for web dashboard
- ✅ Developer-Friendly: Clear code organization
🔧 Component Architecture:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ main.py │ │ Network │ │ Attack │
│ Entry Point │───▶│ Interface │───▶│ Detection │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │
▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Configuration │ │ Packet │ │ IP Blocking │
│ Management │ │ Handler │ │ (Cross-Platform)│
└─────────────────┘ └─────────────────┘ └─────────────────┘
Detection Algorithm (Threshold-Based Approach)
The firewall operates on a simple sliding window principle:
Data Collection Phase:
# For each IP address, track:
ip_packets[ip] = deque() # All packets with timestamps
ip_syn_packets[ip] = deque() # SYN packets only
ip_connections[ip] = deque() # Connection attempts
ip_ports[ip] = set() # Unique ports accessed
ip_icmp_packets[ip] = deque() # ICMP packets
Time Window Management:
- Uses 1-minute sliding windows for all detection
- Automatically removes data older than 60 seconds
- Resets port tracking every minute per IP
Threshold Evaluation:
# Example: SYN flood detection
if len(ip_syn_packets[ip]) > syn_flood_threshold:
block_ip(ip, "SYN flood detected")
Blocking Mechanism:
# Adds iptables rule to drop all traffic from IP
iptables -A INPUT -s [MALICIOUS_IP] -j DROP
Why This Approach Has Limitations:
- No Behavioral Learning: Cannot distinguish between legitimate bulk transfers and attacks
- Fixed Time Windows: All attacks use same 1-minute window regardless of attack type
- Simple Counting: No statistical analysis or anomaly detection
- No Context Awareness: Doesn't consider normal traffic patterns for each IP
- Memory Inefficient: Stores all packet timestamps instead of using rolling statistics
Attack Detection Workflow:
Packet Received → Extract IP → Update Counters → Check Thresholds → Block if Exceeded
↓ ↓ ↓ ↓ ↓
Scapy Capture → IP Analysis → Sliding Window → Threshold Compare → iptables Block
Project Structure
Core Files:
main.py - NEW: Modern entry point with comprehensive CLI
firewall_config.json - Configuration file with validation
firewall.log - Activity log file (auto-created)
requirements.txt - Python dependencies
Modular Source Code (src/):
src/
├── firewall/ # Core firewall components
│ ├── core.py # Main orchestration
│ ├── detection.py # Attack detection algorithms
│ ├── blocking.py # Cross-platform IP blocking
│ └── stats.py # Statistics tracking
├── config/ # Configuration management
│ ├── models.py # Data models & validation
│ └── loader.py # Config loading with templates
├── network/ # Network handling
│ ├── interface.py # Interface detection
│ └── packet_handler.py # Packet processing
└── utils/ # Utilities
├── logger.py # Logging system
└── system.py # System utilities
Testing & Tools:
tests/ - Comprehensive unit test suite
test_attacks.py - Attack simulation for testing
.github/ - GitHub workflows and documentation
Legacy Files:
simple_firewall_old.py - Original monolithic implementation (backup)
run.py - Legacy launcher (redirects to main.py)
Requirements
- Python 3.6+
- Root/Administrator privileges (required for firewall access)
- Supported Platforms:
- Linux: Uses iptables for blocking
- macOS: Uses pfctl (Packet Filter) for blocking
- Windows: Uses netsh (Windows Firewall) for blocking
Python Packages: