import os
import subprocess
import socket
import requests
blocked_ips = {}
blocked_websites = {}
blocked_applications = {}
def add_ip_to_block(ip, port):
    if (ip, port) in blocked_ips:
        print(f"IP {ip} with port {port} is already blocked")
        return
    if is_ip_port_in_hosts(ip, port):
        print(f"IP {ip} with port {port} is already in block list.")
        return
    blocked_ips[(ip, port)] = True
    print(f"Added {ip} with port {port} to blocked IPs")
def remove_ip_from_block(ip, port):
    if (ip, port) in blocked_ips:
        del blocked_ips[(ip, port)]
        print(f"Unblocked {ip} with port {port}")
    else:
        print(f"IP {ip} with port {port} is not blocked")
def add_website_to_block(website):
    if website in blocked_websites:
        print(f"{website} is already blocked")
        return
    try:
        ip = socket.gethostbyname(website)
        if is_website_in_hosts(website):
            print(f"{website} is already in block list.")
            return
        dns_servers = get_dns_servers(website)
        blocked_websites[website] = {'ip': ip, 'dns_servers': dns_servers}
        block_website_on_system(website)
        print(f"Blocked {website} on the system")
    except socket.gaierror:
        print(f"Cannot resolve DNS for {website}")
def remove_website_from_block(website):
    if website in blocked_websites:
        del blocked_websites[website]
        unblock_website_on_system(website)
        print(f"Unblocked {website} on the system")
    else:
        print(f"{website} is not blocked")
def add_application_to_block(application):
    if application in blocked_applications:
        print(f"{application} is already blocked")
        return
    blocked_applications[application] = True
    print(f"Blocked connections for application: {application}")
def remove_application_from_block(application):
    if application in blocked_applications:
        del blocked_applications[application]
        print(f"Unblocked connections for application: {application}")
    else:
        print(f"{application} is not blocked")
def is_website_in_hosts(website):
    with open('/etc/hosts', 'r') as hosts_file:
        for line in hosts_file:
            if website in line:
                return True
    return False
def is_ip_port_in_hosts(ip, port):
    with open('/etc/hosts', 'r') as hosts_file:
        for line in hosts_file:
            if f"{ip}:{port}" in line:
                return True
    return False
def check_ip_availability(ip):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex((ip, 80))
    sock.close()
    return result == 0
def get_dns_servers(website):
    url = f"https://whois.domaintools.com/{website}"
    response = requests.get(url)
    dns_servers = []
    if response.status_code == 200:
        content = response.text
        start_marker = "<td>DNS</td>"
        end_marker = "</td>"
        start_index = content.find(start_marker)
        if start_index != -1:
            end_index = content.find(end_marker, start_index + len(start_marker))
            if end_index != -1:
                dns_servers = content[start_index + len(start_marker):end_index].split("<br>")
    return dns_servers
def block_website_on_system(website):
    with open('/etc/hosts', 'a') as hosts_file:
        hosts_file.write(f"\n# Blocked Websites\n")
        hosts_file.write(f"0.0.0.0 {website}\n")  # Redirect website to non-existent IP
def unblock_website_on_system(website):
    lines = []
    with open('/etc/hosts', 'r') as hosts_file:
        lines = hosts_file.readlines()
    with open('/etc/hosts', 'w') as hosts_file:
        blocklist_started = False
        for line in lines:
            if line.strip() == "# Blocked Websites":
                blocklist_started = True
            elif blocklist_started and line.strip() == "":
                blocklist_started = False
            if not (blocklist_started and line.startswith(f"0.0.0.0 {website}")):
                hosts_file.write(line)
def show_blocked_ips():
    print("Blocked IPs with specific ports:")
    for ip, port in blocked_ips.keys():
        print(f"{ip}:{port}")
def show_blocked_websites():
    print("Blocked Websites:")
    for website in blocked_websites.keys():
        print(website)
def show_blocked_applications():
    print("Blocked Applications:")
    for application in blocked_applications.keys():
        print(application)
def show_blacklist_items():
    show_blocked_ips()
    show_blocked_websites()
    show_blocked_applications()
if __name__ == "__main__":
    while True:
        print("\n========== Firewall Management ==========")
        print("1. Add IP with specific port to Block")
        print("2. Add Website to Block")
        print("3. Add Application to Block Connection (Internet)")
        print("4. Remove IP with specific port from Block")
        print("5. Remove Website from Block")
        print("6. Remove Application from Block")
        print("7. Show Blacklist Items")
        print("8. Exit")
        print("=========================================")
        choice = input("Enter your choice: ")
        if choice == '1':
            ip = input("Enter IP to block: ")
            port = input("Enter port to block: ")
            add_ip_to_block(ip, port)
        elif choice == '2':
            website = input("Enter website to block: ")
            add_website_to_block(website)
        elif choice == '3':
            application = input("Enter application to block: ")
            add_application_to_block(application)
        elif choice == '4':
            ip = input("Enter IP to unblock: ")
            port = input("Enter port to unblock: ")
            remove_ip_from_block(ip, port)
        elif choice == '5':
            website = input("Enter website to unblock: ")
            remove_website_from_block(website)
        elif choice == '6':
            application = input("Enter application to unblock: ")
            remove_application_from_block(application)
        elif choice == '7':
            show_blacklist_items()
        elif choice == '8':
            print("Exiting...")
            break
        else:
            print("Invalid choice")
Comments
Post a Comment