Esempio n. 1
0
    def __init__(self, argv):
        app = QGuiApplication(argv)
        engine = QQmlApplicationEngine()
        context = engine.rootContext()
        context.setContextProperty('mainWindow',
                                   engine)  # the string can be anything

        engine.load('/Users/hebingchang/QtCreator/sniffer/sniffer.qml')
        self.root = engine.rootObjects()[0]
        self.root.setDevModel(pcap.findalldevs())
        self.dev = pcap.findalldevs()[0]
        self.sniffer_status = False

        # self.root.appendPacketModel({'source': '10.162.31.142', 'destination': '151.101.74.49', 'length': 52, 'id': 1})

        self.packetModel = self.root.findChild(QObject, "packetModel")

        btnStart = self.root.findChild(QObject, "btnStart")
        btnStart.clicked.connect(self.myFunction)  # works too

        self.comboDev = self.root.findChild(QObject, "comboDevice")
        self.comboDev.activated.connect(self.getDev)

        engine.quit.connect(app.quit)
        sys.exit(app.exec_())
Esempio n. 2
0
    def getAllDev(self):
        self.devlist = [] #用于显示
        self.devnamelist = [] #由于网卡数据

        maxlength = 0;
        for dev in pcap.findalldevs():
            length = len(dev.description)
            maxlength = maxlength if maxlength > length else length
        for dev in pcap.findalldevs():
            devname = dev.description
            self.devnamelist.append(dev.name)
            devname += ' '*(maxlength - len(devname))
            devname += dev.name
            self.devlist.append(devname)
Esempio n. 3
0
    def _validate_device(self, device_name):
        """Validate the given device name as being available to the application.
        While this is more hoops than just pcap.lookupdev, we can get a full
        list of ip addresses we're listening for from this method.

        :param str device_name: The device name to validate
        :returns: Bool

        """
        # Get all the devices available
        devices = pcap.findalldevs()

        # Iterate through the devices looking for the one we care about
        for device in devices:

            # Is this the droid, err device we are looking for?
            if device[0] == device_name:
                self._logger.debug('Validated device %s', device_name)

                # Output ip addresses if there are any
                if device[2]:
                    ip_addresses = list()
                    for address_info in device[2]:
                        ip_addresses.append(address_info[0])
                    self._logger.info('IP addresses to listen on: %r',
                                      ip_addresses)

                # Device validates
                return True

        # It was not found
        return False
Esempio n. 4
0
    def install(self):
        '''Main install module. Fetches information from user and setup
        relavant files'''
        import pcap
        if self.get_installation_status():
            print('ARP spoof detector is already installed.')
            return False

        # Register User
        userData = self.get_user_details()
        responseText,responseStatus = self.send_to_server(userData,self.configArray['serverSignUpEndPoint'])
        if responseStatus != 200:
            print('User with same information exists.\nContact your admin for resolution.')
            exit(1)
        else:
            print('\nRegister successfull\n')

        #Get an interface from user
        networkInterface = pcap.findalldevs()
        print('\nChoose an interface to work on:')
        print("%s%s:%s"%('Interface',' '*(10-len('Interface')),'Choice'))

        for x in range(0,len(networkInterface)):
            print("%s%s:%d"%(networkInterface[x][0],' '*(10-len(networkInterface[x][0])),x+1))

        #Validate choice
        choice = int(raw_input('Enter choice:')) -1
        while choice<0 and choice >= len(networkInterface):
            print('Incorrect choice. Try again')
            choice = int(raw_input('Enter choice:')) -1

        userData['interfaceName'] = networkInterface[choice][0]

        #Save user choice
        self.setup_file(userData)
Esempio n. 5
0
def test_findalldevs():
    print(pcap.findalldevs())
    for name, descr, addrs, flags in pcap.findalldevs():
        print('Interface name: %s' % name)
        print('   Description: %s ' % descr)
        if addrs:
            i = 1
            for (addr, netmask, broadaddr, dstaddr) in addrs:
                print('    Address %d: %s ' % (i, addr))
                print('       Netmask: %s' % netmask)
                print('     Broadcast: %s' % broadaddr)
                print('Peer dest addr: %s' % dstaddr)
                i = i + 1
        else:
            print(' No addresses')
        print(' flags: %s ' % flags)
Esempio n. 6
0
    def test_lookupdev_findall(self):
        # current pypcap shows diffent names for findalldevs() and lookupdev()
        # under windows, so skip it
        if sys.platform.find('win') != -1:
            py.test.skip("not supported by windows")

        assert pcap.lookupdev() in pcap.findalldevs()
Esempio n. 7
0
def test_findalldevs():
    print pcap.findalldevs()
    for name, descr, addrs, flags in pcap.findalldevs():
        print 'Interface name: %s' % name
        print '   Description: %s ' % descr
        if addrs:
            i = 1
            for (addr, netmask, broadaddr, dstaddr) in addrs:
                print '    Address %d: %s ' % (i, addr)
                print '       Netmask: %s' % netmask
                print '     Broadcast: %s' % broadaddr
                print 'Peer dest addr: %s' % dstaddr
                i = i + 1
        else:
            print ' No addresses'
        print ' flags: %s ' % flags
