Пример #1
0
        def __init__(self, interface, filters=None):
            pcap.lookupnet(interface)

            self.pc = pcap.pcapObject()
            self.pc.open_live(interface, 3200, False, 0)

            BasePcapWrapper.__init__(self, filters)
Пример #2
0
def capture():
    p = pcap.pcapObject()

    if len(sys.argv) == 2:
        if sys.argv[1] == '-d' or sys.argv[1] == '--dev':
            finddev.print_all_devs()
        elif sys.argv[1] == '-h' or sys.argv[1] == '--help':
            finddev.print_help()
        else:
            print '[-] Wrong order " %s' % sys.argv[1:], '"'
            print_help()
    elif len(sys.argv) == 4:
        if sys.argv[1] == '-c':
            dev = sys.argv[2]
            net, mask = pcap.lookupnet(dev)
            p.open_live(dev, 1600, 0, 100)
            p.setfilter(string.join(sys.argv[3:], ' '), 0, 0)
            try:
                while True:
                    p.dispatch(1, show_packet)
            except KeyboardInterrupt:
                print '[-] %s' % sys.exc_type
                print '[-] shutting down'
                print '[+] %d packets received, %d packets dropped, %d packets dropped by interface' % p.stats()
    else:
        print '[-] Wrong order " %s' % sys.argv[1:], '"'
        print_help()
Пример #3
0
def main() :
    global mode

    if len(sys.argv) < 2:
        print 'usage: %s <interface> ' % sys.argv[0]
        sys.exit(0)

    # MAIN PROGRAM
    if (len(sys.argv) >= 3) :
        if sys.argv[2] == 'ymsg' :
            mode = CAP_YMSG
        elif sys.argv[2] == 'post' :
            mode = CAP_POST
        elif sys.argv[2] == 'ftp' :
            mode = CAP_FTP

    p = pcap.pcapObject()
    dev = sys.argv[1]
    net, mask = pcap.lookupnet(sys.argv[1])

    p.open_live(dev, 1600, 1, 100)
    p.setfilter('tcp', 0, 0)

    p.setnonblock(1)
    p.loop(0, print_packet)
