Ever wondered how to secure your network dynamically by detecting and blocking suspicious activity? Creating a custom dynamic firewall using Python and Scapy offers a practical way to enhance your cybersecurity skills while protecting your network from unauthorized access.
This guide walks you through building a dynamic firewall capable of detecting malicious scans, responding with a “Try Harder” message, and blocking attackers in real time.
What Is a Dynamic Firewall?
A dynamic firewall actively monitors network traffic to detect and respond to suspicious activity. Unlike traditional firewalls with static rules, dynamic firewalls adapt based on real-time analysis, making them effective against evolving threats.
Why Build a Custom Firewall?
- Hands-On Learning: Strengthen your understanding of networking and cybersecurity.
- Enhanced Protection: Block port scans and unauthorized access attempts automatically.
- Custom Responses: Send personalized messages to attackers before blocking them.
Tools and Requirements
To build your dynamic firewall, you’ll need:
- Linux OS: Preferably Ubuntu or Debian.
- Python 3: For scripting.
- Scapy Library: For packet crafting and sniffing.
- iptables: For managing network rules.
- Root Access: Required for packet sniffing and firewall rule changes.
Step-by-Step Guide to Building Your Dynamic Firewall
1. Install Necessary Tools
Start by installing the required tools and libraries:
sudo apt update
sudo apt install python3 python3-pip iptables -y
pip install scapy
2. Create Your Python Firewall Script
Create a new script file:
mkdir ~/firewall && cd ~/firewall
nano firewall.py
Paste the following code into firewall.py
:
#!/usr/bin/env python3
from scapy.all import sniff, IP, TCP, send
import subprocess
import time
# Configuration
BLOCK_DURATION = 600 # Duration to block IPs (in seconds)
THRESHOLD = 5 # Number of scans before blocking
scan_count = {} # Track scan attempts per IP
blocked_ips = {} # Track blocked IPs with timestamps
def block_ip(ip):
"""Block an IP using iptables."""
if ip not in blocked_ips:
print(f"[BLOCK] Blocking IP: {ip}")
subprocess.run(["iptables", "-A", "INPUT", "-s", ip, "-j", "DROP"])
blocked_ips[ip] = time.time()
def unblock_ip():
"""Unblock IPs after the block duration expires."""
current_time = time.time()
for ip, timestamp in list(blocked_ips.items()):
if current_time - timestamp > BLOCK_DURATION:
print(f"[UNBLOCK] Unblocking IP: {ip}")
subprocess.run(["iptables", "-D", "INPUT", "-s", ip, "-j", "DROP"])
del blocked_ips[ip]
def monitor_packet(packet):
"""Monitor incoming packets for suspicious activity."""
if TCP in packet and packet[TCP].flags == "S":
src_ip = packet[IP].src
dst_port = packet[TCP].dport
print(f"[SCAN DETECTED] IP: {src_ip} targeting Port: {dst_port}")
scan_count[src_ip] = scan_count.get(src_ip, 0) + 1
if scan_count[src_ip] > THRESHOLD:
print(f"[TRY HARDER] Excessive scans detected from {src_ip}")
spoofed_packet = IP(dst=src_ip, src=packet[IP].dst) / \
TCP(dport=packet[TCP].sport, sport=dst_port, flags="PA") / \
"Try Harder"
send(spoofed_packet, verbose=0)
block_ip(src_ip)
def start_firewall():
"""Start monitoring network traffic."""
print("[FIREWALL STARTED] Monitoring traffic for malicious activity...")
try:
sniff(filter="tcp", prn=monitor_packet, store=0)
except KeyboardInterrupt:
print("\n[STOPPING FIREWALL]")
unblock_ip()
if __name__ == "__main__":
while True:
unblock_ip() # Periodically unblock expired IPs
start_firewall()
3. Run the Firewall Script
Run the script with root privileges:
sudo python3 firewall.py
How It Works
- Monitoring Traffic: Sniffs TCP packets to detect SYN flags commonly used in port scans.
- Suspicious Behavior Detection: Tracks the number of SYN packets from each IP and flags them as malicious once they exceed the threshold.
- Blocking Attackers: Uses
iptables
to block flagged IPs dynamically. - Sending Custom Messages: Sends a spoofed “Try Harder” message to the attacker before blocking.
- Automatic Unblocking: Unblocks IPs after the specified duration.
Testing Your Firewall
Simulate a port scan using nmap from another device:
nmap -sS <target-ip>
Watch the firewall log for messages like:
[SCAN DETECTED]
[TRY HARDER]
[BLOCK]
Advanced Enhancements
- Add Logging:
- Record scan attempts and blocked IPs in a log file for further analysis.
- White-list Trusted IPs:
- Implement a white-list to prevent blocking known safe IPs.
- Improve Reporting:
Security Best Practices
- Test in a Controlled Environment: Always test scripts in a non-production environment first.
- Keep the System Updated: Regular updates minimize vulnerabilities.
- Monitor and Review Logs: Regularly analyze logs for patterns and improvements.
Conclusion
Building a custom dynamic firewall not only strengthens your network’s security but also provides valuable hands-on experience with cybersecurity concepts. With Python and Scapy, you can efficiently detect, respond to, and block malicious activity while staying ahead of evolving threats.
For more detailed guides and cybersecurity tips, visit innocentmichael.org or email us at [email protected].