github.com/Coalfire-Research/Slackor@v0.0.0-20191010164036-aa32a7f9250b/impacket/examples/sniffer.py (about) 1 #!/usr/bin/env python 2 # SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. 3 # 4 # This software is provided under under a slightly modified version 5 # of the Apache Software License. See the accompanying LICENSE file 6 # for more information. 7 # 8 # Simple packet sniffer. 9 # 10 # This packet sniffer uses a raw socket to listen for packets 11 # in transit corresponding to the specified protocols. 12 # 13 # Note that the user might need special permissions to be able to use 14 # raw sockets. 15 # 16 # Authors: 17 # Gerardo Richarte <gera@coresecurity.com> 18 # Javier Kohen <jkohen@coresecurity.com> 19 # 20 # Reference for: 21 # ImpactDecoder. 22 23 from select import select 24 import socket 25 import sys 26 27 from impacket import ImpactDecoder 28 29 DEFAULT_PROTOCOLS = ('icmp', 'tcp', 'udp') 30 31 if len(sys.argv) == 1: 32 toListen = DEFAULT_PROTOCOLS 33 print("Using default set of protocols. A list of protocols can be supplied from the command line, eg.: %s <proto1> [proto2] ..." % sys.argv[0]) 34 else: 35 toListen = sys.argv[1:] 36 37 # Open one socket for each specified protocol. 38 # A special option is set on the socket so that IP headers are included with 39 # the returned data. 40 sockets = [] 41 for protocol in toListen: 42 try: 43 protocol_num = socket.getprotobyname(protocol) 44 except socket.error: 45 print("Ignoring unknown protocol:", protocol) 46 toListen.remove(protocol) 47 continue 48 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num) 49 s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 50 sockets.append(s) 51 52 if 0 == len(toListen): 53 print("There are no protocols available.") 54 sys.exit(0) 55 56 print("Listening on protocols:", toListen) 57 58 # Instantiate an IP packets decoder. 59 # As all the packets include their IP header, that decoder only is enough. 60 decoder = ImpactDecoder.IPDecoder() 61 62 while len(sockets) > 0: 63 # Wait for an incoming packet on any socket. 64 ready = select(sockets, [], [])[0] 65 for s in ready: 66 packet = s.recvfrom(4096)[0] 67 if 0 == len(packet): 68 # Socket remotely closed. Discard it. 69 sockets.remove(s) 70 s.close() 71 else: 72 # Packet received. Decode and display it. 73 packet = decoder.decode(packet) 74 print(packet)