基于 Linux 的 ARP 攻击检测软件设计与实现
基于 Linux 的 ARP 攻击检测软件设计与实现
本文介绍了一个基于 Linux 的 ARP 攻击检测软件的设计与实现,该软件使用 Python 语言编写,并利用 Scapy、Flask 和 SQLite3 等库实现。
功能包括:
- 能够获取局域网活动主机的 MAC 地址、IP 地址;
- 能够检测防护 ARP 攻击行为,并记录保存;
- 能够显示出 ARP 攻击源的 MAC 地址、IP 地址;
- 利用 Flask 框架实现可视化。
实现这个功能需要用到以下模块:
- scapy: 用于网络数据包的构造和分析
- flask: 用于 Web 应用的开发
- sqlite3: 用于数据库的操作
下面是代码实现:
- 获取局域网活动主机的 MAC 地址、IP 地址
import os
import sys
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].encode('utf-8'))
)[20:24])
def get_mac_address(ifname):
try:
mac = open('/sys/class/net/'+ifname+'/address').readline()
except:
mac = '00:00:00:00:00:00'
return mac[0:17]
def get_active_hosts():
hosts = []
for ifname in os.listdir('/sys/class/net'):
if ifname.startswith('eth') or ifname.startswith('en'):
ip = get_ip_address(ifname)
mac = get_mac_address(ifname)
hosts.append({'ip': ip, 'mac': mac})
return hosts
- 检测防护 ARP 攻击行为,并记录保存
from scapy.all import *
def arp_spoof_detect(pkt):
if pkt[ARP].op == 2: # ARP 响应
mac = pkt[ARP].hwsrc
ip = pkt[ARP].psrc
if mac != get_mac_address('eth0'): # 非本机 MAC 地址
if ip in [h['ip'] for h in get_active_hosts()]: # 局域网内的 IP 地址
if mac != [h['mac'] for h in get_active_hosts() if h['ip'] == ip][0]: # MAC 地址不一致
return (ip, mac)
def arp_spoof_detect_loop():
while True:
sniff(prn=arp_spoof_detect, filter='arp', store=0)
def save_arp_spoof(ip, mac):
conn = sqlite3.connect('arp_spoof.db')
c = conn.cursor()
c.execute('INSERT INTO arp_spoof VALUES (?, ?, ?)', (datetime.now(), ip, mac))
conn.commit()
conn.close()
- 显示出 ARP 攻击源的 MAC 地址、IP 地址
def get_arp_spoof():
conn = sqlite3.connect('arp_spoof.db')
c = conn.cursor()
c.execute('SELECT * FROM arp_spoof')
rows = c.fetchall()
conn.close()
return rows
- 利用 Flask 框架实现可视化
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', active_hosts=get_active_hosts(), arp_spoof=get_arp_spoof())
if __name__ == '__main__':
app.run(debug=True)
最后,可以将以上代码整合在一个文件中,例如 app.py,然后在命令行中运行 python app.py 启动应用程序。在浏览器中访问 http://localhost:5000/ 即可查看可视化界面。
原文地址: https://www.cveoy.top/t/topic/jnQJ 著作权归作者所有。请勿转载和采集!