Esempio n. 8
0
def test_findalldevs():
    print(pcap.findalldevs())
    for name, descr, addrs, flags in pcap.findalldevs():
        print("Interface name: %s" % name)
        print("   Description: %s " % descr)
        if addrs:
            i = 1
            for (addr, netmask, broadaddr, dstaddr) in addrs:
                print("    Address %d: %s " % (i, addr))
                print("       Netmask: %s" % netmask)
                print("     Broadcast: %s" % broadaddr)
                print("Peer dest addr: %s" % dstaddr)
                i = i + 1
        else:
            print(" No addresses")
        print(" flags: %s " % flags)
Esempio n. 9
0
	def refresh(self,a):
		if a==1:
			self.clear()
			#get the information of all devices
    			for name,descr, addrs, flags  in pcap.findalldevs():
        			self.addItem(name)
			pcap.close()
Esempio n. 10
0
    def _validate_device(self, device_name):
        """Validate the given device name as being available to the application.
        While this is more hoops than just pcap.lookupdev, we can get a full
        list of ip addresses we're listening for from this method.

        :param str device_name: The device name to validate
        :returns: Bool

        """
        # Get all the devices available
        devices = pcap.findalldevs()

        # Iterate through the devices looking for the one we care about
        for device in devices:

            # Is this the droid, err device we are looking for?
            if device[0] == device_name:
                self._logger.debug('Validated device %s', device_name)

                # Output ip addresses if there are any
                if device[2]:
                    ip_addresses = list()
                    for address_info in device[2]:
                        ip_addresses.append(address_info[0])
                    self._logger.info('IP addresses to listen on: %r',
                                      ip_addresses)

                # Device validates
                return True

        # It was not found
        return False
Esempio n. 11
0
def get_udp_from_dev(network='10.168.103.0', port='14550'):
    devs = pcap.findalldevs()
    pc = None
    for dev in devs:
        try:
            t = inet_to_str(pcap.lookupnet(bytearray(dev, 'utf-8'))[0])
        except Exception as e:
            print(e)
        if t == network:
            pc = pcap.pcap(dev)
    if not pc:
        return False

    pc.setfilter('udp')  #设置监听过滤器,这里指定port 'udp port 54915'
    for ts, buf in pc:
        eth = dpkt.ethernet.Ethernet(buf)
        if not isinstance(eth.data, dpkt.ip.IP):
            print('Non IP Packet type not supported %s\n' %
                  eth.data.__class__.__name__)
            continue
        ip = eth.data
        if isinstance(ip.data, dpkt.udp.UDP):
            udp = ip.data
            print('[+] Src:', udp.sport, ' --> Dst:', udp.dport)

        do_not_fragment = bool(ip.off & dpkt.ip.IP_DF)
        more_fragments = bool(ip.off & dpkt.ip.IP_MF)
        fragment_offset = ip.off & dpkt.ip.IP_OFFMASK
        print('Timestamp: ', str(datetime.datetime.utcfromtimestamp(ts)))
        print('Ethernet Frame: ', mac_addr(eth.src), mac_addr(eth.dst),
              eth.type)
        print ('IP: %s -> %s   (len=%d ttl=%d DF=%d MF=%d offset=%d)' % \
(inet_to_str(ip.src),inet_to_str(ip.dst), ip.len, ip.ttl, do_not_fragment, more_fragments,fragment_offset))
Esempio n. 12
0
def test_findalldevs():
    print pcap.findalldevs()
    for name, descr, addrs, flags in pcap.findalldevs():
        print 'Interface name: %s' % name
        print '   Description: %s ' % descr
        if addrs:
            i=1
            for ( addr, netmask, broadaddr, dstaddr) in addrs:
                print '    Address %d: %s ' % (i, addr)
                print '       Netmask: %s' % netmask
                print '     Broadcast: %s' % broadaddr
                print 'Peer dest addr: %s' % dstaddr
                i=i+1
        else:
            print ' No addresses'
        print ' flags: %s ' % flags
Esempio n. 13
0
File: zhua.py Progetto: yshdxm/note
 def __init__(self):
     print('[+] 网卡列表')
     self.network=pcap.findalldevs()
     print('='*30)
     for ifaces in self.network:
         print(ifaces)
     print('=' * 30)
     self.qqnumbers=[]
Esempio n. 14
0
def main():
    arg_parser = argparse.ArgumentParser(description="ifstat - network interface statistics utility")
    arg_parser.add_argument(dest='device', help='The device name to get stats for')
    arg_parser.add_argument('--interval', '-i', dest='interval', default=1.0, type=float, help='Interval to gather and display stats')

    args = arg_parser.parse_args()

    if args.device not in pcap.findalldevs():
        sys.stderr.write('Error: No such device %s \n' % (args.device, ))
        return

    collector = getstats.StatCollector(args.device)
    collector.start()
    raw_stats = collector.get_stats()
    stat_processor = StatProcessor(raw_stats)

    locale.setlocale(locale.LC_ALL, '')
    window = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.curs_set(0)
    window.keypad(1)
    # XXX: halfdelay is in tenths of seconds
    curses.halfdelay(int(args.interval * 10))
    colors = _init_colors()
    last_time = time.time()
    sessions_pad = SessionsPad(colors=colors)
    device_pad = DevicePad(args.device, args.interval, colors=colors, ylocation=sessions_pad.get_y_size())
    current_stats = {"device": {}, "sessions": []}
    try:
        running = True
        while running:
            # XXX: Get & process new stats only when the intervals have passed
            current_time = time.time()
            if current_time - last_time >= args.interval:
                raw_stats = collector.get_stats()
                current_stats = stat_processor.process_new_stats(raw_stats, args.interval)
                last_time = current_time

                maxy, maxx = window.getmaxyx()
                sessions_pad.display(maxy, maxx, current_stats["sessions"])
                device_pad.display(maxy, maxx, current_stats["device"])

            key = window.getch()

            if key != -1:
                sessions_pad.key(key)
                device_pad.key(key)
            if key == ord('q'):
                collector.stop()
                running = False

    finally:
        curses.nocbreak()
        curses.echo()
        curses.endwin()
    def all_netdevs(self):
        """
        list all available network devices

        need to be root or have special authorisation
        """
        l = list()
        for d in findalldevs():
            l.append(d[0])
        return l
