0% found this document useful (0 votes)
25 views3 pages

Smart Firewall - Py

This document outlines a Python script for a Smart AI Firewall that monitors network packets and blocks potential threats based on predefined rules. It includes functionalities for logging, updating firewall rules from a cloud source, and a graphical user interface for displaying activity logs. The script also features automatic startup registration on Windows systems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views3 pages

Smart Firewall - Py

This document outlines a Python script for a Smart AI Firewall that monitors network packets and blocks potential threats based on predefined rules. It includes functionalities for logging, updating firewall rules from a cloud source, and a graphical user interface for displaying activity logs. The script also features automatic startup registration on Windows systems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import os

import time
import json
import socket
import threading
from tkinter import *
from tkinter import scrolledtext
from [Link] import sniff, IP, TCP, UDP
import requests

# -------- SETTINGS --------


FIREWALL_RULES_FILE = "[Link]"
CLOUD_RULES_URL = "[Link] # Simulated source
LOG_FILE = "firewall_log.txt"
AUTO_UPDATE_INTERVAL = 300 # in seconds

# -------- PLACEHOLDER AI DETECTION (replace with real ML model) --------


def is_threat(packet):
# Simulated logic (Replace this with ML inference)
if [Link](IP):
ip = packet[IP].src
if [Link]("192.168."):
return False
if [Link](TCP) and packet[TCP].dport == 80:
return True
return False

# -------- PACKET HANDLING --------


def handle_packet(packet):
if is_threat(packet):
log_threat(packet)
block_ip(packet[IP].src)

def block_ip(ip):
[Link](f"netsh advfirewall firewall add rule name=\"Block {ip}\" dir=in
action=block remoteip={ip}")
append_log(f"[BLOCKED] IP: {ip}")

def log_threat(packet):
with open(LOG_FILE, "a") as f:
[Link](str([Link]()) + "\n")

def append_log(msg):
timestamp = [Link]("%Y-%m-%d %H:%M:%S")
full = f"{timestamp} - {msg}"
print(full)
if gui_textbox:
gui_textbox.insert(END, full + "\n")
gui_textbox.yview(END)

# -------- GUI --------


gui_textbox = None

def start_gui():
global gui_textbox
win = Tk()
[Link]("Smart AI Firewall")
[Link]("600x400")
Label(win, text="Firewall Activity Log").pack()
gui_textbox = [Link](win, wrap=WORD)
gui_textbox.pack(expand=True, fill='both')

Button(win, text="Force Rule Update",


command=update_rules_from_cloud).pack(pady=5)
[Link]()

# -------- RULE MANAGEMENT --------


def load_local_rules():
if [Link](FIREWALL_RULES_FILE):
with open(FIREWALL_RULES_FILE, "r") as f:
return [Link](f)
return []

def update_rules_from_cloud():
try:
# Simulate cloud download (replace with actual URL)
response = [Link](CLOUD_RULES_URL, timeout=10)
if response.status_code == 200:
with open(FIREWALL_RULES_FILE, "w") as f:
[Link]([Link])
append_log("[RULES UPDATED] Successfully downloaded new rules.")
else:
append_log("[ERROR] Failed to update rules from cloud.")
except Exception as e:
append_log(f"[ERROR] Cloud rule update failed: {e}")

def auto_update_rules():
while True:
update_rules_from_cloud()
[Link](AUTO_UPDATE_INTERVAL)

# -------- PACKET SNIFFING --------


def packet_sniffer():
sniff(filter="ip", prn=handle_packet, store=0)

# -------- WINDOWS SERVICE (RUN ALWAYS) --------


def register_startup():
try:
import winreg
file_path = [Link](__file__)
key = [Link](winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run",
0, winreg.KEY_SET_VALUE)
[Link](key, "SmartFirewall", 0, winreg.REG_SZ, file_path)
[Link](key)
append_log("[INFO] Auto-startup registered.")
except Exception as e:
append_log(f"[ERROR] Failed to register startup: {e}")

# -------- MAIN --------


def main():
register_startup()
[Link](target=packet_sniffer, daemon=True).start()
[Link](target=auto_update_rules, daemon=True).start()
start_gui()

if __name__ == "__main__":
main()

You might also like