import netifaces
import queue,re
import pyshark, threading
from scapy.all import *
#设定匹配关键词
kewords = ['www.baidu.com','mp.csdn.net','']
#枚举网络接口
def net_list():
nets = netifaces.interfaces()
def net_detail(net):
return netifaces.ifaddresses(net)
return nets
#设用传输和接受队列
q = queue.Queue()
#解析数据包
def load_net(interface):
while 1:
while not q.empty():
capture = q.get()
print('loadt: ',time.time())
fields = {}
for i in range(len(list(capture))):
try:
fields.update({'Source': capture[i].ip.src, "Destination": capture[i].ip.dst, "Protocol": capture[i].highest_layer})
except:
fields.update({'Source': capture[i].eth.src, "Destination": capture[i].eth.dst, "Protocol": capture[i].highest_layer})
fields.update({'Src_mac':capture[i].eth.src, 'Dst_mac':capture[i].eth.dst, 'Timestamp':str(capture[i].sniff_time)[:-7], })
Info = ''
for j in capture[i][capture[i].highest_layer].field_names:
if len(capture[i][capture[i].highest_layer].get_field(j)) < 20:
Info =Info + j + '=' + capture[i][capture[i].highest_layer].get_field(j) + ' '
fields['Info'] = Info
content = ''
fields.update({'Src_port': '', "Dst_port": ''})
if 'TCP' in str(capture[i].layers):
fields.update({'Src_port': capture[i].tcp.srcport, "Dst_port": capture[i].tcp.dstport, 'Tcp_seq': capture[i].tcp.seq, 'Tcp_ack':capture[i].tcp.ack})
pattern = r'[A-Z]'
mat =re.compile(pattern)
flags = ''.join(mat.findall(capture[i].tcp._all_fields['tcp.flags.str']))
fields.update({'Flags': flags, 'Tcp_len': capture[i].tcp.len})
if 'payload' in dir(capture[i].tcp):
payload = capture[i].tcp.payload.binary_value
content = str(payload)
elif 'UDP' in str(capture[i].layers):
fields.update({'Src_port': capture[i].udp.srcport, "Dst_port": capture[i].udp.dstport})
if 'payload' in dir(capture[i].udp):
payload = capture[i].udp.data.data.binary_value
content = str(payload)
if 'ICMP' in str(capture[i].layers):
fields.update({'Icmp_type':capture[i].icmp.type, 'Icmp_code':capture[i].icmp.code, "Icmp_id": capture[i].icmp.ident})
if 'IP' in str(capture[i].layers):
fields.update({'Ip_id': int(capture[i].ip.id, 16), 'Ip_ttl': capture[i].ip.ttl})
fields.update({'Content': content})
matching(fields)
#使用pyshark抓包,结束后向队列传入‘Over’信号
def capture_net(interface):
t = threading.Thread(target=load_net, args=[interface,])
t.start()
while 1:
capture = pyshark.LiveCapture(interface= interface,output_file= './{}.cap'.format(interface))
capture.sniff(packet_count= 500)
capture.close()
#, display_filter= 'ip contains www.baidu.com'
#capture = sniff(iface = interface, count = 100,)
#wrpcap('./{}.cap'.format(interface), capture)
#shutil.copy('./{}.cap'.format(interface),'./{}.pcap'.format(interface))
q.put(capture)
print('capture :', time.time())
#virbr0为网络接口(采集虚拟机网络)
capture_net('virbr0')
创建规则,用户访问百度后触发
{"protocol":["TCP", "UDP"],"sourcemac":"fe:54:00:03:23:36","port":"any","distmac":"any","dstport":"any","content":"www.baidu.com","message":"BAIDU"}
def net_list():
nets = netifaces.interfaces()
def net_detail(net):
return netifaces.ifaddresses(net)
return nets
def Rues(path):
files = os.listdir(path)
for i in files:
with open(path + i, 'r') as file:
rule = []
data = file.readline()
while data:
rule.append(json.loads(data))
data = file.readline()
return rule
q = queue.Queue()
rules = Rues('./rules/')
def matching(data):
action =''
for i in rules:
values = list(i.values())
if (data['Protocol'] in values[0] or values[0] =='any') and (data['Src_mac'] in values[1] or values[1] =='any') and (data['Src_port'] in values[2] or values[2] =='any') and (data['Dst_mac'] in values[3] or values[3] =='any') \
and (data['Dst_port'] in values[4] or values[4] =='any') and values[5] in data['Content']:
action = values[6]
break
if action:
print('Find!' + action)
return action