Esempio n. 16
0
def main(argv):
    print(pcap.findalldevs())
    read_interface = create_reading_interface()

    #while True:
    for index in range(0, 10):
        #print(read_interface.stats(), read_interface.readpkts())
        #print(read_interface.readpkts())
        for timestamp, read_data in read_interface.readpkts():
            print(timestamp, read_data)
    def all_netdevs(self):
        """
        list all available network devices

        need to be root or have special authorisation
        """
        l = list()
        for d in findalldevs():
            l.append(d[0])
        return l
def main(argv):
    print(pcap.findalldevs())
    read_interface = create_reading_interface()

    #while True:
    for index in range(0, 10):
        #print(read_interface.stats(), read_interface.readpkts())
        #print(read_interface.readpkts())
        for timestamp, read_data in read_interface.readpkts():
            print(timestamp, read_data)
Esempio n. 19
0
def usage():
    sys.stderr.write('Usage: %s [-i device] [-l] [pattern]' % sys.argv[0])
    sys.stderr.write("""
Options:

\t-i device - Use the specific device.
\t-l - Use pcap.loop() method.

Available devices:""")
    sys.stderr.write('\t' + '\n\t'.join(pcap.findalldevs()))
    sys.exit(1)
Esempio n. 20
0
def listdevs():
    #通过pcap查找所有可用的网卡接口
    devs = pcap.findalldevs()
    if (args.list != False):
        print("list the devices:")
        if (len(devs) == 0):
            print("no device is avaliable")
        else:
            for dev in devs:
                print(dev)
    return devs
Esempio n. 21
0
def get_udp_from_network(filename='192.168.1.0',
                         ip_list=['192.168.1.4'],
                         port=14550):
    devs = pcap.findalldevs()
    pc = None
    for dev in devs:
        try:
            t = inet_to_str(pcap.lookupnet(bytearray(dev, 'utf-8'))[0])
        except Exception as e:
            print(e)
            continue
        if t == filename:
            pc = pcap.pcap(dev)
    if not pc:
        return False

    pc.setfilter('ip host %s and udp port %d' % (ip_list[0], port))
    # print('ip host %s and udp port %d' % (ip_list[0], port))

    for ts, buf in pc:
        # print(buf)

        eth = dpkt.ethernet.Ethernet(buf)

        if not isinstance(eth.data, dpkt.ip.IP):
            continue

        ip = eth.data
        src = socket.inet_ntoa(ip.src)
        dst = socket.inet_ntoa(ip.dst)

        if not (src in ip_list or dst in ip_list):
            print('not %s' % ip_list[0])
            print(src, dst)
            continue

        if not isinstance(ip.data, dpkt.udp.UDP):
            print('Non UDP Packet type not supported %s\n' %
                  ip.data.__class__.__name__)
            continue

        udp = ip.data
        sport = udp.sport
        dport = udp.dport

        if not (sport == port or dport == port):
            print('not %d' % port)
            print(sport, dport)
            continue

        # print(udp.data)
        src_addr = (src, sport)
        yield (udp.data, src_addr)
Esempio n. 22
0
def get_interface(e):
    """gets an interface by something"""
    faces = pcap.findalldevs()

    cryztal = [get_interface_by_idx, get_interface_by_name, get_interface_by_address]

    for meth in cryztal:
        try:
            return meth(e, faces)
        except:
            pass

    return None
