• Advertise
  • Support Center
Saturday, July 12, 2025
  • Login
  • Register
INNOCENT MICHAEL
  • HOME
  • MAIN CATEGORY
    • BREAKING NEWSUPDATES
      • BROWSE
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
      • USA NEWS
        • Browse News
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
      • CANADA NEWS
        • Browse News
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
      • UK NEWS
        • Browse News
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
      • NIGERIA NEWS
        • Browser News
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
    • WATCHVIDEOS
    • AUDIOPODCAST
    • BULLETIN
    • BUSINESS NEWS
    • CYBERSECURITY
    • ENTERTAINMENT
      • NEWS
    • TECHNOLOGY
      • TECH NEWS
      • HOMELAB
    • REDCARPET CHRONICLE
    • POLITICSNEWS
      • BROWSE
      • POLITICS NEWS (CA)
      • POLITICS NEWS (USA)
      • POLITICS NEWS (UK)
    • SPORTS
      • SPORTS UPDATE
      • AEW
      • WWE
  • SHOP
    • Browse Shop
  • QUICK LINKS
    • OUR PLATFORMS
  • LEGAL HUB
    • Wikipedia
    • ABOUT US
    • OUR EDITORIAL PHILOSOPY
Live TV Indicator
WATCH ONLINE TV
No Result
View All Result
INNOCENT MICHAEL
  • HOME
  • MAIN CATEGORY
    • BREAKING NEWSUPDATES
      • BROWSE
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
      • USA NEWS
        • Browse News
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
      • CANADA NEWS
        • Browse News
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
      • UK NEWS
        • Browse News
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
      • NIGERIA NEWS
        • Browser News
        • Local News
        • Breaking News
        • Society & Culture
        • Crisis & Controversy
        • Economy & Markets
        • Tech & Innovation
    • WATCHVIDEOS
    • AUDIOPODCAST
    • BULLETIN
    • BUSINESS NEWS
    • CYBERSECURITY
    • ENTERTAINMENT
      • NEWS
    • TECHNOLOGY
      • TECH NEWS
      • HOMELAB
    • REDCARPET CHRONICLE
    • POLITICSNEWS
      • BROWSE
      • POLITICS NEWS (CA)
      • POLITICS NEWS (USA)
      • POLITICS NEWS (UK)
    • SPORTS
      • SPORTS UPDATE
      • AEW
      • WWE
  • SHOP
    • Browse Shop
  • QUICK LINKS
    • OUR PLATFORMS
  • LEGAL HUB
    • Wikipedia
    • ABOUT US
    • OUR EDITORIAL PHILOSOPY
  • Login
  • Register
No Result
View All Result
INNOCENT MICHAEL
Home Cybersecurity Tips
Build Your Own Custom Dynamic Firewall with Python and Scapy

Build Your Own Custom Dynamic Firewall with Python and Scapy

in Cybersecurity Tips, Hackers, Tech
0
Share on FacebookShare On Whatsapp

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

  1. Add Logging:
    • Record scan attempts and blocked IPs in a log file for further analysis.
  2. White-list Trusted IPs:
    • Implement a white-list to prevent blocking known safe IPs.
  3. Improve Reporting:
    • Set up email or webhook notifications for critical events.

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].


Share6SendTweet4Share1Share

Related Posts

The UK’s phone theft crisis is a wake-up call for digital security
Hackers

The UK’s phone theft crisis is a wake-up call for digital security

April 19, 2025
36
7 Clever Ways to Reuse Your Old Windows 10 PC
Tech

7 Clever Ways to Reuse Your Old Windows 10 PC

April 19, 2025
25
Why I Auto-Backup Photos to Proton Drive (5 Strong Reasons)
Data Security

Why I Auto-Backup Photos to Proton Drive (5 Strong Reasons)

April 10, 2025
48
AI Offensive Security: RamiGPT Gains Root in Under a Minute
AI

AI Offensive Security: RamiGPT Gains Root in Under a Minute

April 1, 2025
44
Tor Browser 14.0.8: Urgent Security Update for Windows Users
Apps

Tor Browser 14.0.8: Urgent Security Update for Windows Users

April 1, 2025
29
Pocket Card Users Under Attack Via Sophisticated Phishing Campaign
Cyber Threats

Phishing Pandemic: Pocket Card Clients Face Serious Threat

March 25, 2025
46
Subscribe
Login
Notify of
guest
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
video
play-rounded-fill

Stay Updated

Subscribe to our newsletter and be the first to receive updates, tips, and exclusive offers straight to your inbox.

Haysuite Haysuite Haysuite
The UK’s phone theft crisis is a wake-up call for digital security
Hackers

The UK’s phone theft crisis is a wake-up call for digital security

April 19, 2025
36
7 Clever Ways to Reuse Your Old Windows 10 PC
Tech

7 Clever Ways to Reuse Your Old Windows 10 PC

April 19, 2025
25
8 Proven Ways to Clear Clipboard on Windows 11 Safely
Windows

8 Proven Ways to Clear Clipboard on Windows 11 Safely

April 18, 2025
18
What to Do When Ransomware Hits: Pay or Prepare?
Ransomware

What to Do When Ransomware Hits: Pay or Prepare?

April 18, 2025
14
Meta Resumes EU AI Training: Why Europe’s Data Matters
AI

Meta Resumes EU AI Training: Why Europe’s Data Matters

April 16, 2025
25

© 2024 Innocent Michael Network Inc..

  • Wikipedia
  • CRM
  • Submit Your Article
  • Support
  • Legal
Menu
  • Wikipedia
  • CRM
  • Submit Your Article
  • Support
  • Legal

Welcome Back!

Sign In with Facebook
Sign In with Google
Sign In with Linked In
OR

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Sign Up with Facebook
Sign Up with Google
Sign Up with Linked In
OR

Fill the forms below to register

*By registering into our website, you agree to the Terms & Conditions and Privacy Policy.
All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

No Result
View All Result
  • Login
  • Sign Up
Live TV Indicator
WATCH ONLINE TV
  • HOME
  • BROWSE
    • WATCH
    • AUDIO
    • BULLETIN
    • BUSINESS NEWS
    • CYBERSECURITY
    • TECHNOLOGY
      • TECH NEWS
      • HOMELAB
    • REDCARPET CHRONICLE
  • NEWS
    • GLOBAL NEWS
    • USA NEWS
    • CANADA NEWS
    • UK NEWS
    • NIGERIA NEWS
  • POLITICS
    • POLITICS NEWS (GLOBAL)
    • POLITICS NEWS (CA)
    • POLITICS NEWS (USA)
    • POLITICS NEWS (UK)
  • SPORTS NEWS
    • SPORTS NEWS (GLOBAL)
    • AEW NEWS
    • SOCCER NEWS
    • WWE NEWS
  • SHOP
  • QUICK LINKS
  • LEGAL HUB

Copyright © 2024 INNOCENT MICHAEL NETWORK INC.

wpDiscuz
0
0
Would love your thoughts, please comment.x
()
x
| Reply