import tkinter as tk
import os
import sys
import time
import threading
import netifaces
from scapy.all import *
from scapy.layers.l2 import ARP
from tkinter import messagebox
from scapy.layers.l2 import get_mac_address

class ArpDetector:
    '''
    ARP欺骗检测类

    通过发送ARP请求并分析响应来检测ARP欺骗攻击。
    '''
    def __init__(self, interface):
        self.interface = interface
        self.ip_mac_map = {}
        self.attacker_ip = None
        self.attacker_mac = None
        self.thread = None
        self.stop_event = threading.Event()

    def start(self):
        '''启动ARP欺骗检测线程'''
        self.thread = threading.Thread(target=self.run)
        self.thread.start()

    def stop(self):
        '''停止ARP欺骗检测线程'''
        self.stop_event.set()
        self.thread.join()

    def run(self):
        '''ARP欺骗检测线程主函数'''
        self.attacker_ip = netifaces.ifaddresses(self.interface)[netifaces.AF_INET][0]['addr']
        self.attacker_mac = get_mac_address(ip=self.attacker_ip)
        print(f'攻击者IP: {self.attacker_ip}, MAC: {self.attacker_mac}')

        while not self.stop_event.is_set():
            self.scan_network()
            self.detect_arp_spoofing()
            time.sleep(5)

    def scan_network(self):
        '''扫描网络,获取IP地址和MAC地址的对应关系'''
        for ip in netifaces.ifaddresses(self.interface)[netifaces.AF_INET][0]['addr'].split('.')[:-1]:
            for i in range(1, 255):
                target_ip = f'{ip}.{i}'
                if target_ip != self.attacker_ip:
                    arp_request = ARP(pdst=target_ip)
                    arp_reply = sr1(arp_request, timeout=1, verbose=0)
                    if arp_reply and arp_reply.hwsrc not in ('00:00:00:00:00:00', self.attacker_mac):
                        self.ip_mac_map[target_ip] = arp_reply.hwsrc

    def detect_arp_spoofing(self):
        '''检测ARP欺骗攻击'''
        for target_ip, target_mac in self.ip_mac_map.items():
            arp_request = ARP(op=1, pdst=target_ip, hwdst=target_mac, psrc=self.attacker_ip, hwsrc=self.attacker_mac)
            arp_reply = sr1(arp_request, timeout=1, verbose=0)
            if arp_reply and arp_reply.hwsrc != target_mac:
                print(f'检测到ARP欺骗攻击: {target_ip} ({target_mac}) -> {arp_reply.hwsrc}')

class IcmpFloodDetector:
    '''
    ICMP洪水攻击检测类

    通过统计单位时间内接收到的ICMP数据包数量来检测ICMP洪水攻击。
    '''
    def __init__(self, interface):
        self.interface = interface
        self.attacker_ip = None
        self.thread = None
        self.stop_event = threading.Event()

    def start(self):
        '''启动ICMP洪水攻击检测线程'''
        self.thread = threading.Thread(target=self.run)
        self.thread.start()

    def stop(self):
        '''停止ICMP洪水攻击检测线程'''
        self.stop_event.set()
        self.thread.join()

    def run(self):
        '''ICMP洪水攻击检测线程主函数'''
        self.attacker_ip = netifaces.ifaddresses(self.interface)[netifaces.AF_INET][0]['addr']
        print(f'攻击者IP: {self.attacker_ip}')

        while not self.stop_event.is_set():
            self.detect_icmp_flood()
            time.sleep(5)

    def detect_icmp_flood(self):
        '''检测ICMP洪水攻击'''
        icmp_packets = sniff(filter=f'icmp and src host {self.attacker_ip}', timeout=1, count=10)
        if len(icmp_packets) == 10:
            print('检测到ICMP洪水攻击')

class TcpAttackDetector:
    '''
    TCP攻击检测类

    通过统计单位时间内接收到的TCP数据包数量来检测TCP攻击,如SYN Flood攻击。
    '''
    def __init__(self, interface):
        self.interface = interface
        self.attacker_ip = None
        self.thread = None
        self.stop_event = threading.Event()

    def start(self):
        '''启动TCP攻击检测线程'''
        self.thread = threading.Thread(target=self.run)
        self.thread.start()

    def stop(self):
        '''停止TCP攻击检测线程'''
        self.stop_event.set()
        self.thread.join()

    def run(self):
        '''TCP攻击检测线程主函数'''
        self.attacker_ip = netifaces.ifaddresses(self.interface)[netifaces.AF_INET][0]['addr']
        print(f'攻击者IP: {self.attacker_ip}')

        while not self.stop_event.is_set():
            self.detect_tcp_attack()
            time.sleep(5)

    def detect_tcp_attack(self):
        '''检测TCP攻击'''
        tcp_packets = sniff(filter=f'tcp and src host {self.attacker_ip}', timeout=1, count=10)
        if len(tcp_packets) == 10:
            print('检测到TCP攻击')