Esempio n. 23
0
 def __init__(self,title):
     wx.Frame.__init__(self,None,title=title,size = (600,700))
     boxSizer = wx.BoxSizer(wx.VERTICAL)
     filterSizer = wx.BoxSizer(wx.HORIZONTAL)
     
     self.panel = wx.Panel(self)
     
     # boxSizer.Add(self.panel,1,wx.EXPAND|wx.ALL) #wx.ALL 周围的距离,EXPAND扩充到全部
     device = pcap.findalldevs()
     if not device:
         device = ['网卡初始化有问题!']
     ethtext = wx.StaticText(self.panel,-1,"请选择网卡")
     self.ethlist = wx.Choice(self.panel,-1,choices=device,size=(350,20))
     
     filterText = wx.StaticText(self.panel,-1,'请书写过滤规则')
     hosttext = wx.StaticText(self.panel,-1,'host')
     self.hostctrl = wx.TextCtrl(self.panel,-1,size=(150,20))
     uritext = wx.StaticText(self.panel,-1,'uri')
     self.urictrl = wx.TextCtrl(self.panel,-1,size=(100,20))
     self.startButton = wx.Button(self.panel,-1,'开始')        
     self.stopButton = wx.Button(self.panel,-1,'停止')
     self.stopButton.Disable() #将停止按钮设置为disable
     self.Bind(wx.EVT_BUTTON,self.start,self.startButton)
     self.Bind(wx.EVT_BUTTON,self.stop,self.stopButton)
     #书写过滤规则的sizer
     filterSizer.Add(hosttext,0,wx.LEFT|wx.TOP,border=10)
     filterSizer.Add(self.hostctrl,0,wx.LEFT|wx.TOP,border=10)
     filterSizer.Add(uritext,0,wx.LEFT|wx.TOP,border=10)
     filterSizer.Add(self.urictrl,0,wx.LEFT|wx.TOP,border=10)
     filterSizer.Add(self.startButton,0,wx.LEFT|wx.TOP,border=10)
     filterSizer.Add(self.stopButton,0,wx.LEFT|wx.TOP,border=10)
     
     #显示抓到的包
     self.sniffer = wx.ListCtrl(self.panel,0,size=(550,450),style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES)
     self.sniffer.InsertColumn(0,'id',format=wx.LIST_FORMAT_LEFT, width=50)
     self.sniffer.InsertColumn(1,'host',format=wx.LIST_FORMAT_LEFT, width=150)
     self.sniffer.InsertColumn(2,'uri',format=wx.LIST_FORMAT_LEFT, width=150)
     
     self.exit = wx.Button(self.panel,-1,'退出')
     self.Bind(wx.EVT_BUTTON,self.exitpro,self.exit)
     
     
     boxSizer.Add(ethtext,0,wx.EXPAND|wx.LEFT|wx.TOP,border=10)
     boxSizer.Add(self.ethlist,0,wx.LEFT|wx.TOP,border=10)
     boxSizer.Add(filterText,0,wx.LEFT|wx.TOP,border=10)
     boxSizer.Add(filterSizer,0,wx.LEFT|wx.TOP,border=10)
     boxSizer.Add((-1,20))
     boxSizer.Add(self.sniffer,0,wx.LEFT|wx.TOP,border=10)
     boxSizer.Add(self.exit,0,flag=wx.ALIGN_CENTER|wx.TOP,border=10)
     
     self.panel.SetSizer(boxSizer)
Esempio n. 24
0
    def __init__(self, ifacename, modules):
	self.mod_dir = 'modules'
	self.modules = list()
	self.interface = None
	# Get interface to use
	for iface in pcap.findalldevs():
	    if ifacename == iface[0]:
		self.interface = iface
		break
	if not self.interface:
	    out.error("Can't find %s interface. Priveleges ?" % ifacename)
	    self.stop()
	# Load modules
	self.loadModules(modules)
Esempio n. 25
0
def main():

	devs = pcap.findalldevs()
	print "please chose which interface to listen:"
	for index,dev in enumerate(devs):
		print str(index)+":"+dev
	i = raw_input()
	dev = devs[int(i)]
	pc = pcap.pcap(dev)
	print "listening on %s"%pc.name

	# th = threading.Thread(target=calc_speed)
	# th.start()
	pc.loop(-1,pcap_handler)
Esempio n. 26
0
 def __init__(self, input_device, snaplen=2000, filter_rules=None):
     # check if the devname is an interface or not.
     if input_device in pcap.findalldevs():
         self._pc = pcap.pcap(input_device, snaplen, immediate=True)
     else:
         self._pc = pcap.pcap(input_device, timeout_ms=0)
     # set filter.
     self._pc.setfilter(filter_rules)
     dprint("dloff:", self._pc.dloff)
     dprint("fd:", self._pc.fd)
     dprint("filter:", self._pc.filter)
     dprint("name:", self._pc.name)
     dprint("snaplen:", self._pc.snaplen)
     dprint("nb_blk:", self._pc.getnonblock())
Esempio n. 27
0
    def wait_for_interface(self):
        '''Waits till the required network interface is ready for use'''
        print('Waiting for interface: %s'%(self.interface))
        import time
        isNetworkUp = False

        while not isNetworkUp:
            for x in pcap.findalldevs(): #Fetch list of all network interface
                if x[0] == self.interface and x[3] == pcap.DLT_IEEE802: #pcap.DLT_IEEE802=6
                    isNetworkUp = True
            time.sleep(3)

        print('Interface %s is ready for capturing'%(self.interface))
        return True
Esempio n. 28
0
def search_if_by_ip(ip_str):
    search_addr = ip4_str_to_num(ip_str)

    for dev in pcap.findalldevs():
        name, _, addresses, _ = dev

        for (addr, netmask, _, _) in addresses:
            if re.match("[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+", addr):
                addr_num = ip4_str_to_num(addr)
                netmask_num = ip4_str_to_num(netmask)
                if (addr_num & netmask_num) == (search_addr & netmask_num):
                    return name

    return None
Esempio n. 29
0
def search_if_by_ip(ip_str):
	search_addr = ip4_str_to_num(ip_str)

	for dev in pcap.findalldevs():
		name, _, addresses, _ = dev

		for (addr, netmask, _, _) in addresses:
			if re.match("[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+", addr):
				addr_num = ip4_str_to_num(addr)
				netmask_num = ip4_str_to_num(netmask)
				if (addr_num & netmask_num) == (search_addr & netmask_num):
					return name

	return None
