利用Python实现DNS报文的识别以及信息提取并分析可疑域名
1 from xml.dom.expatbuilder import theDOMImplementation 2 from scapy.all import * 3 import optparse 4 import sys 5 import ipaddress 6 import threading 7 8 class DNSAnalyzer: 9 def __init__(self) -> None: 10 self.interface = self.get_params() 11 self.dns_info = {} 12 self.interval = 5 13 14 def get_params(self): 15 parser = optparse.OptionParser('Usage: <Program> -i interface') 16 parser.add_option('-i', '--interface', dest='interface', type='string', help='Specify interface to listen') 17 options, args = parser.parse_args() 18 if options.interface is None: 19 print(parser.usage) 20 sys.exit(0) 21 return options.interface 22 23 24 def packet_handler(self, pkt): 25 if pkt.haslayer(DNSRR): 26 rrname = pkt.getlayer(DNSRR).rrname.decode('utf-8') 27 dns_type = pkt.getlayer(DNSRR).type 28 rdata = pkt.getlayer(DNSRR).rdata 29 30 if dns_type == 1: 31 # print("*"*50) 32 33 if rrname not in self.dns_info.keys(): 34 self.dns_info[rrname] = [rdata] 35 else: 36 self.dns_info[rrname] = self.dns_info[rrname].append(rdata) 37 # print(self.dns_info) 38 39 def display_timer(self): #定时显示字典里的数据,比如每5秒钟 40 for k, v in self.dns_info.items(): 41 print("%s\t\t\t\t\t%s" % (k, str(v))) 42 if len(v) > 1: 43 print("[-] Found suspicious DNS domain:", k, str(v)) 44 45 t = threading.Timer(self.interval, self.display_timer) 46 t.start() 47 48 def packet_sniff(self): 49 50 try: 51 52 sniff(iface=self.interface, prn=self.packet_handler, store=False) 53 54 except Exception as e: 55 print(e) 56 sys.exit(0) 57 58 def run(self): 59 try: 60 t = threading.Thread(target=self.packet_sniff) 61 t.start() 62 except KeyboardInterrupt: 63 print("Exit program now") 64 sys.exit(0) 65 except Exception as e: 66 print(e) 67 sys.exit(0) 68 69 70 71 if __name__ == '__main__': 72 dnsanalyzer = DNSAnalyzer() 73 dnsanalyzer.run() 74 dnsanalyzer.display_timer()
STRIVE FOR PROGRESS,NOT FOR PERFECTION