Пример #4
0
def main():
    sc = sniff()
    sc.toggleconnect()

    if len(sys.argv) < 3:
        print ('usage: sniff.py <interface> <expr>')
        sys.exit(0)
    p = pcap.pcapObject()
    dev = sys.argv[1]
    net, mask = pcap.lookupnet(dev)
    # note:    to_ms does nothing on linux
    p.open_live(dev, 1600, 0, 100)
    #p.dump_open('dumpfile')
    p.setfilter(string.join(sys.argv[2:],' '), 0, 0)

    # try-except block to catch keyboard interrupt.    Failure to shut
    # down cleanly can result in the interface not being taken out of promisc.
    # mode
    #p.setnonblock(1)
    try:
        while 1:
            p.dispatch(1, sc.print_packet)

    except KeyboardInterrupt:
        sc.toggleconnect()
        print ('%s' % sys.exc_type)
        print ('shutting down')
        print ('%d packets received, %d packets dropped, %d packets dropped by interface' % p.stats())


    '''#open session
Пример #5
0
 def __init__(self, name):
     """
     """
     self.name = name
     try:
         self.naddr, self.mask = pcap.lookupnet(self.name)
     except:
         self.naddr, self.mask = None, None
Пример #6
0
 def prepare(self, interface):
     sniffer = pcap.pcapObject()
     net, mask = pcap.lookupnet(interface)
     
     sniffer.open_live(interface, 1600, 0, 100)
     sniffer.setfilter('tcp port 80', 0, 0)
     
     self.sniffer = sniffer
Пример #7
0
def setupPort(port):
    p = pcap.pcapObject()
    dev = "eth0"
    net, mask = pcap.lookupnet(dev)
    p.open_live(dev, 1600, 0, 100)
    filterString = "port " + str(port)
    p.setfilter(filterString, 0, 0)
    return p
Пример #8
0
    def run(self):   
        p = pcap.pcapObject()
        dev = "eth0"
        net, mask = pcap.lookupnet(dev)
        p.open_live(dev, 1600, 0, 100)
        p.setfilter("tcp port 8000", 0, 0)

        while not self.thread_stop:  
            p.dispatch(1, self.print_packet)
Пример #9
0
 def __init__(self, callback, interface='en0'):
     super(Scrobbify, self).__init__()
     self._stop = threading.Event()
     
     self.callback = callback
     
     self.p = pcap.pcapObject()
     net, mask = pcap.lookupnet(interface)
     self.p.open_live(interface, 1600, 0, 100)
     self.p.setfilter(self.expr, 0, 0)
Пример #10
0
def sniff(argv, udp_obj):
  """Sniff packets using pcap libriry
  and call the method to send the SYN nomber to hte peer
  or to Connection Broker"""
 
  sys.argv = argv
  if len(sys.argv) < 3:
    print 'usage: sniff.py <interface> <expr>'
    sys.exit(0)
    
  dev = sys.argv[1]
  #p = pcap.pcap(dev)
  p = pcap.pcapObject()
  #dev = pcap.lookupdev()
  net, mask = pcap.lookupnet(dev)
  # note:  to_ms does nothing on linux
  p.open_live(dev, 1600, 0, 100)
  #p.dump_open('dumpfile')
  p.setfilter(string.join(sys.argv[2:],' '), 0, 0)

  # try-except block to catch keyboard interrupt.  Failure to shut
  # down cleanly can result in the interface not being taken out of promisc.
  # mode
  #p.setnonblock(1)
  #udp_obj = UDP_factory()
  #reactor.run()
  udp_obj.punchHole()
  try:
    while 1:
    #for ts, pkt in p:
    #for i in range(1,9):
      #print i
      #print_packet(ts, pkt)
      #p.dispatch(print_packet, -1)
      p.dispatch(1, udp_obj.send_SYN_to_ConnectionBroker)
      #p.loop(1, udp_obj.send_SYN_to_ConnectionBroker)
      
      #udp_obj.send_SYN_to_ConnectionBroker(ts, pkt)
      #break
      print 'break'
      break
    # specify 'None' to dump to dumpfile, assuming you have called
    # the dump_open method
    #  p.dispatch(0, None)

    # the loop method is another way of doing things
    #  p.loop(1, print_packet)

    # as is the next() method
    # p.next() returns a (pktlen, data, timestamp) tuple 
    #  apply(print_packet,p.next())
  except KeyboardInterrupt:
    print '%s' % sys.exc_type
    print 'shutting down'
    print '%d packets received, %d packets dropped, %d packets dropped by interface' % p.stats()
Пример #11
0
def decode_file(fname,res):
    if interface != None:
        try:
            p = pcap.pcapObject()
            net, mask = pcap.lookupnet(interface)
            p.open_live(interface, 1600, 0, 100)
            Message = " live capture started, using:%s\nStarting timestamp (%s) corresponds to %s"%(interface, time.time(), time.strftime('%x %X'))
            print Message
            #l.warning(Message)
            while 1:
                p.dispatch(1, Print_Packet_Tcpdump)
        except (KeyboardInterrupt, SystemExit):
            print '\n\nCRTL-C hit...\nCleaning up...'
            sys.exit()
    else:
        try:
            p = pcap.pcapObject()
            p.open_offline(fname)
            #l.warning('\n\n started, using:%s file'%(fname))
            Version = IsCookedPcap(res)
            if Version == 1:
                thread = Thread(target = p.dispatch, args = (0, Print_Packet_Cooked))
                thread.daemon=True
                thread.start()
                try:
                    while thread.is_alive():
                        thread.join(timeout=1)
                except (KeyboardInterrupt, SystemExit):
                    print '\n\nCRTL-C hit..Cleaning up...'
                    threading.Event().set()
            if Version == 2:
                thread = Thread(target = p.dispatch, args = (0, Print_Packet_Cooked))
                thread.daemon=True
                thread.start()
                try:
                    while thread.is_alive():
                        thread.join(timeout=1)
                except (KeyboardInterrupt, SystemExit):
                    print '\n\nCRTL-C hit..Cleaning up...'
                    threading.Event().set()
            if Version == 3:

                thread = Thread(target = p.dispatch, args = (0, Print_Packet_Tcpdump))
                thread.daemon=True
                thread.start()
                try:
                    while thread.is_alive():
                        thread.join(timeout=1)
                except (KeyboardInterrupt, SystemExit):
                    print '\n\nCRTL-C hit..Cleaning up...'
                    threading.Event().set()

        except Exception:
            print 'Can\'t parse %s'%(fname)
Пример #12
0
	def __init__(self,dev,filter):
		Thread.__init__(self)
		self.done = False;
		self.p = pcap.pcapObject()
		self.net, self.mask = pcap.lookupnet(dev)
		# open_live creates and opens the pcapture interface
		#   arguments are (device, snaplen, promisc, read_timeout_ms)
		#   note:    to_ms does nothing on linux
		#   promisc is 0, we don't open in promiscious mode
		self.p.open_live(dev, 1600, 0, 10)
		self.p.setfilter(filter, 0, 0)
		self.p.setnonblock(1)
Пример #13
0
def main():
    options, args = parse_options()
    
    p = pcap.pcapObject()
    device = sys.argv[1]
    net, mask = pcap.lookupnet(device)
    p.open_live(device, 1600, 0, 100)
    p.setfilter(options.filter, 0, 0)
    if options.mode.lower() == "offline":
        run_offline(p)
    else:
        run_live(p, options.logfile)
Пример #14
0
	def run(self):
		""" @brief Capture each packet and return list of filtered information.
		@param System Arguments: interface and port number to sniff on
		@return List of packets' arrival time, time from first arrived packet and the type of packet. """
		dev = "en0"
		p = pcap.pcapObject()
		net, mask = pcap.lookupnet(dev)
		try:
			p.open_live(dev, 65535, 0, 100)
			p.setfilter(string.join(sys.argv[2:],' '), 0, 0)
			logging.debug("Started packet capture module: Listening on %s: net=%s, mask=%s" % (dev, net, mask))
		except Exception, e:
			print "Started packet capture module: open_live() failed for device='%s'. Error: %s" % (dev, str(e))
def startListening(device):
	p = pcap.pcapObject()
	net, mask = pcap.lookupnet(device)
	p.open_live(device, 1600, 1, 100)
	print "Scanning on %s" % device
	
	try:
		while 1:
			p.dispatch(1, parse_packet)
			time.sleep(0.001)
	except KeyboardInterrupt:
		print '%s' % sys.exc_type
		print 'shutting down'
		print '%d packets received, %d packets dropped, %d packets dropped by interface' % p.stats()
Пример #16
0
 def sniff(self):
     p = pcap.pcapObject()
     dev = self.interface
     net, mask = pcap.lookupnet(dev)
     p.open_live(dev, 1600, 1, 100)
     p.setfilter("tcp src port %s" % self.port, 0, 0)
     try:
         while 1:
             p.dispatch(1, decode_packet)
     except KeyboardInterrupt:
         #scheduler.shutdown()
         print '%s' % sys.exc_type
         print 'shutting down'
         print '%d packets received, %d packets dropped, %d packets \
                 dropped by interface' % p.stats()
Пример #17
0
 def run(self):
     try:
         p = pcap.pcapObject()
         dev = netdev
         net, mask = pcap.lookupnet(dev)
         p.open_live(dev, 1600, 0, 100)
         if backend_ip:
             p.setfilter(filter_str + " and not host " + backend_ip, 0, 0)
         else:
             p.setfilter(filter_str, 0, 0)
         logging.info("start to sniffy...")
         while True:
             p.dispatch(1, store_packet)
     except:
         print "something wrong, exit!"
         os.kill(os.getpid(), 9)
Пример #18
0
def StartSniffer():
    p = pcap.pcapObject()
    dev = "eth0"
    net, mask = pcap.lookupnet(dev)
    
    p.open_live(dev, 1600, 0, 200)
    
    try:
        while 1:
            p.dispatch(1, print_packet)

    except KeyboardInterrupt:
        print ('%s' % sys.exc_type)
        print ('shutting down')
        cur.close()
        conn.close()
        sys.exit(1)
Пример #19
0
	def run(self):
		p = pcap.pcapObject()
    		#self.test_findalldevs()
    
    		#dev = pcap.lookupdev()
    		#dev = raw_input("please select an interface shown above:")
    		print 'run:',self.devi
    		net, mask = pcap.lookupnet(str(self.devi))
   		p.open_live(str(self.devi), 1600, 0, 100)
    		#rule=raw_input("please input your filtering rule:(protocol port num):")

		#rule should be given in filter
		#so self.ruleString might ....
		rule=str(self.filter_rule)
		print 'rule:'+rule
    		p.setfilter(rule,0,0)

    		try:
        		
    			if os.path.exists('/home/py_sniff/'+self.documentPath)==False:
				os.makedirs(r'/home/py_sniff/'+self.documentPath)
        		pkt_number=0
        		while 1:
            			dispatch_tuple=self.patch_a_packet(p)
            			if(dispatch_tuple!=None):
                			pkt_number=pkt_number+1
               				print '['+str(pkt_number)+']\n'
                			#print dispatch_tuple
            				#one packet one txt
            				(a,b,c,d,e,f)=self.print_and_save_packet(dispatch_tuple[0],dispatch_tuple[1],dispatch_tuple[2],self.documentPath,pkt_number)
            				print '==================================================='
#!!!!!!!!!!!!!!!!!!!!!addItem
					#stamp,source,destination,protocol,length,information
					
					self.emit(QtCore.SIGNAL('CAPTURE_ONE_PACKET'),pkt_number,a,b,c,d,e,f)
    		except KeyboardInterrupt:
        		print '%s' % sys.exc_type
        		print 'shutting down'
       			print '%d packets received, %d packets dropped, %d packets dropped by interface' % p.stats()
Пример #20
0
def main():
    global options
    global args
    global logfile_handle
    
    parse_options()
    set_exit_handler(on_shutdown)
    
    if options.logfile is not None:
        # open file handle
        logfile_handle = open(options.logfile, 'w')
    
    p = pcap.pcapObject()
    device = args[0]
    net, mask = pcap.lookupnet(device)
    p.open_live(device, 1600, 0, 100)
    p.setfilter(options.filter, 0, 0)

    try:
        while 1:
            p.dispatch(1, on_packet)
    except KeyboardInterrupt:
        on_shutdown()
        sys.exit(0)
Пример #21
0
      print '  %s: %d' % (key, decoded[key])
    print '  protocol: %s' % protocols[decoded['protocol']]
    print '  header checksum: %d' % decoded['checksum']
    print '  data:'
    dumphex(decoded['data'])
 

if __name__=='__main__':

  if len(sys.argv) < 3:
    print 'usage: sniff.py <interface> <expr>'
    sys.exit(0)
  p = pcap.pcapObject()
  #dev = pcap.lookupdev()
  dev = sys.argv[1]
  net, mask = pcap.lookupnet(dev)
  # note:  to_ms does nothing on linux
  p.open_live(dev, 1600, 0, 100)
  #p.dump_open('dumpfile')
  p.setfilter(string.join(sys.argv[2:],' '), 0, 0)

  # try-except block to catch keyboard interrupt.  Failure to shut
  # down cleanly can result in the interface not being taken out of promisc.
  # mode
  #p.setnonblock(1)
  try:
    while 1:
      p.dispatch(1, print_packet)

    # specify 'None' to dump to dumpfile, assuming you have called
    # the dump_open method
Пример #22
0
        decoded = LibVirtWakeOnLan.DecodeIPPacket(data[14:])
        macaddress = LibVirtWakeOnLan.GetMACAddress(decoded['data'])
        if not macaddress:
            return
        return  LibVirtWakeOnLan.StartServerByMACAddress(macaddress)

if __name__ == '__main__':
    from lvwolutils import Utils
    Utils.SetupLogging()

    # line below is replaced on commit
    LVWOLVersion = "20140814 231218"
    Utils.ShowVersion(LVWOLVersion)

    if len(sys.argv) < 2:
        print('usage: libvirtwol <interface>')
        sys.exit(0)

    interface = sys.argv[1]
    p = pcap.pcapObject()
    net, mask = pcap.lookupnet(interface)
    # set promiscuous to 1 so all packets are captured
    p.open_live(interface, 1600, 1, 100)
    # added support for ether proto 0x0842
    p.setfilter('udp port 7 or udp port 9 or ether proto 0x0842', 0, 0)

    try:
        while 1:
            p.dispatch(1, LibVirtWakeOnLan.InspectIPPacket)
    except KeyboardInterrupt:
        pass
Пример #23
0
        arp.tha = eth_aton("00:00:00:00:00:00")
        # Target protocol address:
        arp.tpa = socket.inet_aton(address)
        # Request to resolve ha given pa
        arp.op = dpkt.arp.ARP_OP_REQUEST

        eth = dpkt.ethernet.Ethernet()
        eth.src = arp.sha
        # Broadcast ARP request
        eth.dst = eth_aton(ETH_BROADCAST)
        eth.data = arp
        eth.type = dpkt.ethernet.ETH_TYPE_ARP
        print "ACTIVE: Sent ARP to {}".format(address)

        return pcap.sendpacket(str(eth))


# TODO: Make interface(s) configurable
print pcap.findalldevs()
interface = pcap.lookupdev()
local_net, local_mask = pcap.lookupnet(interface)
print "Listening on {}: {}/{}".format(interface, socket.inet_ntoa(local_net), socket.inet_ntoa(local_mask))

listener = Sniffer()
listener.daemon = True
listener.start()

pinger = Pinger()
pinger.daemon = True
pinger.start()
Пример #24
0
    def run(self):
        """Sniffer main function"""
        # Get logger
        logger = logging.getLogger()
        logger.info("Sniffer %i : Capture started on %s" % (self.id, self.dev))

        # Init
        last_update_t = time()
        last_save_t = time()
        capture = False

        # Optimizations
        db_on = self.database["on"]
        lmod = self.lmod
        term = self.terminated
        pipe_send_fnt = self.pipe_sender.send

        lfnt_pkthandle = list()
        lfnt_trigger_update = list()
        lfnt_trigger_save = list()
        for mod in lmod:
            lfnt_pkthandle.append(mod.pkt_handler)
            lfnt_trigger_update.append(mod.trigger_data_update)
            lfnt_trigger_save.append(mod.trigger_db_save)

        # List loaded module
        for mod in self.lmod:
            logger.info(
                "Sniffer %i : Load network module - websocket subprotocol " %
                (self.id) + mod.__str__())

        # Mysql database
        mydb = self.database["class"](
            host=self.database["conf"]["host"],
            user=self.database["conf"]["user"],
            passwd=self.database["conf"]["passwd"],
            database=self.database["conf"]["database"],
            port=self.database["conf"]["port"])

        if db_on:
            # connection to database
            mydb.connection()

            if mydb.is_connect():
                for mod in lmod:
                    mod.database_init(mydb)
                mydb.commit()

        # Get device informations if possible (IP address assigned)
        try:
            net, mask = pcap.lookupnet(self.dev)
        except:
            net, mask = "192.168.1.0", "255.255.255.0"

        # Create new pcap capture object
        p = pcap.pcapObject()

        try:
            # (Dev, buffer, promiscuous mode, timeout)
            p.open_live(self.dev, PCAP_PACKET_MAX_LEN, PCAP_PROMISCUOUS_MODE,
                        PCAP_SNIFFER_TIMEOUT)
            # keep it in an available object
            GetSniffer().set_sniffer(p)
            capture = True

            # Handler loop
            # tt = (0, 0)
            while not term.value:
                pkt = p.next()

                if pkt is not None:

                    # Decode packet
                    pktdec = Packet(pkt[0], pkt[1], pkt[2])
                    # a = time()
                    # send pkt to modules
                    map(lambda x: x(pktdec), lfnt_pkthandle)

                    # res = time() - a
                    # a, b = tt
                    # tt = (a+res, b+1)
                    # if tt[1] > 100:
                    #     print "Time sniff :", tt[0]/tt[1], "Time Tot :", tt[0]
                    #     tt = (0,0)

                # Modules update call
                if time() - last_update_t > MIN_TIME_MOD_UPDATE:
                    last_update_t = time()
                    l_res = list()
                    for mod in lmod:
                        data = mod.trigger_data_update()
                        if data is not None:
                            l_res.append((mod.protocol, data))

                    # Data to send with websocket
                    if len(l_res) > 0:
                        pipe_send_fnt(l_res)

                # Modules save call
                if db_on and mydb.connect is not None:
                    if time() - last_save_t > MIN_TIME_DB_UPDATE:
                        last_save_t = time()
                        map(lambda x: x(mydb), lfnt_trigger_save)
                        mydb.commit()

        except KeyboardInterrupt:
            logger.info("Sniffer %i : Interruption signal" % self.id)
        except Exception as e:
            logger.debug("Sniffer %i :" % self.id, exc_info=True)
            # logger.error("Sniffer %i : %s" % (self.id, e.strerror))
            print e
        finally:
            if capture:
                if db_on:
                    mydb.close()
                logger.info("Sniffer %i : Capture stopped..." % self.id)
                pkt_recv, pkt_drop, pkt_devdrop = p.stats()
                if pkt_recv > 0:
                    lost = pkt_drop / (pkt_recv * 1.0) * 100
                else:
                    lost = 0.0
                logger.info(
                    'Sniffer %i : %i packets received, %i packets dropped, %i packets dropped by interface - %d%%'
                    % (self.id, pkt_recv, pkt_drop, pkt_devdrop, lost))
Пример #25
0
    def decode_ip_packet(s):
        d={}
        d['version']=(ord(s[0]) & 0xf0) >> 4
        d['header_len']=ord(s[0]) & 0x0f
        d['tos']=ord(s[1])
        d['total_len']=socket.ntohs(struct.unpack('H',s[2:4])[0])
        d['id']=socket.ntohs(struct.unpack('H',s[4:6])[0])
        d['flags']=(ord(s[6]) & 0xe0) >> 5
        d['fragment_offset']=socket.ntohs(struct.unpack('H',s[6:8])[0] & 0x1f)
        d['ttl']=ord(s[8])
        d['protocol']=ord(s[9])
        d['checksum']=socket.ntohs(struct.unpack('H',s[10:12])[0])
        d['source_address']=pcap.ntoa(struct.unpack('i',s[12:16])[0])
        d['destination_address']=pcap.ntoa(struct.unpack('i',s[16:20])[0])
        if d['header_len']>5:
        d['options']=s[20:4*(d['header_len']-5)]
        else:
        d['options']=None
        d['data']=s[4*d['header_len']:]
        return d


        def dumphex(s):
            bytes = map(lambda x: '%.2x' % x, map(ord, s))
            for i in xrange(0,len(bytes)/16):
                print '    %s' % string.join(bytes[i*16:(i+1)*16],' ')
                print '    %s' % string.join(bytes[(i+1)*16:],' ')


                def print_packet(pktlen, data, timestamp):
                    if not data:
                    return

                    if data[12:14]=='\x08\x00':
decoded=decode_ip_packet(data[14:])
    print '\n%s.%f %s > %s' % (time.strftime('%H:%M',
                time.localtime(timestamp)),
            timestamp % 60,
            decoded['source_address'],
            decoded['destination_address'])
    for key in ['version', 'header_len', 'tos', 'total_len', 'id',
    'flags', 'fragment_offset', 'ttl']:
    print '  %s: %d' % (key, decoded[key])
    print '  protocol: %s' % protocols[decoded['protocol']]
    print '  header checksum: %d' % decoded['checksum']
    print '  data:'
    dumphex(decoded['data'])


    if __name__=='__main__':

    if len(sys.argv) < 3:
    print 'usage: sniff.py <interface> <expr>'
    sys.exit(0)
    p = pcap.pcapObject()
#dev = pcap.lookupdev()
    dev = sys.argv[1]
net, mask = pcap.lookupnet(dev)
# note:  to_ms does nothing on linux
p.open_live(dev, 1600, 0, 100)
#p.dump_open('dumpfile')
    p.setfilter(string.join(sys.argv[2:],' '), 0, 0)

# try-except block to catch keyboard interrupt.  Failure to shut
# down cleanly can result in the interface not being taken out of promisc.
# mode
#p.setnonblock(1)
    try:
    while 1:
p.dispatch(1, print_packet)

# specify 'None' to dump to dumpfile, assuming you have called
# the dump_open method
#  p.dispatch(0, None)

# the loop method is another way of doing things
#  p.loop(1, print_packet)

# as is the next() method
# p.next() returns a (pktlen, data, timestamp) tuple 
#  apply(print_packet,p.next())
    except KeyboardInterrupt:
    print '%s' % sys.exc_type
    print 'shutting down'
    print '%d packets received, %d packets dropped, %d packets dropped by interface' % p.stats()
Пример #26
0
    def run(self):
        """Sniffer main function"""
        # Get logger
        logger = logging.getLogger()
        logger.info("Sniffer %i : Capture started on %s" % (self.id, self.dev))

        # Init
        last_update_t = time()
        last_save_t = time()
        capture = False

        # Optimizations
        db_on = self.database["on"]
        lmod = self.lmod
        term = self.terminated
        pipe_send_fnt = self.pipe_sender.send

        lfnt_pkthandle = list()
        lfnt_trigger_update = list()
        lfnt_trigger_save = list()
        for mod in lmod:
            lfnt_pkthandle.append(mod.pkt_handler)
            lfnt_trigger_update.append(mod.trigger_data_update)
            lfnt_trigger_save.append(mod.trigger_db_save)



        # List loaded module
        for mod in self.lmod:
            logger.info("Sniffer %i : Load network module - websocket subprotocol " % (self.id) + mod.__str__())


        
        # Mysql database
        mydb = self.database["class"](
            host=self.database["conf"]["host"],
            user=self.database["conf"]["user"],
            passwd=self.database["conf"]["passwd"],
            database=self.database["conf"]["database"],
            port=self.database["conf"]["port"])

        if db_on:
            # connection to database
            mydb.connection()

            if mydb.is_connect():
                for mod in lmod:
                    mod.database_init(mydb)
                mydb.commit()

        # Get device informations if possible (IP address assigned)
        try:
            net, mask = pcap.lookupnet(self.dev)
        except:
            net, mask = "192.168.1.0", "255.255.255.0"

        # Create new pcap capture object
        p = pcap.pcapObject()

        try:
            # (Dev, buffer, promiscuous mode, timeout)
            p.open_live(self.dev, PCAP_PACKET_MAX_LEN, PCAP_PROMISCUOUS_MODE, PCAP_SNIFFER_TIMEOUT)
            # keep it in an available object
            GetSniffer().set_sniffer(p)
            capture = True

            # Handler loop
            # tt = (0, 0) 
            while not term.value:
                pkt = p.next()
                
                if pkt is not None:
                    
                    # Decode packet
                    pktdec = Packet(pkt[0], pkt[1], pkt[2])
                    # a = time()
                    # send pkt to modules
                    map(lambda x: x(pktdec), lfnt_pkthandle)

                    # res = time() - a
                    # a, b = tt
                    # tt = (a+res, b+1)
                    # if tt[1] > 100:
                    #     print "Time sniff :", tt[0]/tt[1], "Time Tot :", tt[0]
                    #     tt = (0,0)

                
                # Modules update call
                if time() - last_update_t > MIN_TIME_MOD_UPDATE:
                    last_update_t = time()
                    l_res = list()
                    for mod in lmod:
                        data = mod.trigger_data_update()
                        if data is not None:
                            l_res.append((mod.protocol, data))
                    
                    # Data to send with websocket
                    if len(l_res) > 0:
                        pipe_send_fnt(l_res)

                # Modules save call
                if db_on and mydb.connect is not None:
                    if time() - last_save_t > MIN_TIME_DB_UPDATE:
                        last_save_t = time()
                        map(lambda x: x(mydb), lfnt_trigger_save)
                        mydb.commit()
                

        except KeyboardInterrupt:
            logger.info("Sniffer %i : Interruption signal" % self.id)
        except Exception as e:
            logger.debug("Sniffer %i :" % self.id, exc_info=True)
            # logger.error("Sniffer %i : %s" % (self.id, e.strerror))
            print e
        finally:
            if capture:
                if db_on:
                    mydb.close()
                logger.info("Sniffer %i : Capture stopped..." % self.id)
                pkt_recv, pkt_drop, pkt_devdrop = p.stats()
                if pkt_recv > 0:
                    lost = pkt_drop / (pkt_recv * 1.0) * 100
                else:
                    lost = 0.0
                logger.info('Sniffer %i : %i packets received, %i packets dropped, %i packets dropped by interface - %d%%'
                            % (self.id, pkt_recv, pkt_drop, pkt_devdrop, lost))
Пример #27
0
    p = pcap.pcapObject()
    # dev = pcap.lookupdev()
    isLive = False
    targetFile = "igmp.pcap"
    targetDevice = "eth0"
    if len(sys.argv) >= 2:
        dev = sys.argv[1]
        if os.path.isfile(dev):
            isLive = False
            targetFile = dev
        else:
            isLive = True
            targetDevice = dev

    if isLive:
        net, mask = pcap.lookupnet(targetDevice)
        # note:  to_ms does nothing on linux
        isPromisc = 1
        p.open_live(dev, 1600000, isPromisc, 0)
        # p.dump_open('dumpfile')
        captureFilter = string.join(sys.argv[2:], ' ') if len(sys.argv) >= 3 else 'igmp'  # igmp
        p.setfilter(captureFilter, 0, 0)

        handler = IgmpHandler(p)
        handler.set_on_packet(on_packet)
        handler.set_src_filter(source_filter)

        balancer.run_consumer()
        handler.capture()
    elif os.path.isfile(targetFile):
        handler = IgmpHandler(p)
Пример #28
0
import pcap, time, sys

p = pcap.pcapObject()
net, mask = pcap.lookupnet("xl1")
p.open_live("xl1", 1600, 0, 100)
p.setfilter("tcp port 80 or port 8080 or port 3128" , 0, 0)

dupecache = {}

def print_deduped(data):
    if data not in dupecache:
        print data
        sys.stdout.flush()
    dupecache[data] = time.time()


def print_packet(pktlen, data, timestamp):
    if not data or pktlen > 1400:
        return
    # remove minimum IP / TCP header
    data = data[54:]
    pos = data.find("GET")
    if pos < 0:
        pos = data.find("HEAD")
    if pos < 0:
        return
    data = data[pos:]
    l = data.split("\n")
    reqstr = l[0]
    reqstr = reqstr[reqstr.find(" ")+1:reqstr.rfind(" ")]
    if reqstr[:1] != "/":
Пример #29
0
	    #print '  protocol: %s' % protocols[decoded['protocol']]
	    #print '  header checksum: %d' % decoded['checksum']
	    #print '  data:'

	    #data = str(dumphex(decoded['data']))
	    dumphex(decoded['data'])
	    #f.write(data)
if __name__=='__main__':

  if len(sys.argv) < 3:
    print 'usage: sniff.py <interface> <expr>'
    sys.exit(0)
  p = pcap.pcapObject()
  #dev = pcap.lookupdev()
  dev = sys.argv[1]
  net, mask = pcap.lookupnet(dev)
  # note:  to_ms does nothing on linux
  p.open_live(dev, 1600, 0, 100)
  p.dump_open('dumpfile')
  #p.setfilter(string.join(sys.argv[2:],' '), 0, 0)

  # try-except block to catch keyboard interrupt.  Failure to shut
  # down cleanly can result in the interface not being taken out of promisc.
  # mode
  #p.setnonblock(1)
  try:
    while 1:
      p.dispatch(1, print_packet)

    # specify 'None' to dump to dumpfile, assuming you have called
    # the dump_open method
Пример #30
0
        hv = hex(ord(ch)).replace('0x', '')
        if len(hv) == 1:
            hv = '0' + hv
        lst.append(hv)

    return reduce(lambda x, y: x + y, lst)


def analyze(id, data, timestamp):
    strdata = toHex(data)
    for mac, vm in vm_macs.iteritems():
        # Skip nytrio vm
        if vm == 'NDEMO_NYTRIO':
            continue
        if mac.replace(':', '') in strdata:
            commands.getoutput('virsh start %s' % vm)


if __name__ == '__main__':
    interface = 'virbr1'
    p = pcap.pcapObject()
    net, mask = pcap.lookupnet(interface)
    p.open_live(interface, 1600, 0, 100)
    p.setfilter('udp and port 7 or port 9', 0, 0)

    try:
        while 1:
            p.dispatch(1, analyze)
    except KeyboardInterrupt:
        pass
Пример #31
0
 def __init__(self,interface):
   threading.Thread.__init__(self)
   print "initializing.."
   self.p = pcap.pcapObject() 
   net, mask = pcap.lookupnet(interface)
   self.interface=interface
Пример #32
0
        decoded = decode_ip_packet(data[14:])
        print('\n%s.%f %s > %s' %
              (time.strftime('%H:%M', time.localtime(timestamp)), timestamp %
               60, decoded['source_address'], decoded['destination_address']))
        for key in [
                'version', 'header_len', 'tos', 'total_len', 'id', 'flags',
                'fragment_offset', 'ttl'
        ]:
            print('  %s: %d' % (key, decoded[key]))
        print('  protocol: %s' % protocols[decoded['protocol']])
        print('  header checksum: %d' % decoded['checksum'])
        #print '  data:'
        #dumphex(decoded['data'])


if __name__ == '__main__':
    print(pcap.findalldevs())
    for dev in pcap.findalldevs():
        print(dev)
        net, mask = pcap.lookupnet(dev.encode())
        print(net.__repr__(), mask.__repr__())
    p = pcap.pcap('本地网络')
    net, mask = pcap.lookupnet(dev.encode())
    try:
        for timestamp, data in p:
            print_packet(data, timestamp)
            #print timestamp, len(data)
    except KeyboardInterrupt:
        print('%s' % sys.exc_type)
        print('shutting down')
Пример #33
0
    global p
    print 'Listening...'
    p.setnonblock(1)
    while 1:
        p.dispatch(1, read_packet)
        time.sleep(0.00001)

        

net_if = 'eth0'

s = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)
s.bind((net_if, 0))

p = pcap.pcapObject()
net, mask = pcap.lookupnet(net_if)
# args are:
# net interface name
# Buffer size to allocate
# Promisc mode on/off
# time to accumulate packets before making higher level call
p.open_live(net_if, 65535, 1, 10)
time.sleep(0.01)

# We're putting together an ethernet frame here, 
# but you could have anything you want instead
# Have a look at the 'struct' module for more 
# flexible packing/unpacking of binary data
# and 'binascii' for 32 bit CRC

# 1 magic word (0x69)
Пример #34
0
def listener():
    global p
    print 'Listening...'
    p.setnonblock(1)
    while 1:
        p.dispatch(1, read_packet)
        time.sleep(0.00001)


net_if = 'eth0'

s = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)
s.bind((net_if, 0))

p = pcap.pcapObject()
net, mask = pcap.lookupnet(net_if)
# args are:
# net interface name
# Buffer size to allocate
# Promisc mode on/off
# time to accumulate packets before making higher level call
p.open_live(net_if, 65535, 1, 10)
time.sleep(0.01)

# We're putting together an ethernet frame here,
# but you could have anything you want instead
# Have a look at the 'struct' module for more
# flexible packing/unpacking of binary data
# and 'binascii' for 32 bit CRC

# 1 magic word (0x69)