Esempio n. 30
0
def test_unicode():
    path = relative_file('test.pcap')
    p = pcap.pcap(path)
    assert isinstance(p.name, str)

    f = 'icmp[icmptype] != icmp-echo'
    p.setfilter(f)
    assert isinstance(p.filter, str)

    devs = pcap.findalldevs()
    for name in devs:
        assert isinstance(name, str)
    try:
        isinstance(pcap.lookupdev(), str)
    except OSError:
        # skip if no devices are detected
        pass
Esempio n. 31
0
def list_interfaces():
    """
    Prints out all available interfaces with IP adresses, when possible.
    """
    i = 0
    for name in pcap.findalldevs():
        prettydevicename = ''
        queryname = name
        if name.startswith(r'\Device\NPF_'):
            queryname = name[12:]
        if name.endswith('}'):
            prettydevicename = 'eth{0} '.format(i)
            i += 1
        try:
            import netifaces
            print('{1}{0} {2}'.format(name, prettydevicename,
                                      netifaces.ifaddresses(queryname)
                                      [netifaces.AF_INET][0]['addr']))
        except ImportError:
            print('{0}{1}'.format(prettydevicename, name))
Esempio n. 32
0
def list_interfaces():
    """
    Prints out all available interfaces with IP adresses, when possible.
    """
    i = 0
    for name in pcap.findalldevs():
        prettydevicename = ''
        queryname = name
        if name.startswith(r'\Device\NPF_'):
            queryname = name[12:]
        if name.endswith('}'):
            prettydevicename = 'eth{0} '.format(i)
            i += 1
        try:
            import netifaces
            print('{1}{0} {2}'.format(
                name, prettydevicename,
                netifaces.ifaddresses(queryname)[netifaces.AF_INET][0]
                ['addr']))
        except ImportError:
            print('{0}{1}'.format(prettydevicename, name))
Esempio n. 33
0
    def load(self):
        engine = QQmlApplicationEngine()
        context = engine.rootContext()
        context.setContextProperty('mainWindow',
                                   engine)  # the string can be anything
        engine.load('./qt-gui/sniffer.qml')

        parse = parseController()
        context.setContextProperty('parse', parse)

        if os.name == 'nt':
            self.devs_name = list(psutil.net_if_addrs().keys())
            self.devs = [
                '\\\\Device\\\\NPF_' + x for x in netifaces.interfaces()
            ]
        else:
            self.devs_name = self.devs = pcap.findalldevs()

        self.root = engine.rootObjects()[0]
        self.root.setDevModel(self.devs_name)
        self.dev = self.devs[0]
        self.sniffer_status = False

        self.packetModel = self.root.findChild(QObject, "packetModel")

        self.sniffer_thread = SnifferThread()  # This is the thread object
        # Connect the signal from the thread to the finished method
        self.sniffer_thread.signal.connect(self.addItem)

        self.btnStart = self.root.findChild(QObject, "rowLayout1").findChild(
            QObject, "btnStart")
        self.btnStart.clicked.connect(self.toggleSniffer)

        self.comboDev = self.root.findChild(QObject, "comboDevice")
        self.comboDev.activated.connect(self.getDev)

        engine.quit.connect(self.app.quit)

        return self.app.exec_()
Esempio n. 34
0
def getInterface():

    ifs = pcap.findalldevs()

    # No interfaces available, abort.
    if len(ifs) == 0:
        print "You don't have enough permissions to open any interface on this system."
        sys.exit(1)

    # Only one interface available, use it.
    elif len(ifs) == 1:
        print "Only one interface present, defaulting to it."
        return ifs[0]

    # have to update
    # Ask the user to choose an interface from the list.
    count = 0
    for iface in ifs:
        print '%i - %s' % (count, iface)
        count += 1
    idx = int(raw_input('Please select an interface: '))
    return ifs[idx]
Esempio n. 35
0
def manageThreads(options, procs, ifaces):
    for iface in set(pcap.findalldevs() + ifaces):
        # ignore vm interfaces
        if iface[:2].lower() == 'vm': continue
        try:
            ip = get_ip(iface)
            # ignore loopback
            if ip[:3] == '127': continue
        # interface doesn't have ip
        except:
            for p in procs[1:]:
                # terminate thread if iface without ip is being watched
                if iface == p.sl.iface:
                    print iface, 'ip address lost'
                    p.terminate()
                    procs.remove(p)
                    ifaces.remove(iface)
        else:
            # check if interface is being watched by process
            for p in procs[1:]:
                if iface == p.sl.iface:
                    # check if interface ip has changed
                    if ip != p.ip:
                        # terminate thread listening on interface
                        p.terminate()
                        procs.remove(p)
                        print iface, 'ip address changed.'
                    else:
                        break
            else:
                # create scan object and give to process to run
                sl = ScanLogger(options.verbose, options.logfile,
                                options.whois, iface)
                p = Proc(sl, ip)
                procs.append(p)
                p.start()
                # add to interfaces being watched
                ifaces.append(iface)
                print iface + ': ' + ip
