Python打造ARP攻击检测工具: 从原理到实战代码

本文将使用Python和强大的网络库Scapy,带你从零开始,打造一款能够检测ARP欺骗攻击的软件。

一、ARP欺骗攻击原理

ARP(地址解析协议)负责将IP地址解析为MAC地址。攻击者利用ARP协议的漏洞,发送伪造的ARP报文,将攻击目标的IP地址与攻击者控制的MAC地址绑定,从而拦截目标设备的网络流量,实现攻击目的。

二、Python实现ARP攻击检测

1. 获取局域网活动主机信息

首先,我们需要获取局域网内活动主机的MAC地址、IP地址以及ARP表信息。

  • 获取本机IP地址和MAC地址
import socket
import fcntl
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

def get_mac_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
    return ':'.join(['%02x' % ord(char) for char in info[18:24]])

ip_address = get_ip_address('eth0')
mac_address = get_mac_address('eth0')

print(f'本机IP地址: {ip_address}')
print(f'本机MAC地址: {mac_address}')
  • 获取ARP表
from scapy.all import ARP, Ether, srp

def get_arp_table(ip_range):
    arp = ARP(pdst=ip_range)
    ether = Ether(dst='ff:ff:ff:ff:ff:ff')
    packet = ether/arp
    result = srp(packet, timeout=3, verbose=0)[0]
    arp_table = []
    for sent, received in result:
        arp_table.append({'ip': received.psrc, 'mac': received.hwsrc})
    return arp_table

arp_table = get_arp_table('192.168.1.0/24')
print(f'ARP表: {arp_table}')

2. 检测ARP欺骗攻击

  • 监听ARP广播包
from scapy.all import ARP, sniff

def arp_monitor_callback(pkt):
    if ARP in pkt and pkt[ARP].op in (1,2): # who-has or is-at
        return pkt.sprintf('%ARP.hwsrc% %ARP.psrc%')

def start_arp_monitor():
    sniff(prn=arp_monitor_callback, filter='arp', store=0)
  • 判断ARP欺骗攻击
def arp_spoof_detect(pkt, arp_table):
    if ARP in pkt and pkt[ARP].op == 2: # is-at
        for entry in arp_table:
            if pkt[ARP].psrc == entry['ip'] and pkt[ARP].hwsrc != entry['mac']:
                print(f'检测到ARP欺骗攻击: {pkt[ARP].psrc} is-at {pkt[ARP].hwsrc}')

def start_arp_spoof_detect(arp_table):
    sniff(prn=lambda pkt: arp_spoof_detect(pkt, arp_table), filter='arp', store=0)

三、完整代码

import socket
import fcntl
import struct
from scapy.all import ARP, Ether, srp, sniff

# ... (上述代码)

if __name__ == '__main__':
    ip_address = get_ip_address('eth0')
    mac_address = get_mac_address('eth0')
    arp_table = get_arp_table('192.168.1.0/24')

    print(f'本机IP地址: {ip_address}')
    print(f'本机MAC地址: {mac_address}')
    print(f'ARP表: {arp_table}')

    # 启动ARP监控
    start_arp_monitor()
    # 启动ARP欺骗检测
    start_arp_spoof_detect(arp_table)

四、总结

本文介绍了使用Python实现ARP攻击检测的方法,并提供了完整的代码示例。你可以根据自身需求对代码进行修改和扩展,例如添加报警功能、记录攻击日志等。请注意,在实际应用中,还需要结合其他安全措施,才能构建更加完善的网络安全防御体系。

Python打造ARP攻击检测工具: 从原理到实战代码

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

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