def voip_play2(s1,**kargs): """ Same than voip_play, but will play both incoming and outcoming packets. The sound will surely suffer distortion. Only supports sniffing. .. seealso:: voip_play to play only incoming packets. """ dsp,rd = os.popen2(sox_base % "-c 2") global x1, x2 x1 = "" x2 = "" def play(pkt): global x1, x2 if not pkt: return if not pkt.haslayer(UDP) or not pkt.haslayer(IP): return ip=pkt.getlayer(IP) if s1 in [ip.src, ip.dst]: if ip.dst == s1: x1 += pkt.getlayer(conf.raw_layer).load[12:] else: x2 += pkt.getlayer(conf.raw_layer).load[12:] x1, x2, r = _merge_sound_bytes(x1, x2) dsp.write(r) sniff(store=0, prn=play, **kargs)
def run(self): try: log.info("Setting filter: %s", self.config.filter) if self.config.iface == "any": # pragma: no cover sniff( filter=self.config.filter, store=0, prn=self.handle_packet, stop_filter=self.wants_stop ) else: sniff( filter=self.config.filter, store=0, prn=self.handle_packet, iface=self.config.iface, stop_filter=self.wants_stop ) except socket.error as ex: if self._error_to_stderr: sys.stderr.write("Error: %s, device: %s\n" % (ex, self.config.iface)) else: log.error("Error: %s, device: %s", ex, self.config.iface) finally: log.info("The sniff loop exited") os.kill(os.getpid(), signal.SIGINT)
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) parser = DiagParser(options) def print_interfaces(): print("[*] Available interfaces:") for iface in get_if_list(): print("[ ]\t%s (%s)" % (iface, get_if_addr(iface))) if not (options.interface or options.pcap): print("[*] Must provide a pcap file or an interface to sniff on") print_interfaces() return if options.pcap: print("[*] Parsing pcap file (%s)" % options.pcap) else: if options.interface not in get_if_list(): print("[*] Invalid interface '%s'" % options.interface) print_interfaces() return print("[*] Listening on interface (%s)" % options.interface) try: sniff(iface=options.interface, offline=options.pcap, prn=parser.parse_packet, store=0) except KeyboardInterrupt: pass print("[*] Finished parsing/sniffing") parser.reassemble()
def run(self): try: log.info("Setting filter: %s", self.config.filter) sniff(filter=self.config.filter, store=0, prn=self.handle_packet, iface=self.config.iface) finally: log.info("The sniff loop exited") os.kill(os.getpid(), signal.SIGINT)
def getRSNInformation(self, essid): sendp( RadioTap()/ Dot11(addr1=self.bssid, addr2=self.source_mac, addr3=self.bssid, SC=self.__unfuckupSC__(), subtype=4)/ Dot11ProbeReq()/ Dot11Elt(ID=0, info=essid)/ Dot11Elt(ID=1, info='\x82\x84\x0b\x16\x24\x30\x48\x6c')/ Dot11Elt(ID=50, info='\x0c\x12\x18\x60'), iface=self.interface, verbose=False) self.sequence += 1 sniff(iface=self.interface, store=0, timeout=self.timeout, stop_filter=self.__stopfilter__) if self.lastpacket == None or not self.lastpacket.haslayer('Dot11ProbeResp'): return None probeResp = self.lastpacket.getlayer(Dot11ProbeResp) tmp = probeResp.getlayer(Dot11Elt) while tmp: if tmp.fields.get('ID') == 48: rsnInfo = tmp break else: tmp = tmp.payload if rsnInfo == None: rsnInfo = '' # we didn't find it in the probe response, so we'll return an empty string else: rsnInfo = parseRSNData(rsnInfo.info) rsnInfo = buildRSNData(rsnInfo) rsnInfo = '\x30' + chr(len(rsnInfo)) + rsnInfo return rsnInfo
def run(self): pfilter = 'port %d' % self._port try: kwargs = { 'filter': pfilter, 'store': 0, 'prn': self._handle_packet, 'iface': self._iface, 'stop_filter': lambda p: self._wants_stop, } if self._offline: kwargs['offline'] = self._offline sniff(**kwargs) except Exception as ex: if 'Not a pcap capture file' in str(ex): print('%s is not a valid pcap file' % self._offline) return print('Error: %s: %s (device: %s)' % (ex, traceback.format_exc(), self._iface)) finally: if self._offline: # drain dispatcher while not self._dispatcher.empty: time.sleep(0.1)
def pull_data(): """ Obtiene datos de la interfaz. Deberia delegar el pedido al manager de datos """ sniff(iface = IFACE, prn = lambda package: process_sniffed_package(package, persist_bssid_ssids), lfilter = lambda package: package.haslayer(Dot11Elt) )
def run(self): """ This is the thread routine that handles probe requests and sends probe responses when appropriate. """ while not self.__shutdown__: sniff(iface=self.interface, store=0, timeout=RESPONSE_TIMEOUT, stop_filter=self.__stopfilter__) if self.lastpacket: if self.lastpacket.haslayer(Dot11ProbeReq): ssid = None tmp = self.lastpacket.getlayer(Dot11ProbeReq) while tmp: tmp = tmp.payload if tmp.fields['ID'] == 0: ssid = tmp.info break if ssid is None: continue elif ssid == '' and self.essid: ssid = self.essid if self.essid is None or self.essid == ssid: self.probe_response_template.getlayer(Dot11).addr1 = get_source(self.lastpacket) self.probe_response_template.getlayer(Dot11Elt).info = ssid sendp(self.probe_response_template, iface=self.interface, verbose=False) self.lastpacket = None continue clientMAC = get_source(self.lastpacket) if not self.client_queue.full(): self.client_queue.put(clientMAC, False) self.lastpacket = None continue
def get_rsn_information(self, essid): rsnInfo = None sendp( RadioTap()/ Dot11(addr1=self.bssid, addr2=self.source_mac, addr3=self.bssid, SC=self.__fixSC__(), subtype=4)/ Dot11ProbeReq()/ Dot11Elt(ID=0, info=essid)/ Dot11Elt(ID=1, info='\x82\x84\x0b\x16\x24\x30\x48\x6c')/ Dot11Elt(ID=50, info='\x0c\x12\x18\x60'), iface=self.interface, verbose=False ) self.sequence += 1 sniff(iface=self.interface, store=0, timeout=self.timeout, stop_filter=self.__stopfilter__) if self.lastpacket is None or not self.lastpacket.haslayer(Dot11ProbeResp): return None probeResp = self.lastpacket.getlayer(Dot11ProbeResp) tmp = probeResp.getlayer(Dot11Elt) while tmp: if tmp.fields.get('ID') == 48: rsnInfo = tmp break else: tmp = tmp.payload if rsnInfo is None: rsnInfo = '' # Did not find rsnInfo in probe response. else: rsnInfo = build_rsn_data(parse_rsn_data(rsnInfo.info)) rsnInfo = '\x30' + chr(len(rsnInfo)) + rsnInfo return rsnInfo
def voip_play2(s1,**kargs): dsp,rd = os.popen2("sox -t .ul -c 2 - -t ossdsp /dev/dsp") def play(pkt,last=[]): if not pkt: return if not pkt.haslayer(UDP): return ip=pkt.getlayer(IP) if s1 in [ip.src, ip.dst]: if not last: last.append(pkt) return load=last.pop() x1 = load.load[12:] # c1.write(load.load[12:]) if load.getlayer(IP).src == ip.src: x2 = "" # c2.write("\x00"*len(load.load[12:])) last.append(pkt) else: x2 = pkt.load[:12] # c2.write(pkt.load[12:]) dsp.write(merge(x1,x2)) sniff(store=0, prn=play, **kargs)
def voip_play3(lst=None, **kargs): """Same than voip_play, but made to read and play VoIP RTP packets, without checking IP. .. seealso:: voip_play for basic VoIP packets """ dsp, rd = os.popen2(sox_base % "") def play(pkt, dsp=dsp): if pkt and pkt.haslayer(UDP) and pkt.haslayer(RTP): dsp.write(pkt.getlayer(RTP).load) try: if lst is None: sniff(store=0, prn=play, **kargs) else: for p in lst: play(p) finally: try: dsp.close() rd.close() except: pass
def capture_packet(self): """ 设置过滤器, 只接收IP、IPv6、TCP、UDP """ sniff(store=False, filter="(tcp or udp or icmp) and (ip6 or ip)", prn=lambda x: self.getConnections(x), stop_filter=lambda x: self.start_flag.is_set())
def auth_sniffer(self, iface): try: self.__AUTH_STATUS = True sniff(iface=iface, prn=self.get_auth_resp) except ValueError: pass finally: self.__AUTH_STATUS = False
def start_eapol_sniffer(self): try: self.__SNIFFER_STATUS = not bool(0) sniff(iface=self.iface, prn=self.eapol_sniffer_replay, timeout=20) except ValueError: pass finally: self.__SNIFFER_STATUS = not bool(1)
def asso_sniffer(self, iface): try: self.__ASSO_STATUS = True sniff(iface=iface, prn=self.get_asso_resp) except Exception as e: if not e == "EAPOL": sys.exit(e) finally: self.__ASSO_STATUS = False
def run(self): filter = 'ip host {} and tcp port {}'.format(self.target_ip, self.target_port) log.info('Starting sniffer for %s:%d on %s (%s)', self.target_ip, self.target_port, self.interface, filter) sniff(iface=self.interface, prn=self.process, filter=filter, stop_filter=lambda p: self.stop_event.is_set())
def run(self): sniff(filter='ip', prn=self.process_packet, store=0, iface=IFACE, stop_filter=lambda x: shutdown_event.is_set()) # Note: The stop_filter function is applied to each packet, meaning that sniffing won't stop if we do not # receive any packets. See: https://github.com/secdev/scapy/issues/989 print "Stopped sniffing."
def recv(self, bufferlen=0): """ Read a frame and return the information above the Dot11 layer. """ sniff(iface=self.interface, store=0, timeout=self.timeout, stop_filter=self.__stopfilter__) if self.lastpacket: return self.lastpacket else: return None
def _sniff(self): self._wait_for_gui() if self.channelthread: self.channelthread.start() self._say("starts sniffing on interface %s" % self.iface) sniff(iface=self.iface, prn=self._callback, stop_filter=self._callback_stop, store=False)
def process(self): while self.state: try: sniff(prn=self.extract, filter="port 80 or port 443", store=False, stop_filter=self.state) except: pass
def cl_generator(self): signal.signal(signal.SIGINT, self.sniff_breaker) try: sniff(iface=self.iface, prn=self.cl_generator_replay, timeout=self.timeout) except ValueError: pass finally: signal.signal(signal.SIGINT, lambda sig, fr: sys.exit(-1))
def quick_confirm(self): filt = "icmp and dst host " + self.victim.get_addr() self.quick_confirm_bool = False send(self.ping_pkt, verbose=False) sniff(count=1, filter=filt, timeout=1, prn=self.set_confirm_bool(True)) self.success = self.quick_confirm_bool
def run(self): pfilter = "port %d" % self._port try: log.info("Setting filter: %s", pfilter) sniff(filter=pfilter, store=0, prn=self.handle_packet, iface=self._iface) except socket.error as ex: log.error("Error: %s, device: %s", ex, self._iface) finally: log.info("The sniff loop exited") os.kill(os.getpid(), signal.SIGINT)
def parse_and_write_file(input_file): # packets = rdpcap(input_file) sniff(offline=input_file, prn=parse_pkt, store=0) print("\n") save_flow_dict() save_dict(SrcIPs, "Source IPs") save_dict(DstIPs, "Destination IPs") save_dict(Protocols, "Protocols") save_dict(SrcPort, "Source Ports") save_dict(DstPort, "Destination Ports")
def DHCP_FULL(ifname, MAC, timeout=3): global Global_IF Global_IF = ifname # 发送DHCP Discover数据包 pool.apply_async(DHCP_Discover_Sendonly, args=(Global_IF, MAC)) # 侦听数据包,使用过滤器filter="port 68 and port 67"进行过滤,把捕获的数据包发送给DHCP_Monitor_Control函数进行处理 sniff(prn=DHCP_Monitor_Control, filter="port 68 and port 67", store=0, iface=scapy_iface(Global_IF), timeout=timeout)
def sniff_wrap(iface, prn, store): while True: try: sniff(iface=iface, prn=prn, store=store) except Exception as ex: print ex, iface if ex[0] == 100: os.system("/sbin/iwconfig %s mode monitor" % iface) os.system("/sbin/ifconfig %s up" % iface) time.sleep(0.1) pass
def run(self): pfilter = "port %d" % self._port try: if self._iface == "any": sniff(filter=pfilter, store=0, prn=self.handle_packet) else: sniff(filter=pfilter, store=0, prn=self.handle_packet, iface=self._iface) except socket.error as ex: sys.stderr.write("Error: %s, device: %s\n" % (ex, self._iface)) finally: os.kill(os.getpid(), signal.SIGINT)
def locate(self): if not self.ap: self.__AVAIL = True return try: self.pull.info( "Waiting for the Access Point MAC address to receive... [30]") sniff(iface=self.iface, prn=self.collector, timeout=30) except ImportError, e: if str(e) == "!": self.__AVAIL = True
def cl_generator(self): try: sniff(iface=self.iface, prn=self.cl_generator_replay) raise KeyboardInterrupt except KeyboardInterrupt: if self.verbose: self.pull.use("Clients %s (%s) - %s[Found %s]%s" % (self.bssid.replace(':', '').upper(), self.pull.DARKCYAN+org(self.bssid).org+self.pull.END,\ self.pull.GREEN, len(self.__CONNECTECD_CL), self.pull.END)) else: self.pull.use("Clients %s - [Found %s]" % (self.bssid.replace( ':', '').upper(), len(self.__CONNECTECD_CL)))
def run(self): """ Activity function for class """ #print("rev task is running") while not self.killed: #sendrecv.sniff(filter="udp and (port 67 or 68)", prn=lambda p: self.print_dhcp_response(p)) sendrecv.sniff(filter="udp and (port 67 or 68)", prn=self.dhcp_response, timeout=1) print("rev task exit")
def monitor(self): parser = argparse.ArgumentParser( description="Start the Antenna") parser.add_argument('--interface', required=True, default="wlan0mon", help="Interface name to start monitoring") args = parser.parse_args(sys.argv[2:]) try: sniff(iface=args.interface, prn=self.packet_callback, store=0) except Exception as e: logger.error(f"Error starting sniffer: {e}")
def sniff_packets(iface=None): """ Sniff HTTP packets using the given interface. If no interface is given use Scapy default interface. :param iface: Interface top sniff on """ if iface: # Port 80 is for HTTP # process_packet is the callback sniff(filter="port 80", prn=process_packet, iface=iface, store=False) else: # Sniff using the default interface sniff(filter="port 80", prn=process_packet, store=False)
def main(): try: print(f"Scanning for {CONFIG.timeout}sec...") sniff(prn=packet_handler, store=False, monitor=True, timeout=CONFIG.timeout) print("Finishing up...") print(f"Found {len(endpoints)} endpoints") print(f"Found {count_passwords()} passwords") # print(repr(endpoints)) except KeyboardInterrupt: print("Exiting...") exit(0)
def sniff_single(self, file: str, filt: str = ""): if self.must_send: file_size_limit = 1000 else: file_size_limit = 0 conf.iface = self.interface.get_name() sniff(prn=lambda x: wrpcap(file, x, append=True), count=file_size_limit, filter=filt, stop_filter=lambda x: self.is_killed())
def run(self): while self.kill_received is not True: try: sniff( filter=self.FILTER, prn=self._dispatch_to_handler, store=0, timeout=5, iface=str(self._interface.name), ) except: self._logger.exception("Unexpected error occurred in listener thread")
def run(self): try: log.info("Setting filter: %s", self.config.filter) if self.config.iface == "any": sniff(filter=self.config.filter, store=0, prn=self.handle_packet) else: sniff(filter=self.config.filter, store=0, prn=self.handle_packet, iface=self.config.iface) except socket.error as ex: log.error("Error: %s, device: %s", ex, self.config.iface) finally: log.info("The sniff loop exited") os.kill(os.getpid(), signal.SIGINT)
def voip_play(s1, lst=None, **kargs): """Play VoIP packets with RAW data that are either sniffed either from an IP, or specified as a list. It will play only the incoming packets ! :param s1: The IP of the src of all VoIP packets. :param lst: (optional) A list of packets to load :type s1: string :type lst: list :Example: >>> voip_play("64.2.142.189") while calling '*****@*****.**' >>> voip_play("64.2.142.189", lst) with list a list of packets with VoIP data in their RAW layer .. seealso:: voip_play2 to play both the outcoming and incoming packets at the same time. .. seealso:: voip_play3 to read RTP VoIP packets """ proc = subprocess.Popen(sox_base[0] + sox_base[1], stdin=subprocess.PIPE, stdout=subprocess.PIPE) dsp, rd = proc.stdin, proc.stdout def play(pkt): if not pkt: return if not pkt.haslayer(UDP) or not pkt.haslayer(IP): return ip = pkt.getlayer(IP) if s1 == ip.src: dsp.write(pkt.getlayer(conf.raw_layer).load[12:]) try: if lst is None: sniff(store=0, prn=play, **kargs) else: for p in lst: play(p) finally: dsp.close() rd.close()
def incoming_data_handler(thread_name, sock): def receive_data(): def get_data(pkt: IP): print(pkt[UDP].dport, sock.getsockname()[1]) if pkt[UDP].dport == sock.getsockname()[1]: print(str(pkt[DNSQR].qname.decode('utf-8'))) return get_data sniff( filter= f"udp port {sock.getsockname()[1]} and ip dst {sock.getsockname()[0]}", prn=receive_data())
def run(self, *args, **kwargs): try: sniff_kwargs = {"filter": self._pfilter, "store": 0, "prn": self.handle_packet} if "offline" in kwargs: sniff_kwargs["offline"] = kwargs["offline"] sniff(**sniff_kwargs) except socket.error as ex: sys.stderr.write("Error: %s, filter: %s\n" % (ex, self._pfilter)) finally: if "offline" not in kwargs: os.kill(os.getpid(), signal.SIGINT)
def main(): log.info( f'Started UPnP sniffer filter: "{_SNIFFER_FILTER}" on {_SNIFFER_IFACE}' ) # starts an infinite sniffer loop with the following properties # the IP packets are deframented on-the-flow # sniffer is filtered for the specified TCP/5000 and for scapy dependent filer to contain the Raw layer (DATA) # capture packet on iface, do not store the traffic and resolve each packet with specified callback sniff(session=IPSession, filter=_SNIFFER_FILTER, lfilter=lambda x: x.haslayer(Raw), iface=_SNIFFER_IFACE, prn=inspect_packet, store=False)
def connect(self, essid, rsnInfo = ''): """ Connect/Associate with an access point. errDict = { -1:"Already Connected", 0:"No Error", 1:"Failed To Get Probe Response", 2:"Failed To Get Authentication Response", 3:"Failed To Get Association Response", 4:"Authentication Request Received Fail Response", 5:"Association Request Received Fail Response" } """ # Dot11 Probe Request (to get authentication information if applicable) if rsnInfo == None: # None explicitly means go get it, leave it '' to proceed with out it rsnInfo = self.getRSNInformation(essid) # Dot11 Authentication Request sendp( RadioTap()/ Dot11(addr1=self.dest_mac, addr2=self.source_mac, addr3=self.bssid, SC=self.__unfuckupSC__())/ Dot11Auth(seqnum=1), iface=self.interface, verbose=False) self.sequence += 1 sniff(iface=self.interface, store=0, timeout=self.timeout, stop_filter=self.__stopfilter__) if self.lastpacket == None or not self.lastpacket.haslayer('Dot11Auth'): return 2 if self.lastpacket.getlayer('Dot11Auth').status != 0: return 4 # Dot11 Association Request sendp( RadioTap()/ Dot11(addr1=self.bssid, addr2=self.source_mac, addr3=self.bssid, SC=self.__unfuckupSC__(), subtype=0)/ Dot11AssoReq(cap='ESS+short-preamble+short-slot', listen_interval=10)/ Dot11Elt(ID=0, info=essid)/ Dot11Elt(ID=1, info='\x82\x84\x0b\x16\x24\x30\x48\x6c')/ Dot11Elt(ID=50, info='\x0c\x12\x18\x60')/ rsnInfo, iface=self.interface, verbose=False) self.sequence += 1 sniff(iface=self.interface, store=0, timeout=self.timeout, stop_filter=self.__stopfilter__) if self.lastpacket == None or not self.lastpacket.haslayer(Dot11AssoResp): return 3 if self.lastpacket.getlayer(Dot11AssoResp).status != 0: return 5 self.connected = True self.sequence = 0 # reset it return 0
def voip_play(s1, list=None, **kargs): FIFO = get_temp_file() FIFO1 = FIFO % 1 FIFO2 = FIFO % 2 os.mkfifo(FIFO1) os.mkfifo(FIFO2) try: os.system("soxmix -t .ul %s -t .ul %s -t ossdsp /dev/dsp &" % (FIFO1, FIFO2)) c1 = open(FIFO1, "w", 4096) c2 = open(FIFO2, "w", 4096) fcntl.fcntl(c1.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(c2.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) # dsp,rd = os.popen2("sox -t .ul -c 2 - -t ossdsp /dev/dsp") def play(pkt, last=None): if last is None: last = [] if not pkt: return if not pkt.haslayer(UDP): return ip = pkt.getlayer(IP) if s1 in [ip.src, ip.dst]: if not last: last.append(pkt) return load = last.pop() # x1 = load.load[12:] c1.write(load.load[12:]) if load.getlayer(IP).src == ip.src: # x2 = "" c2.write("\x00" * len(load.load[12:])) last.append(pkt) else: # x2 = pkt.load[:12] c2.write(pkt.load[12:]) # dsp.write(merge(x1,x2)) if list is None: sniff(store=0, prn=play, **kargs) else: for p in list: play(p) finally: os.unlink(FIFO1) os.unlink(FIFO2)
def run(self): # bind a UDP socket server on port 53, otherwise we'll have # ICMP type 3 error as a client, because the port will be seen # as unreachable (nothing being binded on it) t = threading.Thread(target=socket_server, args=(self.host_ip, )) t.start() self.logger.info(f"DNS sniffer started on {self.host_ip}:53") sniff( filter=f"udp port 53 and ip dst {self.host_ip}", prn=self._dns_responder, iface=self.interface, ) t.join()
def voip_play(s1,list=None,**kargs): FIFO=get_temp_file() FIFO1=FIFO % 1 FIFO2=FIFO % 2 os.mkfifo(FIFO1) os.mkfifo(FIFO2) try: os.system("soxmix -t .ul %s -t .ul %s -t ossdsp /dev/dsp &" % (FIFO1,FIFO2)) c1=open(FIFO1,"w", 4096) c2=open(FIFO2,"w", 4096) fcntl.fcntl(c1.fileno(),fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(c2.fileno(),fcntl.F_SETFL, os.O_NONBLOCK) # dsp,rd = os.popen2("sox -t .ul -c 2 - -t ossdsp /dev/dsp") def play(pkt, last=None): if last is None: last = [] if not pkt: return if not pkt.haslayer(UDP): return ip=pkt.getlayer(IP) if s1 in [ip.src, ip.dst]: if not last: last.append(pkt) return load=last.pop() # x1 = load.load[12:] c1.write(load.load[12:]) if load.getlayer(IP).src == ip.src: # x2 = "" c2.write("\x00"*len(load.load[12:])) last.append(pkt) else: # x2 = pkt.load[:12] c2.write(pkt.load[12:]) # dsp.write(merge(x1,x2)) if list is None: sniff(store=0, prn=play, **kargs) else: for p in list: play(p) finally: os.unlink(FIFO1) os.unlink(FIFO2)
def capture(userfilter="", pcapname=".tmp.pcap", func=None, count=0, time=None, offline=None): """This function is a wrapper function above the sniff scapy function. The result is a list of templates. The specification on filtering options can be found at: https://goo.gl/kVAmHQ Parameters ---------- userfilter : :obj:`str` Filters to capture packets. pcapname : :obj:`str` Path where the pcap will be written. func : :obj:`function` Function to be called when a packet arrive, the packet will be passed as parameter. count : int Number of packets to capture. time : int Stop sniffing after a given time. Returns ------- :obj:`TList` List of templates """ if func: plist = sniff(filter=userfilter, prn=func, count=count, timeout=time, offline=offline) else: plist = sniff(filter=userfilter, count=count, timeout=time, offline=offline) # Save the list of packages to disk for later readin with pyshark if len(plist) > 0: wrpcap(join(POLYM_PATH, pcapname), plist) tgen = TGenerator(join(POLYM_PATH, pcapname), scapy_pkts=plist) # Returns a list of templates return TList(tgen, len(plist), namesgen(plist)) return None
def voip_play(s1, lst=None, **kargs): """Play VoIP packets with RAW data that are either sniffed either from an IP, or specified as a list. It will play only the incoming packets ! :param s1: The IP of the src of all VoIP packets. :param lst: (optional) A list of packets to load :type s1: string :type lst: list :Example: >>> voip_play("64.2.142.189") while calling '*****@*****.**' >>> voip_play("64.2.142.189", lst) with list a list of packets with VoIP data in their RAW layer .. seealso:: voip_play2 to play both the outcoming and incoming packets at the same time. .. seealso:: voip_play3 to read RTP VoIP packets """ dsp, rd = os.popen2(sox_base % "") def play(pkt): if not pkt: return if not pkt.haslayer(UDP) or not pkt.haslayer(IP): return ip = pkt.getlayer(IP) if s1 == ip.src: dsp.write(pkt.getlayer(conf.raw_layer).load[12:]) try: if lst is None: sniff(store=0, prn=play, **kargs) else: for p in lst: play(p) finally: dsp.close() rd.close()
def run(self): if self.interface.hop: hopper = ChannelHoppingThread(self.interface) hopper.start() try: sniff(iface=self.interface.name, prn=self.interface.scan, stop_filter=self._stopped) if self.interface.hop: hopper.stop() hopper.join() except OSError as e: cprint( "Error! The interface {} does not exist!".format( self.interface.name), 'white', 'on_red') sys.exit()
def waitForBeacon(self): """Waits for a 802.11 beacon from an AP with our SSID.""" global RECV_TIMEOUT if self.testmode: return FAKE_AP_MAC self.log("Waiting for a beacon from SSID=[%s]" % self.ssid) beacon = False mac = None starttime = time.time() while not beacon: p = sniff(count=1, timeout=RECV_TIMEOUT)[0] if p is None or len(p) == 0 or (time.time() - starttime) > self.tping: # Timeout! raise WiExceptionTimeout("waitForBeacon() timeout exceeded!") # Check if beacon comes from the AP we want to connect to if p.haslayer(Dot11Elt) and p.getlayer(Dot11Elt).info == self.ssid: beacon = True mac = p.addr3 self.log("Beacon from SSID=[%s] found (MAC=[%s])" % (self.ssid, mac)) return mac
def run(self, *args, **kwargs): pfilter = "port %d" % self._port try: sniff_kwargs = {"filter": pfilter, "store": 0, "prn": self.handle_packet} if self._iface != "any": sniff_kwargs["iface"] = self._iface if "offline" in kwargs: sniff_kwargs["offline"] = kwargs["offline"] sniff(**sniff_kwargs) except socket.error as ex: sys.stderr.write("Error: %s, device: %s\n" % (ex, self._iface)) finally: if "offline" not in kwargs: os.kill(os.getpid(), signal.SIGINT)
def main(): """ :return: void """ got_data = 0 ip_layer = IP(src=TUNNEL_SERVER_IP, dst=TUNNEL_CLIENT_IP) while True: print "===============================================================" pkt = sniff(filter="icmp", timeout=15, count=1) print "received packet ------------------------------------------" pkt[0].show() print "received packet ------------------------------------------" i = 0 tunneled_data = pkt[0][ICMP].load if tunneled_data[:9] == "#request:": i = pkt[0][ICMP].seq tunneled_data = "#answer: " + random_word() + str(i) got_data = 1 if got_data == 0: tunneled_data = "Couldn't get data" icmp = (ICMP(type=0, code=0, id=pkt[0][ICMP].id, seq=i, chksum=random.randrange(1, 65535, 1)) / tunneled_data) packet = ip_layer / icmp print "sent packet ------------------------------------------" packet.show() print "sent packet ------------------------------------------" send(packet) got_data = 0
def voip_play3(lst=None,**kargs): dsp,rd = os.popen2("sox -t .ul - -t ossdsp /dev/dsp") try: def play(pkt, dsp=dsp): if pkt and pkt.haslayer(UDP) and pkt.haslayer(conf.raw_layer): dsp.write(pkt.getlayer(RTP).load) if lst is None: sniff(store=0, prn=play, **kargs) else: for p in lst: play(p) finally: try: dsp.close() rd.close() except: pass
def sniffradio(opened_socket=None, radio=None, *args, **kargs): if radio is not None: switch_radio_protocol(radio) s = opened_socket if opened_socket is not None else GnuradioSocket() rv = sendrecv.sniff(opened_socket=s, *args, **kargs) if opened_socket is None: s.close() return rv
def waitForPacket(self, condition): r = None while True: p = sniff(count=1, timeout=20)[0] if p is None or len(p) == 0: break if condition(p): r = p break return r
def main(): options = parse_options() if options.verbose: logging.basicConfig(level=logging.DEBUG) parser = DiagParser(options) if options.pcap: print("[*] Parsing pcap file (%s)" % options.pcap) else: print("[*] Listening on interface (%s)" % options.interface) try: sniff(iface=options.interface, offline=options.pcap, prn=parser.parse_packet, store=0) except KeyboardInterrupt: pass print("[*] Finished parsing/sniffing") parser.reassemble()
def run(self): "Sniffer main loop" begin = time() pkts_all = 0 sniff_begin = time() stat_prev = sniff_begin stat_every = 3 # seconds while True: start = time() # This catches KeyboardInterrupt, # TODO: Disable this catching + Probably hop on another thread and use prn argument. # But then - you'd have watchdog problems. pkts = sendrecv.sniff(iface=self.interface, count=20, timeout=0.1) pkts_all += len(pkts) for pkt in pkts: data = self.packet_parser.parse(pkt) if data is None: continue data['ch'] = self.hopper.channel_number data['sniffer'] = self.sniffer_name if ('PROBE_REQ' in data['tags'] or 'PROBE_RESP' in data['tags'] or 'ASSOC_REQ' in data['tags'] or 'DISASS' in data['tags']): # Increase karma when client traffic is detected self.hopper.increase_karma() data['tags'] = list(data['tags']) self.db.frames.add(data) now = time() took = now - start if stat_prev + stat_every < now: took = time() - sniff_begin print "STAT: pkts=%d t_total=%.2fs pps=%.2f swipes=%d avg_swipe_t=%.2f cur_ch=%d" % ( pkts_all, took, pkts_all / took, self.hopper.swipes_total, took/(self.hopper.swipes_total + 0.001), self.hopper.channel_number, ) stat_prev = now if self.enable_hopping: ret = self.hopper.karmic_hop() if ret is False: break self.watchdog.dontkillmeplease()
def voip_play1(s1,list=None,**kargs): dsp,rd = os.popen2("sox -t .ul - -t ossdsp /dev/dsp") def play(pkt): if not pkt: return if not pkt.haslayer(UDP): return ip=pkt.getlayer(IP) if s1 in [ip.src, ip.dst]: dsp.write(pkt.getlayer(conf.raw_layer).load[12:]) try: if list is None: sniff(store=0, prn=play, **kargs) else: for p in list: play(p) finally: dsp.close() rd.close()
def p0f_getlocalsigs(): """This function returns a dictionary of signatures indexed by p0f db (e.g., p0f_kdb, p0fa_kdb, ...) for the local TCP/IP stack. You need to have your firewall at least accepting the TCP packets from/to a high port (30000 <= x <= 40000) on your loopback interface. Please note that the generated signatures come from the loopback interface and may (are likely to) be different than those generated on "normal" interfaces.""" pid = os.fork() port = random.randint(30000, 40000) if pid > 0: # parent: sniff result = {} def addresult(res): # TODO: wildcard window size in some cases? and maybe some # other values? if res[0] not in result: result[res[0]] = [res[1]] else: if res[1] not in result[res[0]]: result[res[0]].append(res[1]) # XXX could we try with a "normal" interface using other hosts iface = conf.route.route('127.0.0.1')[0] # each packet is seen twice: S + RA, S + SA + A + FA + A # XXX are the packets also seen twice on non Linux systems ? count = 14 pl = sniff(iface=iface, filter='tcp and port ' + str(port), count=count, timeout=3) # noqa: E501 for pkt in pl: for elt in packet2p0f(pkt): addresult(elt) os.waitpid(pid, 0) elif pid < 0: log_runtime.error("fork error") else: # child: send # XXX erk time.sleep(1) s1 = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM) # S & RA try: s1.connect(('127.0.0.1', port)) except socket.error: pass # S, SA, A, FA, A s1.bind(('127.0.0.1', port)) s1.connect(('127.0.0.1', port)) # howto: get an RST w/o ACK packet s1.close() os._exit(0) return result