BoloBolo Crew
🐍 Below is an example of an advanced firewall implemented in Python.
This script uses the socket and psutil modules to monitor and control network connections.
It allows or blocks traffic based on predefined rules chosen by you.
#!/usr/bin/env python3
import socket
import psutil
# Define firewall rules (Allow or Block IPs and Ports)
firewall_rules = {
"allow": [("192.168.1.100", 80), ("127.0.0.1", 8000)], # Example: Allow localhost and a specific IP
"block": [("192.168.1.200", 22)], # Example: Block SSH access to a specific IP
}
def is_allowed_connection(ip, port):
"""
Checks if the given IP and port match the allow or block rules.
"""
if (ip, port) in firewall_rules["block"]:
return False
if (ip, port) in firewall_rules["allow"]:
return True
# Default policy: Deny everything not explicitly allowed
return False
def monitor_connections():
"""
Monitors active network connections and enforces firewall rules.
"""
print("Firewall is running. Monitoring connections...\n")
while True:
# Iterate through all current connections
for conn in psutil.net_connections(kind="inet"):
laddr = conn.laddr # Local address (IP, port)
raddr = conn.raddr # Remote address (IP, port)
status = conn.status
if raddr: # Only monitor connections with a remote address
remote_ip, remote_port = raddr
if not is_allowed_connection(remote_ip, remote_port):
print(f"Blocked: {remote_ip}:{remote_port} (status: {status})")
terminate_connection(conn.pid)
else:
print(f"Allowed: {remote_ip}:{remote_port} (status: {status})")
def terminate_connection(pid):
"""
Terminates a process by its PID.
"""
try:
psutil.Process(pid).terminate()
print(f"Terminated process {pid} to block connection.")
except Exception as e:
print(f"Error terminating process {pid}: {e}")
if __name__ == "__main__":
try:
monitor_connections()
except KeyboardInterrupt:
print("\nFirewall stopped.")
First install psutil
and make the script executable.
So write in your terminal
$ pip install psutil
$ chmod +x python_advanced_firewall.py
When the firewall is running on your system you should see output similar to this.
Firewall is running. Monitoring connections...
Allowed: 192.168.1.100:80 (status: ESTABLISHED)
Blocked: 192.168.1.200:22 (status: ESTABLISHED)
Terminated process 12345 to block connection.
Allowed: 127.0.0.1:8000 (status: LISTEN)
Blocked: 203.0.113.42:443 (status: ESTABLISHED)
Terminated process 67890 to block connection.
Allowed: 10.0.0.5:8080 (status: ESTABLISHED)
Now your system is protected 🫡. Good work 👋.