Esempio n. 36
0
    def capture(self):
        try:

            devs = pcap.findalldevs()
            dev_name = self.network_device_name
            find_flag = False
            for each_dev in devs:
                if each_dev == str(dev_name):
                    find_flag = True
                    break
            if not find_flag:
                return "[Error] There is no such network device"

            pc = pcap.pcap(dev_name, promisc=True, immediate=True, timeout_ms=40)

            for ptime, pdata in pc:
                network_data = {}
                network_data['packet_time'] = ptime
                network_data['raw_data'] = pdata
                """put packet to queue"""
                self.lpu.put(network_data)
        except Exception as e:
            print("Occur error " + str(e))
Esempio n. 37
0
def main_dev():
    devs = pcap.findalldevs()
    pc = pcap.pcap(devs[3])
    pc.setfilter('udp port 54915')  #设置监听过滤器,这里指定ip
    for ts, buf in pc:
        eth = dpkt.ethernet.Ethernet(buf)
        if not isinstance(eth.data, dpkt.ip.IP):
            print('Non IP Packet type not supported %s\n' %
                  eth.data.__class__.__name__)
            continue
        ip = eth.data
        if isinstance(ip.data, dpkt.udp.UDP):
            udp = ip.data
            print('[+] Src:', udp.sport, ' --> Dst:', udp.dport)

        do_not_fragment = bool(ip.off & dpkt.ip.IP_DF)
        more_fragments = bool(ip.off & dpkt.ip.IP_MF)
        fragment_offset = ip.off & dpkt.ip.IP_OFFMASK
        print('Timestamp: ', str(datetime.datetime.utcfromtimestamp(ts)))
        print('Ethernet Frame: ', mac_addr(eth.src), mac_addr(eth.dst),
              eth.type)
        print ('IP: %s -> %s   (len=%d ttl=%d DF=%d MF=%d offset=%d)' % \
(inet_to_str(ip.src),inet_to_str(ip.dst), ip.len, ip.ttl, do_not_fragment, more_fragments,fragment_offset))
Esempio n. 38
0
def manageThreads(options, procs, ifaces):
    for iface in set(pcap.findalldevs() + ifaces):
        # ignore vm interfaces
        if iface[:2].lower() == 'vm': continue
        try:
            ip = get_ip(iface)
            # ignore loopback
            if ip[:3] == '127': continue
        # interface doesn't have ip
        except:
            for p in procs[1:]:
                # terminate thread if iface without ip is being watched
                if iface == p.sl.iface:
                    print iface, 'ip address lost'
                    p.terminate()
                    procs.remove(p)
                    ifaces.remove(iface)
        else:
            # check if interface is being watched by process
            for p in procs[1:]:
                if iface == p.sl.iface:
                    # check if interface ip has changed
                    if ip != p.ip:
                        # terminate thread listening on interface
                        p.terminate() 
                        procs.remove(p)                      
                        print iface, 'ip address changed.'                 
                    else: break
            else:
                # create scan object and give to process to run
                sl = ScanLogger(options.verbose, options.logfile, options.whois, iface)
                p = Proc(sl, ip)
                procs.append(p)
                p.start()
                # add to interfaces being watched
                ifaces.append(iface)
                print iface + ': ' + ip
Esempio n. 39
0
def findalldevs():
    return pcap.findalldevs()
Esempio n. 40
0
def main():

    configure_logger(log)

    log.info('This is RIfSniff Collector v%s' % VERSION)

    parser = argparse.ArgumentParser(description='RIfSniff Packet Collector',
        epilog='Try using it with `sudo` if --list shows no available interfaces')

    parser.add_argument('--version', action='version', version='%(prog)s 0.1')
    parser.add_argument('-l', '--list', action='store_true',
                        help='List local interfaces available for packet capture')
    parser.add_argument('-c', '--list-compact', action='store_true',
                        help='List interface names only, no description')
    parser.add_argument('-a', '--address', type=str, default='0.0.0.0',
                        help='Address for inbound connection (default: 0.0.0.0)')
    parser.add_argument('-p', '--port', type=int, default=6384,
                        help='Port for inbound connection (default: 6384)')

    args = parser.parse_args()

    signal.signal(signal.SIGINT, sighandler)

    if args.list_compact or args.list:
        try:
            devs = pcap.findalldevs()

            if not devs:
                log.warn('No device available for capture')
                log.warn('Try running the program with higher permissions (e.g.: sudo)')
            elif args.list_compact:
                log.info('Listing names of devices available for capture')
                utils.print_device_list(devs)
            else:
                log.info('Listing devices available for capture')
                for dev in devs:
                    utils.print_device_description(dev)
        finally:
            log.info('Exiting...')
            sys.exit(0)

    server_addr = (args.address, args.port)

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(server_addr)
    server_socket.listen(10)

    try:
        while True:
            log.info('server socket listening on <%s:%d>' % server_addr)
            client, address = server_socket.accept()

            pipe_r, pipe_w = multiprocessing.Pipe(duplex=False)

            #proc = multiprocessing.Process(target=serve_client, args=(pipe_r,))
            proc = RemoteInterfaceSniffer(pipe_r)
            PROCLIST.append(proc)
            proc.start()

            client_handle = reduce_handle(client.fileno())
            pipe_w.send(client_handle)
    finally:
        logging.shutdown()

    sys.exit(0)
