该 Python 代码实现了检测 ARP 攻击的功能,并且能够记录攻击源 IP 地址、MAC 地址和伪造源 MAC 地址。

代码使用 sniff 函数监听网络流量,并分析 ARP 协议包以识别攻击行为。

当检测到攻击源时,代码会弹出警告窗口,并将检测结果记录在 'detection_log.txt' 文件中。

代码示例

def detect_attack():
    with open('clients.txt', 'r') as f:
        clients = f.readlines()
        for client in clients:
            ip = client.split()[0]
            mac = get_mac(ip)
            sniff_filter = 'arp and src host ' + ip
            sniff_timeout = 10
            sniff_count = 0
            sniff_packets = sniff(filter=sniff_filter, timeout=sniff_timeout)
            for packet in sniff_packets:
                sniff_count += 1
                if packet.haslayer(ARP) and packet[ARP].op == 2:  # 判断是否为ARP响应包
                    src_mac = packet[ARP].hwsrc  # 获取源MAC地址
                    dst_mac = packet[ARP].hwdst  # 获取目标MAC地址
                    if src_mac != get_mac(ip) and src_mac != '00:00:00:00:00:00':  # 判断是否存在伪造源MAC地址的情况
                        messagebox.showwarning('警告',
                                               '检测到伪造源攻击!攻击源IP地址为' + ip + ',MAC地址为' + mac + ',伪造源MAC地址为' + src_mac + '!')
                        with open('detection_log.txt', 'a') as f:
                            f.write(
                                '警告' + '检测到伪造源攻击!攻击源IP地址为' + ip + ',MAC地址为' + mac + ',伪造源MAC地址为' + src_mac + '!\n')
                        return
            if sniff_count > 100:
                messagebox.showwarning('警告', '检测到攻击源IP地址为' + ip + ',MAC地址为' + mac + '!')
                with open('detection_log.txt', 'a') as f:
                    f.write('警告' + '检测到攻击源IP地址为' + ip + ',MAC地址为' + mac + '!\n')
            else:
                messagebox.showinfo('提示', '未检测到攻击源!')
                with open('detection_log.txt', 'a') as f:
                    f.write('提示' + '未检测到攻击源!\n')
            return

优化建议

  1. 添加攻击时间记录: 在检测到攻击时记录攻击发生的具体时间,方便分析攻击趋势。
  2. 记录攻击类型: 记录攻击类型,例如伪造源攻击、ARP 欺骗等。
  3. 发送警报: 将检测到的攻击信息发送给安全管理员或其他相关人员,以便及时采取应急措施。
  4. 使用日志轮转机制: 避免 'detection_log.txt' 文件过大,可以使用日志轮转机制将日志文件分割成多个文件,方便管理和分析。
  5. 使用数据库: 可以将检测到的攻击信息存储在数据库中,方便查询和分析。
Python ARP 攻击检测脚本: 识别和记录攻击源

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

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