class NetworkScanner:
    '''
    网络扫描类

    扫描网络并获取所有在线设备的IP地址和MAC地址。
    '''
    def __init__(self, interface):
        self.interface = interface
        self.ip_mac_map = {}
        self.thread = None
        self.stop_event = threading.Event()

    def start(self):
        '''启动网络扫描线程'''
        self.thread = threading.Thread(target=self.run)
        self.thread.start()

    def stop(self):
        '''停止网络扫描线程'''
        self.stop_event.set()
        self.thread.join()

    def run(self):
        '''网络扫描线程主函数'''
        while not self.stop_event.is_set():
            self.scan_network()
            time.sleep(10)

    def scan_network(self):
        '''扫描网络'''
        for ip in netifaces.ifaddresses(self.interface)[netifaces.AF_INET][0]['addr'].split('.')[:-1]:
            for i in range(1, 255):
                target_ip = f'{ip}.{i}'
                if target_ip not in self.ip_mac_map:
                    arp_request = ARP(pdst=target_ip)
                    arp_reply = sr1(arp_request, timeout=1, verbose=0)
                    if arp_reply and arp_reply.hwsrc not in ('00:00:00:00:00:00', 'ff:ff:ff:ff:ff:ff'):
                        self.ip_mac_map[target_ip] = arp_reply.hwsrc
                        print(f'发现设备: {target_ip} ({arp_reply.hwsrc})')
                        self.save_to_file(target_ip, arp_reply.hwsrc)

    def save_to_file(self, ip, mac):
        '''将扫描结果保存到文件'''
        with open('network_scan.txt', 'a') as f:
            f.write(f'{ip},{mac}\n')

class LoginWindow:
    '''
    登录窗口类

    提供用户名和密码验证功能,验证通过后进入主界面。
    '''
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('登录')
        self.root.geometry('300x150')

        tk.Label(self.root, text='用户名').place(x=50, y=30)
        self.username_entry = tk.Entry(self.root)
        self.username_entry.place(x=120, y=30)

        tk.Label(self.root, text='密码').place(x=50, y=60)
        self.password_entry = tk.Entry(self.root, show='*')
        self.password_entry.place(x=120, y=60)

        self.login_button = tk.Button(self.root, text='登录', command=self.login)
        self.login_button.place(x=100, y=100)

        self.register_button = tk.Button(self.root, text='注册', command=self.register)
        self.register_button.place(x=170, y=100)

        self.root.mainloop()

    users = {'username': 'admin', 'password': 'admin'}

    def login(self):
        '''登录验证'''
        username = self.username_entry.get()
        password = self.password_entry.get()
        if username == self.users['username'] and password == self.users['password']:
            # 登录成功,跳转到主界面
            self.show_main_window()
            return
        # 登录失败,弹出错误提示
        messagebox.showinfo('错误', '用户名或密码错误')

    def register(self):
        '''注册新用户'''
        username = self.username_entry.get()
        password = self.password_entry.get()
        if username == self.users['username']:
            # 用户名已存在,弹出错误提示
            messagebox.showerror('错误', '用户名已存在')
            return
        # 用户名不存在,将新用户添加到用户列表中
        self.users['username'] = username
        self.users['password'] = password
        # 注册成功,弹出成功提示
        messagebox.showinfo('提示', '注册成功,请登录')

    def show_main_window(self):
        '''显示主界面'''
        self.root.destroy()
        MainWindow()

class MainWindow:
    '''
    主界面类

    提供启动和停止网络安全检测功能的按钮,并显示检测状态。
    '''
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('网络安全检测系统')
        self.root.geometry('400x300')

        self.status_label = tk.Label(self.root, text='空闲')
        self.status_label.pack()

        self.start_button = tk.Button(self.root, text='启动', command=self.start_detection)
        self.start_button.pack()

        self.stop_button = tk.Button(self.root, text='停止', command=self.stop_detection, state=tk.DISABLED)
        self.stop_button.pack()

        self.root.mainloop()

    def start_detection(self):
        '''启动网络安全检测'''
        self.status_label.config(text='运行中')
        self.start_button.config(state=tk.DISABLED)
        self.stop_button.config(state=tk.NORMAL)

        self.arp_detector = ArpDetector('ens33')
        self.arp_detector.start()

        self.icmp_flood_detector = IcmpFloodDetector('ens33')
        self.icmp_flood_detector.start()

        self.tcp_attack_detector = TcpAttackDetector('ens33')
        self.tcp_attack_detector.start()

        self.network_scanner = NetworkScanner('ens33')
        self.network_scanner.start()

    def stop_detection(self):
        '''停止网络安全检测'''
        self.status_label.config(text='空闲')
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)

        self.arp_detector.stop()
        self.icmp_flood_detector.stop()
        self.tcp_attack_detector.stop()
        self.network_scanner.stop()

if __name__ == '__main__':
    login_window = LoginWindow()
    # main_window = MainWindow()

原文地址: https://www.cveoy.top/t/topic/jnUa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录