Esempio n. 41
0
 def get_if_list():
     # remove 'any' interface
     return map(lambda x:x[0],filter(lambda x:x[1] is None,pcap.findalldevs()))
Esempio n. 42
0
 def test_findalldevs(self):
     try:
         assert pypcap.findalldevs() == pcap.findalldevs()
     except UMPASniffingException:
         py.test.skip("no suitable devices for sniffing found. "
                     "propably not sufficent priviliges.")
Esempio n. 43
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()
Esempio n. 44
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)
    #tmp
  #  ip_mac_dic={}
  #  threads=[]
  #  threads.append(learn_ip_mac())
  #  threads.append(print_ip_mac())
  #  for t in threads:
  #      t.start()
  #  for t in threads:
  #      t.join()  
  #  
    dev=[]
    addrlist=pcap.findalldevs()
    for i in addrlist:
        print i[0]
        dev.append(i[0])
    for i in dev:
        print i
       
    #p = pcap.pcapObject()


  


# vim:set ts=4 sw=4 et:
Esempio n. 45
0
import sys
import signal

import dpkt
import pcap

print "All available interfaces:"
for interface in pcap.findalldevs():
    print " *  %s" % interface

if len(sys.argv) < 2:
    interface = "lo0"
else:
    interface = sys.argv[1]

print "Capturing memcached incoming packets"
print "Interface: %s" % interface

sniffer = pcap.pcap(name=interface, timeout_ms=500)
sniffer.setfilter('tcp dst port 11211 and (tcp[tcpflags] & tcp-push != 0)')

for capture in sniffer:
    if capture is None:
        continue

    ts, pkt = capture
    print "{ts:.6f}".format(ts=ts)
    loopback = dpkt.loopback.Loopback(pkt)
    ip = loopback.data
    tcp = ip.data
    content = tcp.data
Esempio n. 46
0
    default=False,
    help="disable prp, and only capture headers, not the full frame")
parser.add_option(
    '-a',
    '--node-forget-time',
    type="float",
    metavar='SECONDS',
    default=30.0,
    help=
    "idle time after which we forget all previos sequence numbers; 0.0=never")

options, args = parser.parse_args()

if options.interfaces:
    print 'Interfaces available for capturing:'
    for x in pcap.findalldevs():
        print x[0], ':', x[1:]
    sys.exit(0)

if len(args) != 1:
    parser.print_help()
    sys.exit(1)

ignore_macs = []
if options.ignore:
    ignore_macs = options.ignore.split(',')

devnull = open(os.devnull, "w")
error = sys.stderr
info = sys.stdout  # general info
info_pp = sys.stdout  # info per packet
Esempio n. 47
0
 def getDev(self, index):
     self.dev = pcap.findalldevs()[index]
Esempio n. 48
0
Gst.init(None)
del(gi, Gst, GObject)

__all__.extend(['VTLOG'])
import logging
VTLOG = logging.getLogger(__name__)
formatter = logging.Formatter('[%(asctime)s] %(levelname)s : %(message)s')
ch = logging.StreamHandler()
ch.setFormatter(formatter)
VTLOG.addHandler(ch)
VTLOG.setLevel(logging.ERROR)
del(logging, formatter, ch)

__all__.extend(['netifaces'])
import pcap
netifaces = [_[0] for _ in pcap.findalldevs() if _[1]==None]
del(pcap, _)

