def run(self): #~ print 'capT started on',self.dev self.cap = pcapy.open_live(self.dev , 65536 , 1 , 0) while(1) : #~ print 'new loop' if self.stopSig: #~ print 'sleeping' time.sleep(0.1) continue if self.devChanged: #~ print 'dev changed' self.cap = pcapy.open_live(self.dev , 65536 , 1 , 0) self.devChanged=0 try: #~ print 'running1' (self.header, self.packet) = self.cap.next() #~ print 'running2' self.timePacket={} self.timePacket['time']=datetime.datetime.now() self.timePacket['packet']=self.packet self.timePacket['header']=self.header self.packets.append(self.timePacket) #~ print 'capt',self.timePacket except pcapy.PcapError: continue return
def getTraffic(self): # list all the network devices # print(pcapy.findalldevs()) max_bytes = 1024 promiscuous = False read_timeout = 100 # in milliseconds pc = pcapy.open_live(pcapy.findalldevs()[0], max_bytes, promiscuous, read_timeout) pc.setfilter('tcp') # callback for received packets self.lastIp = '' def recv_pkts(hdr, data): packet = EthDecoder().decode(data) packetChild = packet.child() sourceIp = packetChild.get_ip_src() if (sourceIp != self.getLocalIp()): try: newIp = socket.gethostbyaddr(sourceIp)[0] if (newIp != self.lastIp): self.lastIp = newIp print(newIp) #from 20 to 20 save in a set in every 5 min and save to db except: pass #print('Unknown host') packet_limit = 20 # infinite pc.loop(packet_limit, recv_pkts) # capture packets
def main(self): options = {'TCP': False, 'ICMP': False, 'UDP': False, 'OTHER': False} devices = pcapy.findalldevs() print devices print chr(27) + "[0;91m" + "[!]" + chr(27) + "[0m" + " Dispositivos disponibles:" for d in devices: print " -> " + d dev = raw_input(chr(27) + "[0;92m" + "[+]" + chr(27) + "[0m" + " Introduzca el nombre del dispositivo: ") print chr(27) + "[0;91m" + "[!]" + chr(27) + "[0m" + " Dispositivo seleccionado: " + dev cap = pcapy.open_live(dev, 65536, 1, 0) options = raw_input(chr(27) + "[0;92m" + "[+]" + chr(27) + "[0m" + " Introduzca las opciones:") if options == 'ALL': options = {'TCP': True, 'ICMP': True, 'UDP': True, 'OTHER': True} else: lista_options = tuple(options.split(',')) for opcion in lista_options: if opcion in options: options[opcion] = True else: print "[-] Protocolo incorrecto." # Empezamos a sniffar paquetes while 1: (header, packet) = cap.next() self.parse_packet(packet, options)
def __init__(self): try: self.lorcon = PyLorcon2.Context(IFACE) except PyLorcon2.Lorcon2Exception as err: print "Error creating lorcon object: " print str(err) exit() try: self.lorcon.open_injmon() except PyLorcon2.Lorcon2Exception as err: print "Error while setting injection mode, are you root?" print str(err) exit() self.lorcon.set_channel(CHANNEL) # This needs an audit. os.system("ifconfig " + pipes.quote(IFACE) + " up") # Quick definitions for pcapy MAX_LEN = 1514 # max size of packet to capture PROMISCUOUS = 1 # promiscuous mode? READ_TIMEOUT = 0 # in milliseconds MAX_PKTS = 1 # number of packets to capture; 0 => no limit try: self.pcapy = open_live(IFACE, MAX_LEN, PROMISCUOUS, READ_TIMEOUT) except PcapError as err: print "Error creating pcapy descriptor, try turning on the target interface or setting it to monitor mode" print str(err)
def main(argv): #list all net interfaces net_devices = pcapy.findalldevs() print net_devices #choose net_device print "Available Network Interface: " for x in net_devices : print x dev_choice = raw_input("Please choose interface to sniff " ) print "Sniffing Device: " + dev_choice capture = pcapy.open_live(dev_choice, 65536, 1, 0) # capture == the live instance # comment the line below to capture ALL traffic or edit to set BPF filter for wanted traffic packet_reader=capture.setfilter('((udp) && (dst port 53) && (ip[41] = 0x61) && (ip[42] = 0x70) && (ip[43] = 0x69))') print "Listening on %s: NET: %s, MASK: %s, LINKTYPE: %d" % (dev_choice, capture.getnet(), capture.getmask(), capture.datalink()) ascii_list = [] domain_list = [] hash_list = [] #start packet capture while(1): (header, packet) = capture.next() # Uncomment the line below to display header information for each packet # print('%s: captured %d bytes, truncated to %d bytes' %(datetime.datetime.now(), header.getlen(), header.getcaplen())) packet_parser(packet) dec_list, sub_domain, root_domain = decoder(header, packet) dec2ascii(sub_domain, hash_list, domain_list)
def discover_neighbors (interface, timeout=100): def on_vrrp_packet (header, data): ethernet_frame = ethernet.Ethernet(data) ip_packet = ethernet_frame.data vrrp_packet = ip_packet.vrrp # skip over IPv6 right now, IPv4 needs fixing first if vrrp_packet.version == 3: return print "" print ip_packet.unpack print vrrp_packet.unpack print vrrp_packet.checksum vrrp_packet.checksum = 0 print dpkt.in_cksum(vrrp_packet.pack_hdr() + vrrp_packet.addrs[0]) version = vrrp_packet.version for i in vrrp_packet.addrs: print socket.inet_ntop(ip_version_map[version], i) try: pcap = pcapy.open_live (interface, 1524, 1, timeout) pcap.setfilter ('proto 112') # VRRP filter try: while True: # this is more responsive to keyboard interrupts pcap.dispatch (1, on_vrrp_packet) except KeyboardInterrupt, e: pass except Exception, e: print e
def capture(decoder, filter, callback): """Generic function to capture packets using pcapy, available to transports. Useful to receive incoming messages without proxying. Returns if the callback returns a string.""" import pcapy print "Receiving messages on %s" % cfg["interface"] # 1500 bytes, promiscuous mode. try: p = pcapy.open_live(cfg["interface"], 1500, 1, 0) except pcapy.PcapError, e: log("Couldn't open %s: %s" % (cfg["interface"], e)) cfg["interface"] = select_if()[0] log("Trying with %s" % cfg["interface"]) p = pcapy.open_live(cfg["interface"], 1500, 1, 0)
def run(self): Thread.__init__(self) def getInterface(expression): ifs = findalldevs() input = int(expression) # turns into an integer for the function to accept return ifs[input] # returns the inputted interface def recv_pkts(hdr, data): try: currentInt = getInterface(self.expression) if str(parser.learn_mode) == str(False): eth = EthDecoder().decode(data) ethChild = eth.child() ethChild2 = ethChild.child() if ethChild2.get_type() == 134: parser.sniffSlaac(data,currentInt) elif ethChild2.get_type() == 135: parser.sniffSlaac(data,currentInt) elif ethChild2.get_type() == 136: parser.sniffSlaac(data,currentInt) elif str(parser.learn_mode) == str(True): parser.activateLearningMode(data) except: pass pcapy.findalldevs() max_bytes = 1024 promiscuous = False read_timeout = 100 parser = DataParse.Dataparse(self.mode) pc = pcapy.open_live(getInterface(self.expression), max_bytes, promiscuous, read_timeout) pc.setfilter('icmp6') while self.isRunning is True: pc.loop(1, recv_pkts) # capture packets while the thread is running
def _run_sniffer_thread(self): """Sniffer thread Credit: Binary Tides """ #print '_run_sniffer_thread' nic_name = self._sniff_iface_name cli_ip = self._cli_ip max_packet_size = 65536 promiscuous_mode = 1 # may need to set timeout_ms to something non-zero, # otherwise the underlying (libpcap) packet capture loop iteration # can't complete until packets are actually captured timeout_ms = 0 cap = pcapy.open_live(nic_name, max_packet_size, promiscuous_mode, timeout_ms) bpf_filter = "tcp" cap.setfilter(bpf_filter) dumper = cap.dump_open(self._pcap_filename) while(True): #print 'in while' packet_hdr, packet_body = cap.next() #print 'yoda' if self._is_stop_packet(packet_body, self._stop_eth_addr): break dumper.dump(packet_hdr,packet_body) del dumper
def main(): global options global args global pcapWriter global pc # parse command line arguments parser = OptionParser() parser.add_option("-i", "--interface", dest="interface", help="network interface to listen on") parser.add_option("-s", "--filesizelimit", dest="filesizelimit", help="Maximum pcap filesize, in MB") parser.add_option("-t", "--maxseconds", dest="maxsecondsinterval", help="Maximum duration for a pcap file to cover, in seconds.") parser.add_option("-f", "--filenamesuffix", dest="filenamesuffix", help="Suffix to add after timestamp in filename.") (options, args) = parser.parse_args() # list all the network devices pcapy.findalldevs() max_bytes = 1500 promiscuous = True read_timeout = 100 pc = pcapy.open_live(options.interface, max_bytes, promiscuous, read_timeout) pcapWriter = PcapFileWriter(pc, options.maxsecondsinterval, options.filesizelimit, options.filenamesuffix) packet_limit = -1 pc.loop(packet_limit, process_packets)
def loop(): cap = pcapy.open_live("en0", 65565, 1, 0) while True: header, packet = cap.next() eth_header_length = 14 eth_header_raw = packet[:eth_header_length] eth_header = unpack("!6s6sH", eth_header_raw) eth_protocol = socket.ntohs(eth_header[2]) if eth_protocol != 8: print "Bad protocol" raw_data = packet[eth_header_length:] ip_header_raw = raw_data[:20] ip_header = unpack("!BBHHHBBHII", ip_header_raw) version_ihl = ip_header[0] version = version_ihl >> 4 ip_header_length = (version_ihl & 0xF) * 4 print "=" * 80 print "IP Header" print "Version: ", version, "IP Header length: ", str(ip_header_length) print "=" * 80 protocol = ip_header[6] if protocol == 6: tcp_header_raw = raw_data[ip_header_length : ip_header_length + 20] tcp_header = unpack("!HHIIBBHHH", tcp_header_raw) source = tcp_header[0] destination = tcp_header[1] sequence = tcp_header[2] offset = tcp_header[5] >> 4 h_size = ip_header_length + offset * 4 print "TCP Header" print "Source: ", source, "Destination: ", destination print "Sequence: ", sequence, "TCP header length: ", offset print "Data:" print str(raw_data[h_size:]) elif protocol == 17: print "UDP" # pass # udp_header_length = 8 # udp_header_raw = raw_data[ip_header_length:ip_header_length + udp_header_length] # udp_header = unpack('!HHHH', udp_header_raw) # data = packet[ip_header_length + udp_header_length:] # print data print "=" * 80
def main(ip, filter): dev = getInterface() # Open interface for catpuring. p = open_live(dev, 1500, 0, 100) # Set the BPF filter. See tcpdump(3). p.setfilter(filter) print "Listening on %s: net=%s, mask=%s, linktype=%d" % (dev, p.getnet(), p.getmask(), p.datalink()) q = Queue.Queue() # Start the holiday visualiser pulses = pulse.Pulser(ip, q, WAIT_T) pulses.start() # Start sniffing thread and finish main thread. dt = DecoderThread(p, q) dt.start() while True: try: time.sleep(0.01) except KeyboardInterrupt: dt.terminate = True pulses.terminate = True sys.exit(0)
def live(self,dev,loop=500): """ open device Arguments here are: device snaplen (maximum number of bytes to capture _per_packet_) promiscious mode (1 for true), need False for OSX timeout (in milliseconds) """ # check for sudo/root privileges if os.geteuid() != 0: exit('You need to be root/sudo for real-time ... exiting') # real-time cap = pcapy.open_live(dev , 2048 ,False, 50) #cap.setfilter('udp') self.map = [] self.p = PacketDecoder() #start sniffing packets while(loop): try: loop -= 1 (header, data) = cap.next() except KeyboardInterrupt: print 'You hit ^C, exiting PassiveMapper ... bye' exit() except: continue self.process(header,data) return self.map
def main(): dev = 'en1' # Open interface for catpuring. p = open_live(dev, 1500, 0, 100) # Set the BPF filter. See tcpdump(3). p.setfilter('tcp port 80') # only capture http packets print "Listening on %s: net=%s, mask=%s, linktype=%d" % (dev, p.getnet(), p.getmask(), p.datalink()) # Start sniffing thread and finish main thread. DecoderThread(p).start() try : while 1 : time.sleep(1) except KeyboardInterrupt : print "\nClosing OSCServer." server.close() print "Waiting for Server-thread to finish" # st.join() ##!!! print "Done"
def main(argv, selected_device): ''' Description : main function of packet sniffer program input_param : argv - command line params input_type : list input_param : selected_device - selected interface name input_type : string ''' settings.packet_reader = pcapy.open_live(selected_device , 65536 , 1 , 0) settings.dump_file_writer = settings.packet_reader.dump_open(settings.dump_file) settings.packet_reader.setnonblock(True) filters = ' '.join(argv) if argv else '' try: settings.packet_reader.setfilter(filters) except pcapy.PcapError: logger.error("Syntax error in options : {0}".format(filters)) logger.info("For Options syntax, Please refer the link http://biot.com/capstats/bpf.html") sys.exit(-1) #start sniffing packets while True : settings.packet_reader.dispatch(1, dump_packet)
def run(self): header = None payload = None cap = pcapy.open_live(self.args.interface, 2048, 1, 0) #f = 'dst host ' + self.args.source + ' and port 80 and (\ # tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420 or \ # tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354 or \ # tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x48545450 or \ # tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x484541444552\ # )' #f = 'dst host ' + self.args.source + ' and tcp dst port 80' cap.setfilter(self.args.filter) logger.info("Listening on %s: net=%s, mask=%s, linktype=%d" % (self.args.interface, cap.getnet(), cap.getmask(), cap.datalink())) # create a couple of regexs isHTTP = re.compile(r'((GET|POST|HEAD)\s+.*\s+HTTP/1.(1|0))') contentLength = re.compile(r'Content-Length:\s+(\d+)') # see if we can get data from the network interface try: (header, payload) = cap.next() except Exception, e: print 'Capture exception, retrying: %s' % str(e) (header, payload) = cap.next()
def run_pcap(f): def recv_packet(hdr, data): global now, current_data_received, current_data_sent # Fire off the aggregates to the main thread once per second. # This is both because we work on second resolution, and because # firing this for every packet is VERY expensive in Twisted if int(time.time()) != now: reactor.callFromThread(f, now, current_data_received, current_data_sent) current_data_received = defaultdict(int) current_data_sent = defaultdict(int) now = int(time.time()) #src_mac = data[0:6] #dst_mac = data[6:12] src_ip = data[26:30] dst_ip = data[30:34] data_len = hdr.getlen() current_data_received[dst_ip] += data_len current_data_sent[src_ip] += data_len # IP traffic that is leaving or arriving in the specified network, and not staying within it PCAP_FILTER = 'ip and ((src net %s and not dst net %s) or (dst net %s and src net not %s))' \ % tuple([CIDR_RANGE] * 4) MAX_LEN = 35 # We only need the first 35 bytes of a packet MAX_PKTS = -1 # -1 == No limit PROMISCUOUS = 0 READ_TIMEOUT = 100 p = open_live(DEV, MAX_LEN, PROMISCUOUS, READ_TIMEOUT) p.setfilter(PCAP_FILTER) p.loop(MAX_PKTS, recv_packet)
def __init__(self, trigger): self.trigger = trigger pc = pcapy.open_live("wlan0", self.max_bytes, self.promiscuous, self.read_timeout) pc.setfilter("tcp") pc.setfilter("dst port 80 or src port 80") # print "Listening on eth0: net=%s, mask=%s, linktype=%d" % (pc.getnet(), pc.getmask(), pc.datalink()) pc.loop(-1, self.recv_pkts)
def sniffing(): global lastFetched global localBiddingRound global bidRound cap = pcapy.open_live(interface , 65536 , 0 , 0) #while bidRound < 5 : while True: (header, packet) = cap.next() #function to parse a packet result = parse_packet(packet) if result is not None: if result == '1.2.3.4': bidRound += 1 print lastFetched content = randomRequestGenerator() packet = Ether() / IP(dst="10.0.0.255") / content sendp(packet, iface=interface, count=1) if result == '1.2.3.5': #parse JSON first parsed_json = json.loads(lastFetched) print 'Get a reminder from the server, start transmitting..' destIP = parsed_json['destIP'] bandwidth = parsed_json['bandwidth'] duration = parsed_json['duration'] data = parsed_json['data'] pSend = threading.Thread(target=udpSend, args=(destIP, bandwidth, duration, data)) pSend.start()
def main(argv): dev = listen_to cap = pcapy.open_live(dev , 65536 , 1 , 0) while(1) : (header, packet) = cap.next() parse_packet(packet)
def listen(self): info('listening... on %s ..' % self.iface) while self.active: try: self.cap = pcapy.open_live(self.iface, self._max_len, self._promisc, self._read_timeout) if self.usefilter: self.cap.setfilter(self.pcap_filter) if self.logpcap: self.pcapture() debug('%s: net=%s, mask=%s, linktype=%s' % \ (self.iface, self.cap.getnet(), self.cap.getmask(), self.cap.datalink())) self.cap.loop(-1, self.pktcb) except Exception as e: if self.errors > self.max_errors: self.error('I cant work in an environment like this. Bye.') self.do_exit() finally: if self.active: self.error('error(%d) while sniffing: %s' % ( self.errors, e )) info('sleeping for %d seconds' % (self.errors * 4)) time.sleep(self.errors * 4)
def main(self): # Parse flags # Arguments here are: # device # snaplen (maximum number of bytes to capture _per_packet_) # promiscious mode (1 for true) # timeout (in milliseconds) if isfile(self.dumpfile): remove(self.dumpfile) self.keep_running = True self.cap = pcapy.open_live(self.iface, 1518, 1, 0) self.dumper = self.cap.dump_open(self.dumpfile) try: #self.cap.loop(0, self.pkt_handler) (header, payload) = self.cap.next() while header: self.pkt_handler(header, payload) if self.keep_running is False: break (header, payload) = self.cap.next() except KeyboardInterrupt: print 'shutting down'
def producer(args): # connect to kafka producer = kafka.KafkaProducer( bootstrap_servers=args.kafka_brokers.split(","), partitioner=partitioner) # initialize packet capture capture = pcapy.open_live(args.interface, 65535, True, 3000) packet_count = 0 # start packet capture while True: (pkt_hdr, pkt_raw) = capture.next() if pkt_hdr is not None: # send packet to kafka pkt_ts = timestamp(pkt_hdr) producer.send(args.topic, key=pack_ts(pkt_ts), value=pkt_raw) # debug messages, if needed packet_count += 1 if args.debug > 0 and packet_count % args.debug == 0: print 'Sent Packet: count=%s dt=%s topic=%s' % ( packet_count, to_date(pkt_ts), args.topic) print to_hex(pkt_raw)
def main(argv): # Parse flags #try: #argv = FLAGS(argv) #except gflags.FlagsError, e: #print FLAGS # Arguments here are: # device # snaplen (maximum number of bytes to capture _per_packet_) # promiscious mode (1 for true) # timeout (in milliseconds) cap = pcapy.open_live('wlan0', 100, 1, 0) cap.setfilter('tcp') cap.setfilter('dst port 80') print "Listening on %s: net=%s, mask=%s, linktype=%d" % ('wlan0', cap.getnet(), cap.getmask(), cap.datalink()) # Read packets -- header contains information about the data from pcap, # payload is the actual packet as a string (header, payload) = cap.next() while header: print payload print ('%s: captured %d bytes, truncated to %d bytes' %(datetime.datetime.now(), header.getlen(), header.getcaplen())) (header, payload) = cap.next()
def do_capture(INTERFACE_TO_MONITOR): ''' Arguments here are: open_live(INTERFACE_TO_MONITOR,(maximum number of bytes to capture _per_packet_),promiscious mode (1 for true), timeout (in milliseconds) ''' cap = pcapy.open_live(INTERFACE_TO_MONITOR, 65536, 1, 0) logthis.log("PACKET-CAP","Starting to Capture") logthis.log("PACKET-CAP","Waiting for PCAP-PROCESSING MODULE") c, addr = ss.accept() logthis.log("PACKET-CAP","CONNECTION ACCEPTED - LOCAL SOCKET ESTABLISHED") # Read packets -- header contains information about the data from pcap, # payload is the actual packet as a string while 1: (header,payload)=cap.next() the_packet= (header,payload) eth = dpkt.ethernet.Ethernet(payload) if eth.type!=dpkt.ethernet.ETH_TYPE_IP: continue ip = eth.data if ip.p!=dpkt.ip.IP_PROTO_TCP: #Check for TCP packets continue tcp = ip.data c.send((str(tcp.data).encode("hex"))) if tcp.dport == 80 and len(tcp.data) > 0: http = dpkt.http.Request(tcp.data) c.send(str(http))
def main(argv): #http://stackoverflow.com/questions/6347115/python-icmpv6-client table = [] #if(len(sys.argv) >= 4): iface = sys.argv[1] #getting iface parameter # manet = sys.argv[2] #getting manet parameter # str_message = sys.argv[3] #mensage to sen trougth manet # if(iface == '' or manet == '' or str_message == ''): # print 'Parameter is incorrect' # print 'Usage main_interop.py <iface> <manet> <str_message>' # else: #setup_rules(iface) capture = pcapy.open_live(iface, 65536, 1, 0) #Caracteristicas del paquete capturado. pcap = pcs.PcapConnector(iface,64,True,1000) #main_socket = init_socket(iface) #thread.start_new_thread(read_socket,()) #read socket init print("\nWaiting...") a = 0 thread.start_new_thread(interop_beacon_generator,(iface,0,0.5)) #thread basic interop packet send 1 thread.start_new_thread(parse_packet,(capture,pcap,iface,table, )) #capture analisi thread.start_new_thread(read_socket_,(iface, )) #reading socket time.sleep(0.2) thread.start_new_thread(write_socket_,(table, )) #reading socket while(True): if(global_command == 'f'): print('Killing Threads...') thread.exit()
def main(): print '\n\t\nKnow source and destination of packet communicating with' devices = capfunc.devices() print '\nSelect from list of adapters\n' for i in devices: print devices.index(i), i devices_s = int(raw_input('Waiting for you to select Adapter!: ')) ret = str(capfunc.select(devices_s)) if ret == 'true': timeout = capfunc.timecheck() if timeout == 'false': print '\nI said dnt fuzz with me, Here is punishment, start from again' main() t_ms = timeout*1000 get_d = devices[devices_s] cap = pcapy.open_live(get_d , 65536 , 1 , t_ms) timeout = time.time() + timeout while (1): if time.time() > timeout: break try: (header, packet) = cap.next() eth_header = packet[:14] eth = unpack('!6s6sH' , eth_header) source = decode_hex(eth_header[:6]) dest = decode_hex(eth_header[6:12]) print 'Source MAC address is', source, ' Destination MAC address is', dest except Exception,e: print 'Timeout in capturing this packet'
def main(argv): #list all devices devices = pcapy.findalldevs() print devices #ask user to enter device name to sniff print "Available devices are :" for d in devices : print d dev = raw_input("Enter device name to sniff : ") print "Sniffing device " + dev ''' open device # Arguments here are: # device # snaplen (maximum number of bytes to capture _per_packet_) # promiscious mode (1 for true) # timeout (in milliseconds) ''' cap = pcapy.open_live(dev , 65536 , 1 , 0) #start sniffing packets while(1) : (header, packet) = cap.next() #print ('%s: captured %d bytes, truncated to %d bytes' %(datetime.datetime.now(), header.getlen(), header.getcaplen())) parse_packet(packet)
def launch(self): """ Main cycle of sniffing the traffic """ # opening pcap on the setted interface cap = pcapy.open_live(self.interface,65536,1,0) # fix time when we start self.start_time = time() # Timer that sends ping to db every refresh_ping_time seconds rt_ping = RepeatedTimer(self.refresh_ping_time,self.process_ping) LOG.debug("Starting traffic collector agent") while (1) : (header, packet) = cap.next() (src,dst,leng,res) = self.parse_packet(packet) if not res: #print "Not res" continue pk = Packet(src,dst,leng) self.handle_packet(pk) # if the elapsed time is more then refresh_time # Send traffic information to db if time() - self.start_time > self.refresh_time: # reset timer self.start_time = time() self.process_bandwidth() self.send_traffic()
def launch(self,hostname,server_port): self.server_port = server_port #ipaddr = socket.gethostbyname(hostname) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s.connect((hostname, self.server_port)) print "Connected!" print "Listen on interface: " + self.interface cap = pcapy.open_live(self.interface,65536,1,0) self.start_time = clock() while (1) : (header, packet) = cap.next() sys.stdout.write("1") capt_time = clock() (src,dst,leng,res) = self.parse_packet(packet) if not res: continue pk = Packet(src,dst,leng) self.handle_packet(pk) #print str(capt_time) + " - " + str(self.start_time) if capt_time - self.start_time > self.refresh_time: print "Refreshed!" self.process_bandwidth(capt_time) self.process_traffic(capt_time,s) #msg = str(src) + '|' + str(dst) + '|' + str(leng) + ',' #print "Sending: " + msg #s.sendall(bytes(msg,'utf8')) #s.sendall(msg) s.close()
def go(): global ip1 global dev bpffilter = "dst host %s and not src host %s and !(tcp dst port 80 or tcp dst port 443) and (not host %s)" % ( ip1, ip1, adminip) cap = pcapy.open_live(dev, 255, 1, 0) cap.setfilter(bpffilter) logdns2proxy.info( "Starting sniffing in (%s = %s)...." % (dev, ip1)) #start sniffing packets while True: try: (header, packet) = cap.next() parse_packet(packet) except: pass
def __init__(self, device, snaplen, promisc, to_ms, monitor=False): # noqa: E501 if monitor: try: self.pcap = pcap.create(device) self.pcap.set_snaplen(snaplen) self.pcap.set_promisc(promisc) self.pcap.set_timeout(to_ms) if self.pcap.set_rfmon(1) != 0: warning("Could not set monitor mode") if self.pcap.activate() != 0: raise OSError("Could not activate the pcap handler") # noqa: E501 except AttributeError: raise OSError("Your pcapy version does not support" "monitor mode ! Use pcapy 0.11.4+") else: self.pcap = pcap.open_live(device, snaplen, promisc, to_ms) # noqa: E501
def run(self): if self.live: self.handler = pcapy.open_live(self.descriptor, -1, True, 100) else: self.handler = pcapy.open_offline(self.descriptor) self.handler.setfilter(self.filter) params = (self.descriptor, self.handler.getnet(), self.handler.getmask(), self.handler.datalink()) print('Listening on {}: net={}, mask={}, linktype={}'.format(*params)) print('filter: {}'.format(self.filter)) while not self.quit: hdr, raw = self.handler.next() if hdr: self.process(hdr, Ether(raw)) for dumper in self.streams.values(): dumper.close()
def go(): global ip global dev bpffilter = "dst host %s and not src host %s and !(tcp dst port 80 or tcp dst port 443) and (not host %s)" % ( ip, ip, adminip) cap = pcapy.open_live(dev, 255, 1, 0) cap.setfilter(bpffilter) print "Starting sniffing in (%s = %s)...." % (dev, ip) #start sniffing packets while (1): try: (header, packet) = cap.next() parse_packet(packet) except: a = 1
def capture_dhcp(itf): f = open(target, 'w') reader = pcapy.open_live(itf, 4096, False, 5000) reader.setfilter('udp dst port 67') def callback(header, packet): hwaddr = hwaddr_ascii(packet) logger.info('Captured dhcp request from %s', hwaddr) f.write(hwaddr + '\n') f.flush() try: while True: reader.dispatch(1, callback) except KeyboardInterrupt: pass
def producer(args, sniff_timeout_ms=500, sniff_promisc=True): """ Captures packets from a network interface and sends them to a Kafka topic. """ # setup the signal handler signal.signal(signal.SIGINT, signal_handler) global producer_args producer_args = args # connect to kafka logging.info("Connecting to Kafka; %s", args.kafka_configs) kafka_producer = Producer(args.kafka_configs) # initialize packet capture logging.info("Starting packet capture") capture = pcapy.open_live(args.interface, args.snaplen, sniff_promisc, sniff_timeout_ms) pkts_in = 0 try: while not finished.is_set() and (args.max_packets <= 0 or pkts_in < args.max_packets): # capture a packet (pkt_hdr, pkt_raw) = capture.next() if pkt_hdr is not None: logging.debug("Packet received: pkts_in=%d, pkt_len=%s", pkts_in, pkt_hdr.getlen()) pkts_in += 1 pkt_ts = timestamp(pkt_hdr) kafka_producer.produce(args.kafka_topic, key=pack_ts(pkt_ts), value=pkt_raw, callback=delivery_callback) # pretty print, if needed if args.pretty_print > 0 and pkts_in % args.pretty_print == 0: print 'Packet received[%s]' % (pkts_in) # serve the callback queue kafka_producer.poll(0) finally: # flush all messages logging.info("Waiting for '%d' message(s) to flush", len(kafka_producer)) kafka_producer.flush() # pkts_out may not be initialized if the callback was never executed pkts_out = 0 if hasattr(delivery_callback, "pkts_out"): pkts_out = delivery_callback.pkts_out logging.info("'%d' packet(s) in, '%d' packet(s) out", pkts_in, pkts_out)
def __init__(self, interface, network, default, elements, loggers, tunnels): """Function initialized the dipatcher Args: interface : name of the network interface to listen network : networkx graph representation of the network default : default template elements : elements of the network loggers : instances of the logger modules tunnels : tunnel configuration """ self.interface = interface self.mac = netifaces.ifaddresses( self.interface)[netifaces.AF_LINK][0]['addr'] self.network = network try: post('http://localhost:8080/network', json=dumps(json_graph.node_link_data(self.network))) except: logger.exception('Exception: Cannot connect to local server.') self.default = default self.devices, self.routes, self.externals = elements self.hpfeeds, self.dblogger = loggers self.tunnels = tunnels self.packet_queue = dict() self.entry_points = list() self.unreach_list = list() self.pcapy_object = pcapy.open_live(self.interface, 65535, 1, 10) self.decoder = ImpactDecoder.EthDecoder() self.ip_decoder = ImpactDecoder.IPDecoder() self.ip_icmp_decoder = ImpactDecoder.IPDecoderForICMP() self.mac_set = set([self.mac]) for d in self.devices: if len(d.mac): self.mac_set.add(d.mac) for r in self.routes: if r.entry: self.entry_points.append(r) self.unreach_list.extend(r.unreach_list) logger.info('Started dispatcher listening on interface %s', self.interface) while True: try: (hdr, pkt) = self.pcapy_object.next() self.callback(hdr, pkt) except KeyboardInterrupt: return
def liveMonitoring(interface, pktCount, timer, collectionName, connection, DB_NAME): COLLECTION_NAME = collectionName collection = connection[DB_NAME][COLLECTION_NAME] capture = pcapy.open_live(interface, 1600, True, 100) print 'opened interface' i = 0 t1 = time.clock() timerLocal = setTimer(timer) pktCountLocal = setCounter(pktCount) print 'start Loop' while 1: try: (header, payload) = capture.next() except pcapy.PcapError: continue else: if not payload: val = 0 else: val = 1 bacnetPktcomplete = decodePaket(header, payload, False) result = collection.insert_one(bacnetPktcomplete) i = i + val t2 = time.clock() if i > pktCountLocal: print "Counter Exceeded" print i break if (t2 - t1) > timerLocal: print "Timer Exceeded" print timerLocal break
def init(): """ Performs sensor initialization """ global _cap global _datalink def update_timer(): _ = update(server=config.UPDATE_SERVER) if _: trails.clear() trails.update(_) elif not trails: trails.update(load_trails()) thread = threading.Timer(config.UPDATE_PERIOD, update_timer) thread.daemon = True thread.start() update_timer() create_log_directory() if check_sudo() is False: exit("[x] please run with sudo/Administrator privileges") if subprocess.mswindows and (config.MONITOR_INTERFACE or "").lower() == "any": exit("[x] virtual interface 'any' is not available on Windows OS") if config.MONITOR_INTERFACE not in pcapy.findalldevs(): print "[x] interface '%s' not found" % config.MONITOR_INTERFACE exit("[!] available interfaces: '%s'" % ",".join(pcapy.findalldevs())) print "[i] opening interface '%s'" % config.MONITOR_INTERFACE try: _cap = pcapy.open_live(config.MONITOR_INTERFACE, SNAP_LEN, True, 0) except socket.error, ex: if "permitted" in str(ex): exit("\n[x] please run with sudo/Administrator privileges") elif "No such device" in str(ex): exit("\n[x] no such device '%s'" % config.MONITOR_INTERFACE) else: raise
def main(argv): global filter_port if len(argv) == 1: try: filter_port = int(argv[0]) except ValueError: print "Invalid port number" sys.exit(1) print "[+] Starting sniffer" pcap_obj = open_live("eth0", 65536, False, True) try: pcap_obj.loop(-1, parse_udp) except KeyboardInterrupt: print "[!] Exiting" sys.exit(0)
def write_pcap(filename, interface): pcapy.findalldevs() max_bytes = 2048 promiscuous = False read_timeout = 100 pc = pcapy.open_live(interface, max_bytes, promiscuous, read_timeout) dumper = pc.dump_open(filename + ".pcap") signal.signal(signal.SIGTERM, signal_term_handler) try: pc.setfilter('udp') def recv_pkts(hdr, data): dumper.dump(hdr, data) packet_limit = -1 #infinite pc.loop(packet_limit, recv_pkts) except BaseException: pc.close()
def open_iface(iface): ok = False while not ok: try: os.system('sudo ifconfig %s up' % iface) cap = pcapy.open_live(iface , 65536 , 1 , 0) if CAPTURE_PROBES_ONLY: cap.setfilter('wlan type mgt subtype probe-req') else: cap.setfilter('wlan type mgt subtype probe-req || wlan type data || wlan type ctl subtype ps-poll') ok = True except pcapy.PcapError as e: logger.warning("Unable to bring interface %s up, retrying in 1s..." % iface) logger.error("Error: %s" % e) time.sleep(1) logger.info("Interface %s up." % iface) return cap
def __init__(self, iface): self.devices = dict() self.pd = pcapy.open_live(iface, helpers.PCAP_SNAPLEN, helpers.PCAP_PROMISCOUS, helpers.PCAP_TIMEOUT) # Filter Action frames with an specific BSSID Address bpf_filter = "wlan[0] = 0xd0 and wlan addr3 00:25:00:ff:94:73" self.pd.setfilter(bpf_filter) datalink = self.pd.datalink() if datalink == helpers.PCAP_DLT_IEEE802_11: self.decoder = ImpactDecoder.Dot11Decoder() elif datalink == helpers.PCAP_DLT_IEEE802_11_RADIOTAP: self.decoder = ImpactDecoder.RadioTapDecoder() else: raise Exception("Invalid datalink.") self.run()
def start_packet_capture(): print('Packet capture starting on ' + INTERFACE) time.sleep(1) capture = pcapy.open_live(INTERFACE, 1514, 1, 10) capture.setfilter('subtype probe-req') while True: try: header_type = capture.datalink() (header, pkt) = capture.next() if header_type == 0x7F and len( pkt) > 0: # 0x7F/127 RadioTap header packet_handler(header, pkt) except KeyboardInterrupt: global SHUTDOWN SHUTDOWN = True disable_monitor_mode() break
def run(self): #执行监听 capture = pcapy.open_live(self.__device, 65536, 1, 0) #将网卡设置为混杂模式 if len(self.__filter) != 0: #有过滤条件 try: #设置过滤规则,并检测输入的过滤规则是否有误 capture.setfilter(self.__filter) except: self.__showErrorSignal.emit() #向主线程发送过滤规则有误信号 return while self.__runTag: #循环直至runTag为0 (head, data) = capture.next() #捕获数据包 if head != None: resolveObj = Resolve() res = resolveObj.resolve(head, data) #交由解析对象解析数据包 if res != None: res["originalHex"] = data.hex() self.__resList.append(res) self.__getDataSignal.emit() #通知主界面此时可以获取数据
def main(): print "Server.... Port: 62001" print "--------------------------------------------" p = open_live('lo', 46, False, 100) print "Listening...." p.setfilter("udp") p.setfilter("src port 62000") #p.setfilter("ip dst 127.0.1.12") #p.setfilter("src port 32014") #signal.setitimer(signal.ITIMER_VIRTUAL,3) #signal.alarm(100) p.loop(4, EthDecoder1) #loop(no of packets to wait for, function to decode)
def packet_sniffer(self, sniffer_card, is_source): global GLOBAL_IS_EXIT # 监听网卡上的包 pc = pcapy.open_live(sniffer_card, 10240, True, 2000) while True: try: if GLOBAL_IS_EXIT: print "exit thread loop... sub process %s will be exit." % threading.currentThread().getName() break packet_time, packet_data = pc.next() target_data = self.filter_packet(packet_time, packet_data, is_source) if target_data is not None: if CHANGE_DATA_EVENT: self.notify("change_packet_data_%s" % self.thread_name, target_data) self.forward_packet(target_data) except: continue
def open_iface(iface): ok = False while not ok: try: os.system( 'sudo ifconfig %s down && sudo iwconfig %s mode monitor && sudo ifconfig %s up' % (iface, iface, iface)) cap = pcapy.open_live(iface, 65536, 1, 0) cap.setfilter('wlan type mgt subtype probe-req') ok = True except pcapy.PcapError: logger.error( "Unable to bring interface %s up, retrying in 1s... Are you root?" % iface) time.sleep(1) logger.info("Interface %s up." % iface) return cap
def start(self): """ Sniffer.start() - Start the sniffer. Args: None. Returns: tuple: (True/False, None/exception message). """ try: self.sniffer = pcapy.open_live(self.interface, self.snaplen, self.promisc, self.timeout) except pcapy.PcapError as exc: return (False, exc) self.sniffer.setfilter(self.bpf) return (True, None)
def main(argv): # list all devices devices = pcapy.findalldevs() # print devices print '-- Sniffer v1.0 - Por Amilton e Dafny - 2016 --' print # ask user to enter device name to sniff print "Interfaces disponiveis sao:" print devices # for d in devices: # print d # dev = raw_input("Enter device name to sniff: ") dev = "any" print "\nCapturando em todas as interfaces..." ''' open device # Arguments here are: # device # snaplen (maximum number of bytes to capture _per_packet_) # promiscious mode (1 for true) # timeout (in milliseconds) ''' max_bytes = 1024 promiscuous = False read_timeout = 100 # in milliseconds cap = pcapy.open_live(dev, max_bytes, promiscuous, read_timeout) ''' # start sniffing packets while(1): (header, packet) = cap.next() time_cap = datetime.datetime.now() bytes_cap = header.getlen() bytes_trunc = header.getcaplen() parse_packet(packet, time_cap, bytes_cap, bytes_trunc) # time.sleep(0.05) ''' packet_limit = -1 # infinite cap.loop(packet_limit, parse_packet) # capture packets
def configure(self, configuration): BaseThreadedModule.configure(self, configuration) self.interface = self.getConfigurationValue('interface') self.promiscous_mode = 1 if self.getConfigurationValue('promiscous') else 0 self.kv_store = self.getConfigurationValue('key_value_store') if self.getConfigurationValue('key_value_store') else {} self.packet_decoders = {} for ether_type, ether_protocol in PROTOCOL_TO_NAMES.items(): if "decodePacket%s" % ether_protocol in dir(self): self.packet_decoders[ether_type] = getattr(self, "decodePacket%s" % ether_protocol) try: self.sniffer = pcapy.open_live(self.interface, 65536, self.promiscous_mode, 100) except: etype, evalue, etb = sys.exc_info() self.logger.error("Sniffer could not be created. Exception: %s, Error: %s." % (etype, evalue)) self.lumbermill.shutDown() if self.getConfigurationValue('packetfilter'): self.sniffer.setfilter(self.getConfigurationValue('packetfilter')) self.link_layer = self.sniffer.datalink()
def __capture(self): ''' Worker method called on run''' logger.info("Starting capture") cap = pcapy.open_live(self.dev, 1000, 1, 0) # Read packet -- header contains information about the data from pcap, # payload is the actual packet as a string (header, payload) = cap.next() while header: #p = Ether(payload) #p.show2() packet = ''.join( [ "%02X " % ord( x ) for x in payload[12:14] ] ).strip() if packet == "86 DD": #print packet self.__submit(payload) if not self.run: return (header, payload) = cap.next()
def sniffingThread(self, device, count, time): logging.info("Launching sniff process on dev {0} with: count={1}, timeout={2}, filter=\"{3}\"".format(device, count, time, self.bpfFilter)) sniffer = pcapy.open_live(device, 1024, False, int(time)) try: sniffer.setfilter(self.bpfFilter) except: logging.warn("The provided filter is not valid (it should respects the BPF format") return self.datalink = sniffer.datalink() if self.datalink != pcapy.DLT_EN10MB and self.datalink != pcapy.DLT_LINUX_SLL: errorMessage = _("This device cannot be sniffed since the " + "layer 2 is not supported ({0})").format(str(self.datalink)) self.log.warn(errorMessage) raise NetzobImportException("PCAP", errorMessage, ERROR, self.INVALID_LAYER2) else: sniffer.loop(int(count), self._packetHandler)
def capture_frames_from_live(self, interface): """capture_frames_from_live() Open a pcap live session and capture frames from an interface. """ self.module_logger.info("Opening live capture session on interface " + interface) # Set max length for frames to not truncate them and set no read timeout. capture_descriptor = pcapy.open_live(interface, 65535, 0, 0) # Next is needed for thread control because loop can't be aborted via condition, and function has to return. while not self.stop_thread: (header, data) = capture_descriptor.next() if header and data: self.decode_WLAN_frame(header, data) else: break
def read_from_pcapy(): import pcapy dir(pcapy) # pcapy.findalldevs() pc = pcapy.open_live('eth1', 1024, False, 100) pc.setfilter('tcp and host 192.168.1.106 and ( port 5400 or port 5500 )') from impacket.ImpactDecoder import TCPDecoder # callback for received packets def recv_pkts(hdr, data): packet = TCPDecoder().decode(data) print(packet) # packet_limit = -1 # infinite packet_limit = 10 pc.loop(packet_limit, recv_pkts) # capture packets
def start_capture(self): self.pcap_writer = dpkt.pcap.Writer(open(self.out_pcap_file_path, "w")) p = pcapy.open_live(self.intf_name, 65535, True, 1) #p.setnonblock(0) """ while True : try: header,data = p.next() if header != None : self.handle_packet(header,data) #time.sleep(0.5) except socket.timeout: #time.sleep(0.1) continue """ #try: p.loop(-1, self.handle_packet)
def main(argv, dev): #list all devices devices = pcapy.findalldevs() print devices ''' open device # Arguments here are: # device # snaplen (maximum number of bytes to capture _per_packet_) # promiscious mode (1 for true) # timeout (in milliseconds) ''' cap = pcapy.open_live(dev , 65536 , 1 , 0) #start sniffing packets while(1) : (header, packet) = cap.next() parse_packet(packet)
def ReadHdr(): cap = pcapy.open_live("ens33", 65536, 1, 500) while 1: (header,payload) = cap.next() l2hdr = payload[:14] if l2hdr != '': l2data = unpack("!6s6sH", l2hdr) srcmac = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(l2hdr[0]), ord(l2hdr[1]), ord(l2hdr[2]), ord(l2hdr[3]), ord(l2hdr[4]), ord(l2hdr[5])) dstmac = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(l2hdr[6]), ord(l2hdr[7]), ord(l2hdr[8]), ord(l2hdr[9]), ord(l2hdr[10]), ord(l2hdr[11])) print("Source MAC: ", srcmac, " Destination MAC: ", dstmac) #get IP header, which is 20 bytes long #then unpack it into what it is ipheader = unpack('!BBHHHBBH4s4s', payload[14:34]) timetolive = ipheader[5] protocol = ipheader[6] print("Protocol ", str(protocol), "Time To Live: ", str(timetolive))
def read_headers_from_packets(): cap = pcapy.open_live("eth0", 65536, 1, 0) while 1: (header, payload) = cap.next() l2hdr = payload[:14] l2data = unpack("!6s6sH", l2hdr) srcmac = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(l2hdr[0]), ord( l2hdr[1]), ord(l2hdr[2]), ord(l2hdr[3]), ord( l2hdr[4]), ord(l2hdr[5])) dstmac = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(l2hdr[6]), ord( l2hdr[7]), ord(l2hdr[8]), ord(l2hdr[9]), ord( l2hdr[10]), ord(l2hdr[11])) print("Source MAC: ", srcmac, " Destination MAC: ", dstmac) # get IP header from bytes 14 to 34 in payload ipheader = unpack('!BBHHHBBH4s4s', payload[14:34]) timetolive = ipheader[5] protocol = ipheader[6] print("Protocol ", str(protocol), " Time To Live: ", str(timetolive))
def __init__(self, bridge, subnet, arptable): # Open interface for capturing. self.pcap = open_live(bridge.bridgename, 65536, 1, 100) # Query the type of the link and instantiate a decoder accordingly. datalink = self.pcap.datalink() if pcapy.DLT_EN10MB == datalink: self.decoder = EthDecoder() elif pcapy.DLT_LINUX_SLL == datalink: self.decoder = LinuxSLLDecoder() else: raise Exception("Datalink type not supported: " % datalink) self.bridge = bridge self.subnet = subnet self.arptable = arptable self.protocols = args.discovery_protos or self.protocols Thread.__init__(self)