利用Python实现DDOS攻击检测的工具
本代码主要的思路:
1. 利用Scapy模块的sniff方法捕捉网络报文,比如交换机镜像流量或者采集专门的TAP设备采集网络流量
2. 对所有报文进行源IP、目的IP以及目的端口的提取,并将这三种信息作为字典的键存入字段,包数(报文数量)为该键的值(Value)
3. 专门用多线程模块的Timer对上述存有数据的字典定期进行显示
1 from scapy.all import * 2 import sys 3 import optparse 4 import threading 5 import termcolor 6 7 class DDOSDetect: 8 def __init__(self) -> None: 9 self.interface = self.get_params()[0] 10 self.threshold = self.get_params()[1] 11 self.packet_stream = {} #该字段存储每个流以及对应的包数 12 self.interval = 5 13 self.banner() 14 def banner(self): 15 banner= """ 16 ************************************************** 17 18 ***DDOS ATTACK Detection Tool by Jason Wong******* 19 20 ************************************************** 21 22 23 """ 24 print(banner) 25 26 def get_params(self): 27 parser = optparse.OptionParser('Usage: <Program> -i interface -t threshold') 28 parser.add_option('-i', '--interface', dest='interface', type='string', help='Specify interface to listen') 29 parser.add_option('-t', '--threshold', dest='threshold', type='int', help='Specify threshold of packets quantity') 30 options, args = parser.parse_args() 31 if options.interface is None or options.threshold is None: 32 print(parser.usage) 33 sys.exit(0) 34 return options.interface, options.threshold 35 36 37 def packet_handler(self, pkt): 38 if pkt.haslayer(TCP): 39 src = pkt.getlayer(IP).src 40 dst = pkt.getlayer(IP).dst 41 dport = pkt.getlayer(TCP).dport 42 stream = str(src) + ":" + str(dst) + ":" +str(dport) 43 44 if stream in self.packet_stream.keys(): 45 self.packet_stream[stream] = self.packet_stream[stream] + 1 46 else: 47 self.packet_stream[stream] = 1 48 49 50 def packet_stream_display(self): #定时将packet_stream的数据打印出来 51 # print(self.packet_stream) 52 print("Captured Packets Statistics: \n") 53 if len(self.packet_stream) > 0: 54 for k, v in self.packet_stream.items(): 55 if v > self.threshold: 56 print("DDOS attack found: \n%s times: %d" % (k, v)) 57 print(k,'\t', v) 58 t = threading.Timer(self.interval, self.packet_stream_display) 59 t.start() 60 61 62 def run(self): 63 try: 64 65 sniff(iface=self.interface, prn=self.packet_handler, store=False) 66 67 except KeyboardInterrupt: 68 print("Exit program now!") 69 sys.exit(0) 70 except Exception as e: 71 print(e) 72 sys.exit(0) 73 74 def start_total(self): 75 self.packet_stream_display() 76 t = threading.Thread(target=self.run) 77 t.start() 78 79 if __name__ == '__main__': 80 ddos = DDOSDetect() 81 ddos.start_total() 82
实现效果如下图所示:
STRIVE FOR PROGRESS,NOT FOR PERFECTION