__all__.extend(['supported_protocols', 'supported_codecs'])
supported_protocols = ['udp', 'tcp', 'udp-mcast']
supported_codecs = {
    'h263': {
        'encoder': 'avenc_h263',
        'rtppay': 'rtph263pay',
        'rtpdepay': 'rtph263depay',
        'bitrate_from_kbps': lambda x: x*1000,
        'add': ''
    },
    'h264': {
        'encoder': 'x264enc',
        'rtppay': 'rtph264pay',
Esempio n. 49
0
    help="disable prp, and only capture headers, not the full frame",
)
parser.add_option(
    "-a",
    "--node-forget-time",
    type="float",
    metavar="SECONDS",
    default=30.0,
    help="idle time after which we forget all previos sequence numbers; 0.0=never",
)

options, args = parser.parse_args()

if options.interfaces:
    print "Interfaces available for capturing:"
    for x in pcap.findalldevs():
        print x[0], ":", x[1:]
    sys.exit(0)

if len(args) != 1:
    parser.print_help()
    sys.exit(1)

ignore_macs = []
if options.ignore:
    ignore_macs = options.ignore.split(",")

devnull = open(os.devnull, "w")
error = sys.stderr
info = sys.stdout  # general info
info_pp = sys.stdout  # info per packet
Esempio n. 50
0
from winreg import *
import dpkt, pcap, protocol, pcapsave

rawpacket = []
timestamp = []
devs = pcap.findalldevs()
net = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards"
reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
key = OpenKey(reg, net)
lst = []
for i in range(1024):
    try:
        keyname = EnumKey(key, i)
        try:
            for j in range(1024):
                route = net + "\\" + str(keyname)
                key2 = OpenKey(reg, route)
                a, b, c = EnumValue(key2, j)
                if 'Wireless' in str(b):
                    lst.append('WIFI')
                elif 'Realtek PCIe GbE Family Controller' in str(b):
                    lst.append('Ethernet')
                else:
                    lst.append(b)
        except:
            pass
    except:
        pass

for i in range(len(devs)):
    # print(devs[i][12:])
Esempio n. 51
0
def print_all_devs():
    i = 0
    for name, descr, addrs, flags in pcap.findalldevs():
        print '[+] if %02d: %s' % (i + 1, name)
        i += 1
 def getdevices(self):
     return pcap.findalldevs()
Esempio n. 53
0
	def __init__(self,parent=None):
		QtGui.QComboBox.__init__(self,parent)
		for name,descr, addrs, flags  in pcap.findalldevs():
        			self.addItem(name)
Esempio n. 54
0
def main():
    print("* ARP Table *")
    dev = pcap.findalldevs()[2]
    output = os.popen('arp -d')
    output = os.popen('arp -a')
    print(output.read())
    #request 패킷을 보낸 후 ARP 테이블을 생성한 뒤에 공격하고 탐지가 된다.

    i=1

    for timestamp, buf in pcap.pcap(name=dev):
        
        eth = dpkt.ethernet.Ethernet(buf)
        arp = eth.data

        if eth.type == 0x0806:  
           print("\n* [",i,"ARP ] *")

           if arp.op == 1 :  # request packet
               print(" - 요청(Request) 패킷 ------------------------------")
               print('|                                                             |')
               print('| 보내는 MAC (Sender.MAC) : ', ":".join(['%02x' % arp.sha[0],'%02x' % arp.sha[1],'%02x' % arp.sha[2],'%02x' % arp.sha[3],'%02x' % arp.sha[4],'%02x' % arp.sha[5]]),"|") # mac
               print('| 보내는 IP  (Sender.IP)        : ', str(int(arp.spa[0]))+"."+str(int(arp.spa[1]))+"."+str(int(arp.spa[2]))+"."+str(int(arp.spa[3])))  # ip
               print('|                                                             |')
               print('| 받는 MAC (Target.MAC)     : ', ":".join(['%02x' % arp.tha[0],'%02x' % arp.tha[1],'%02x' % arp.tha[2],'%02x' % arp.tha[3],'%02x' % arp.tha[4],'%02x' % arp.tha[5]]),"|") # mac
               print('| 받는 IP (Target.IP)             : ', str(int(arp.tpa[0]))+"."+str(int(arp.tpa[1]))+"."+str(int(arp.tpa[2]))+"."+str(int(arp.tpa[3])))  # ip
               print('|                                                             |')
               print(" ------------------------------------------------------")
               i+=1
               
               tIP = str(int(arp.tpa[0]))+"."+str(int(arp.tpa[1]))+"."+str(int(arp.tpa[2]))+"."+str(int(arp.tpa[3]))
               #print(tIP)

               if tIP in Request_List :
                   print("") # 이미 존재하는 Request IP
               else :
                   Request_List.append(tIP)                  
               #print(Request_List)
              

           if arp.op == 2 :  # reply packet
               print(" - 응답(Reply) 패킷  --------------------------------")
               print('|                                                             |')
               print('| 보내는 MAC (Sender.MAC) : ', ":".join(['%02x' % arp.sha[0],'%02x' % arp.sha[1],'%02x' % arp.sha[2],'%02x' % arp.sha[3],'%02x' % arp.sha[4],'%02x' % arp.sha[5]]),"|") # mac
               print('| 보내는 IP  (Sender.IP)        : ', str(int(arp.spa[0]))+"."+str(int(arp.spa[1]))+"."+str(int(arp.spa[2]))+"."+str(int(arp.spa[3])))  # ip
               print('|                                                             |')
               print('| 받는 MAC (Target.MAC)     : ', ":".join(['%02x' % arp.tha[0],'%02x' % arp.tha[1],'%02x' % arp.tha[2],'%02x' % arp.tha[3],'%02x' % arp.tha[4],'%02x' % arp.tha[5]]),"|") # mac
               print('| 받는 IP (Target.IP)             : ', str(int(arp.tpa[0]))+"."+str(int(arp.tpa[1]))+"."+str(int(arp.tpa[2]))+"."+str(int(arp.tpa[3])))  # ip
               print('|                                                             |')
               print(" ------------------------------------------------------")
               i+=1

               sIP = str(int(arp.spa[0]))+"."+str(int(arp.spa[1]))+"."+str(int(arp.spa[2]))+"."+str(int(arp.spa[3]))
               sMAC = "-".join(['%02x' % arp.sha[0],'%02x' % arp.sha[1],'%02x' % arp.sha[2],'%02x' % arp.sha[3],'%02x' % arp.sha[4],'%02x' % arp.sha[5]])
               #print(sIP,sMAC)
               
               if sIP in Request_List :# request 리스트 안에 있는 지 sIP 조회 하는 문구
                   Right_Reply(sIP,sMAC) # 올바른 reply패킷이므로 ARP_Table에 조회하는 함수로 넘어간다.
                   
               else :
                   print("\n!!!! request 리스트엔 없는 reply패킷 !!! ARP 스푸핑이 의심 됩니다 !!!!\n")
                   if sIP in ARP_Table :  # ARP_Table 에 Reply sender IP가 있는지 체크한다.
                       Mac_Check(sIP,sMAC)  # Mac 주소가 중복 되었는지 체크한다.
Esempio n. 55
0
 def getdevices(self):
     return pcap.findalldevs()