Ejemplo n.º 1
0
def sendReply(nonce):
  #build ethernet frame
  eth=ImpactPacket.Ethernet()
  eth.set_ether_type(0x88b5)
  eth.set_ether_shost(ETH_MY_MAC)
  eth.set_ether_dhost(ETH_MY_MAC)
  
  #build ip packet
  ip=ImpactPacket.IP()
  ip.set_ip_v(4)
  ip.set_ip_len(32)
  ip.set_ip_src("127.0.0.1")
  ip.set_ip_dst("127.0.0.1")
  
  #build UDP packet
  udp=ImpactPacket.UDP()
  udp.set_uh_sport(62001)
  udp.set_uh_dport(62000)
  udp.set_uh_ulen(12)
  payload=nonce
  udp.contains(ImpactPacket.Data(payload))
  
  ip.contains(udp)
  eth.contains(ip)
  
  device=findalldevs()[0]
  
  s=socket.socket(socket.AF_PACKET,socket.SOCK_RAW,socket.IPPROTO_RAW)  #socket initialized
  s.bind((findalldevs()[0],0))
  
  s.send(eth.get_packet())
  print "Sent: "+nonce
Ejemplo n.º 2
0
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.")
	parser.add_option("-r", "--remotehost", dest="remotehost", help="Remote host to backup pcaps")
	parser.add_option("-u", "--remoteuser", dest="remoteuser", help="Remote username to backup pcaps")
	parser.add_option("-p", "--remotepath", dest="remotepath", help="Path on remote host to backup to")
	(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, options.remotehost, options.remotepath, options.remoteuser)

	packet_limit = -1
	pc.loop(packet_limit, process_packets)
Ejemplo n.º 3
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
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
    def __init__(self, args):
        if len(args) < 2:
            print "\t[*] Please specify an adapter collect the WOL passwords from. Eg eth1"
            sys.exit(2)
        print "\n\t[*] WOL-E " + version + " [*]\n\t[*] Wake on LAN Explorer - WOL Packet Sniffer."
        print "\t[*] WOL packet sniffing has started [*]"

        # list all the network devices
        pcapy.findalldevs()

        pc = pcapy.open_live(args, 1024, False, 100)
        pc.setfilter('udp')

        # callback for received packets
        def recv_pkts(hdr, data):

            packet = str(EthDecoder().decode(data))

            writef("output.txt", packet)
            lineList = readf('output.txt')
            bcastframe = str(lineList[-7])
            if len(packet) in range(509, 514) and 'ffff' in bcastframe:
                lastline1 = str(lineList[-1])
                lastline = lastline1[0:14].replace(' ', '')
                print "\t[*] Detected WOL Client power on: " + lastline + ". Saving to WOLClients.txt"
                writea("WOLClients.txt",
                       lastline + " has been powed on using WOL\n")

            elif len(packet) > 514 and 'ffff' in bcastframe:
                packet = str(packet)
                password = packet[-7:]
                lastline = str(lineList[-1])
                lastline = lastline[0:14].replace(' ', '')
                passofwol = hex(ord(password[0])).replace(
                    '0x', '') + ":" + hex(ord(password[1])).replace(
                        '0x', '') + ":" + hex(ord(password[2])).replace(
                            '0x', '') + ":" + hex(ord(password[3])).replace(
                                '0x',
                                '') + ":" + hex(ord(password[4])).replace(
                                    '0x', '') + ":" + hex(ord(
                                        password[5])).replace('0x', '')
                print "\t[*] Detected WOL Client power on: " + lastline[
                    0:2] + ":" + lastline[2:4] + ":" + lastline[
                        4:6] + ":" + lastline[6:8] + ":" + lastline[
                            8:10] + ":" + lastline[10:12]
                print "\t[*] Password in Hex is: " + str(passofwol)
                writea(
                    "WOLClients.txt",
                    str(lastline) + " has been powed on with a password of: " +
                    str(passofwol) + "\n")

            else:
                pass

        packet_limit = -1
        pc.loop(packet_limit, recv_pkts)
Ejemplo n.º 6
0
def init():
    """
    Performs sensor initialization
    """

    global _cap
    global _datalink
    global _multiprocessing

    if config.USE_MULTIPROCESSING:
        try:
            import multiprocessing

            if multiprocessing.cpu_count() > 1:
                _multiprocessing = multiprocessing
        except (ImportError, OSError, NotImplementedError):
            pass

    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
Ejemplo n.º 7
0
 def dump(self):
     pcapy.findalldevs()
     p = pcapy.open_live(self.interface, self.__max_bytes,
                         self.__promiscuous, self.__buffer_timeout)
     p.setfilter(self.filters)
     packet_limit = -1
     print("Listen: %s, net=%s, mask=%s, linktype=[%d, %s] \n\n" %
           (self.interface, p.getnet(), p.getmask(), p.datalink(),
            self.data_link_str(p.datalink())))
     p.loop(packet_limit, self.ether)
Ejemplo n.º 8
0
def init():
    """
    Performs sensor initialization
    """

    global _cap
    global _datalink
    global _multiprocessing

    if config.USE_MULTIPROCESSING:
        try:
            import multiprocessing

            if multiprocessing.cpu_count() > 1:
                _multiprocessing = multiprocessing
        except (ImportError, OSError, NotImplementedError):
            pass

    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
Ejemplo n.º 9
0
def mysniff(interface):
    global ignore

    pcapy.findalldevs()
    pc = pcapy.open_live(interface, max_bytes, promiscuous, read_timeout)
    #ignoro i tipi che non hanno mac sorgente
    filt = 'not(subtype ack or subtype cts)'
    #aggiungo i mac da ignorare
    for e in ignore:
        filt = filt + ' and wlan addr2 not ' + e
    pc.setfilter(filt)
    packet_limit = -1  # -1 per infiniti
    pc.loop(packet_limit, recv_pkts)  # cattura pacchetti
Ejemplo n.º 10
0
    def start(self):
        # iface = self.iface
        # print iface
        # pc = pcapy.open_live(iface, 65535, False, 1)
        # pc.loop(-1, self.packprocess)

        # list all the network devices
        pcapy.findalldevs()

        max_bytes = 1024
        promiscuous = False
        read_timeout = 100  # in milliseconds
        pc = pcapy.open_live("eth0", max_bytes, promiscuous, read_timeout)
        packet_limit = -1  # infinite
        pc.loop(packet_limit, self.packprocess)  # capture packets
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)
Ejemplo n.º 12
0
def getInterface():

    # Get list of all network interfaces available for listening on
    interfaces = findalldevs()

    if len(interfaces) < 1:
        print "\nThere are no network interfaces available, "
        +"or you do not have the correct permissions to view them.\n"

        # If a single interface has been found...
    if len(interfaces) == 1:
        interface = interfaces[0]
    else:
        print "Network interfaces:\n"
        for i in range(len(interfaces)):
            print "---%i - %s\n" % (i + 1, interfaces[i])

        while True:
            input = raw_input("Select an interface to scan, or press 0 to quit: ")
            try:
                i = int(input)
                if i == 0:
                    interface = None
                    break
                interface = interfaces[i - 1]
                break
            except (SyntaxError, ValueError):
                pass
    return interface
Ejemplo n.º 13
0
def main():
    try:
        if len(sys.argv) != 2:
            print "Available devices:"
            print
            devices = pcapy.findalldevs()

            for device in devices:
                print device

            print
            print "Usage: ./%s deviceName", sys.argv[0]
            exit()

        global dev
        dev = sys.argv[1]

        print "Trying to set monitor mode for device " + dev + "..."
        os.system("ifconfig " + dev + " down")
        os.system("iwconfig " + dev + " mode monitor")
        os.system("ifconfig " + dev + " up")
        print "Done. If you don't see any data, the monitor mode setup may have failed."

        cap = pcapy.open_live(dev, 65536, True, 0)

        print
        print "Listening on %s: net=%s, mask=%s, linktype=%d" % (
            dev, cap.getnet(), cap.getmask(), cap.datalink())

        (header, packet) = cap.next()
        while header:
            parse_packet(packet)
            (header, packet) = cap.next()
    except KeyboardInterrupt:
        sys.exit(0)
Ejemplo n.º 14
0
    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)
Ejemplo n.º 15
0
    def create_veth_pair(self, in_name, out_name):
        iflist = pcapy.findalldevs()

        new_in = None
        new_out = None

        for iface in iflist:
            if iface == in_name:
                new_in = iface
            if iface == out_name:
                new_out = iface

        if not new_in and not new_out:
            logger.info(
                "Creating veth interface pair {in_name} and {out_name}")
            os.system(
                f"ip link add {in_name} type veth peer name {out_name} mtu {VETH_MTU}"
            )
            os.system(f"ip link set dev {in_name} up")
            os.system(f"ip link set dev {out_name} up")
            if self.destroy is None:
                self.destroy = True

        else:
            logger.warning(
                f"assuming {in_name} and {out_name} are properly configured")
            if self.destroy is None:
                self.destroy = False

        self.veth_in = new_in
        self.veth_out = new_out
Ejemplo n.º 16
0
Archivo: Pcap.py Proyecto: vanzan/slave
    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
Ejemplo n.º 17
0
    def capture_packet(self, argv):
        device = pcapy.findalldevs()[0]
        cap = pcapy.open_live(device, 65536, True, 0)

        # ホスト判定部------------------------------------------------------------------------------
        self.host_addr_v4 = subprocess.check_output(
            "ip a | grep {0}".format(device), shell=True)
        self.host_addr_v4 = str(self.host_addr_v4)
        first = self.host_addr_v4.index("inet") + 5
        last = self.host_addr_v4.index("brd") - 4
        self.host_addr_v4 = self.host_addr_v4[first:last]

        # サブネットマスクの計算
        self.subnet_mask = subprocess.check_output(
            "ip a | grep {0}".format(device), shell=True)
        self.subnet_mask = str(self.subnet_mask)
        first = self.subnet_mask.index("/") + 1
        last = self.subnet_mask.index("brd")
        self.subnet_mask = int(self.subnet_mask[first:last])
        ip_binary = ""
        while (self.subnet_mask > 0):
            ip_binary = ip_binary + "1"
            self.subnet_mask = self.subnet_mask - 1
        while (len(ip_binary) < 32):
            ip_binary = ip_binary + '0'
        self.subnet_mask = str(int(ip_binary[0:8], 2)) + "." + str(
            int(ip_binary[8:16], 2)) + "." + str(int(
                ip_binary[16:24], 2)) + "." + str(int(ip_binary[24:32], 2))
        # ------------------------------------------------------------------------------------------

        return cap
Ejemplo n.º 18
0
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)
Ejemplo n.º 19
0
	def checkInterface(self, iface):
		# check if there are interfaces available with pcapy
		try:
			ifs = pcapy.findalldevs()
		except pcapy.PcapError:
			self.logger.error("Unable to get interfaces. Are you running as root?")
			exit_gracefully()

		if 0 == len(ifs):
			self.logger.error("No interfaces available.")
			exit_gracefully()

		if not iface in ifs:
			self.logger.error("Interface '%s' not found." % (iface))
			exit_gracefully()

		ipAddresses = [] 
		for ifaceName in netifaces.interfaces():
			try:
				addresses = netifaces.ifaddresses(ifaceName)[netifaces.AF_INET]
				for address in netifaces.ifaddresses(ifaceName)[netifaces.AF_INET]:
					if iface == 'any':
						ipAddresses.append(address['addr'])
					elif iface == ifaceName:
						ipAddresses.append(address['addr'])
			except KeyError:
				if iface == ifaceName:
					self.logger.error("Interface '%s' is down." % (iface))
					exit_gracefully()
		return ipAddresses
Ejemplo n.º 20
0
def get_interface():
    if sys.platform == 'win32':
        # Windows 系统,找到首个有线网卡
        # 遍历所有有线网卡配置找到对应 UUID 的配置,并设置为静态地址
        c = wmi.WMI()
        wql = "select * from Win32_NetworkAdapter where AdapterTypeId=0 and NetConnectionID is not null"
        for iface in c.query(wql):
            for ifconf in c.Win32_NetworkAdapterConfiguration(Index=iface.Index):
                uuid = ifconf.SettingID
                dev = '\\Device\\NPF_%s' % uuid
                mac_addr = ifconf.MACAddress
                return dev, mac_addr
    else:
        # 其他系统,人工选择
        ifs = findalldevs()
        if 0 == len(ifs):
            print "You don't have enough permissions to open any interface on this system."
            sys.exit(1)
        elif 1 == len(ifs):
            print 'Only one interface present, defaulting to it.'
            return ifs[0]

        count = 0
        for iface in ifs:
            print '%i - %s' % (count, iface)
            count += 1
        idx = int(raw_input('Please select an interface: '))
        dev = ifs[idx]
        try:
            mac_addr = nif.ifaddresses(dev)[nif.AF_LINK][0]['addr']
        except:
            mac_addr = None
        return dev, mac_addr
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)
Ejemplo n.º 22
0
def main():
    # получаем список устройств
    dev_list = {}
    n = 0
    iface = ''
    for x in pcapy.findalldevs():
        dev_list[n] = x
        n += 1
    # берем первое из списка
    try:
        iface = dev_list[0]
    except KeyError:
        print "No device found"
        exit(1)
    if len(sys.argv) == 2:
        try:
            if sys.argv[1] in  ['list','ls','all']:
                for x in dev_list:
                    print 'Index:', x, 'Device name:' ,dev_list[x]
                return 0
            else:
                iface = dev_list[int(sys.argv[1])]
        except KeyError:
            print "Invalid device id, trying use first"
            iface = dev_list[0]
    # запускаем на полученном устройстве детектор
    ld = loopDetector(iface)
    ld.Process()
Ejemplo n.º 23
0
def create_usage():
    message = """USAGE: network_monitor.py
    <-d|--device DEVICE #>    device to sniff on (see list below)
    [-f|--filter PCAP FILTER] BPF filter string
    [-P|--log_path PATH]      log directory to store pcaps to
    [-l|--log_level LEVEL]    log level (default 1), increase for more verbosity
    [--port PORT]             TCP port to bind this agent to

Network Device List:
"""
    for index, pcapy_device in enumerate(pcapy.findalldevs()):
        IFS.append(pcapy_device)
        # if we are on windows, try and resolve the device UUID into an IP address.
        if sys.platform.startswith("win"):
            import _winreg

            try:
                # extract the device UUID and open the TCP/IP parameters key for it.
                pcapy_device    = pcapy_device[pcapy_device.index("{"):pcapy_device.index("}") + 1]
                subkey = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\%s" % pcapy_device
                key    = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey)

                # if there is a DHCP address snag that, otherwise fall back to the IP address.
                try:
                    ip = _winreg.QueryValueEx(key, "DhcpIPAddress")[0]
                except:
                    ip = _winreg.QueryValueEx(key, "IPAddress")[0][0]

                pcapy_device = pcapy_device + "\t" + ip
            except:
                pass

        message += "    [%d] %s\n" % (index, pcapy_device)
    return message
Ejemplo n.º 24
0
def main(argv):
    arpres = []
    choice = int(input("请输入 :\n1 离线工作模式\n2 在线工作模式\n"))
    if choice == 1:
        pcapfile = input("请输入pcap文件名:\n")
        cap = pcapy.open_offline(pcapfile)
    if choice == 2:
        devices = pcapy.findalldevs()
        print("可用网卡:")
        for d in devices:
            print(d)
        dev = input("请输入要监听的网卡:\n")
        print("正在监听网卡 " + dev)
        cap = pcapy.open_live(dev, 65536, 1, 100)
    myfilter = input('请输入过滤表达式:\n')

    cap.setfilter(myfilter)
    t1 = threading.Thread(target=loop,
                          args=(
                              cap,
                              arpres,
                          ),
                          name='LoopThread1')
    #t2=threading.Thread(target=loop,args=(cap,),name='LoopThread2')
    t1.start()
    #t2.start()
    t1.join()
Ejemplo n.º 25
0
    def sniff(self, lock):
        global results
        global res_requested
        res_requested = False
        # 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):
            try:
                (header, packet) = cap.next()
                #print ('%s: captured %d bytes, truncated to %d bytes' %(datetime.datetime.now(), header.getlen(), header.getcaplen()))
                self.parse_packet(packet, self.ports_filter, lock)
            except:
                print "Error parsing..."
                pass
Ejemplo n.º 26
0
    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
Ejemplo n.º 27
0
def main(argv):
    t = threading.Thread(name="watchfile_threading",
                         target=watch_file,
                         args=[directory])
    t.start()
    # 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("ens33", 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()))
        command = parse_packet(packet)
Ejemplo n.º 28
0
def get_interface():

    # Get the list of interfaces we can listen on
    ifs = findalldevs()

    # No interfaces found
    if len(ifs) == 0:
        raise RuntimeError, "Error: no available network interfaces, or you don't have enough permissions on this system."

    # A single interface was found
    if len(ifs) == 1:
        interface = ifs[0]

    # Multiple interfaces found
    else:
        print "Available network interfaces:"
        for i in xrange(len(ifs)):
            print '\t%i - %s' % (i + 1, ifs[i])
        print
        while 1:
            choice = raw_input("Choose an interface [0 to quit]: ")
            try:
                i = int(choice)
                if i == 0:
                    interface = None
                    break
                interface = ifs[i-1]
                break
            except Exception:
                pass

    # Return the selected interface
    return interface
Ejemplo n.º 29
0
def main():
    if len(sys.argv) != 2:
        print "Available devices:"
        print
        devices = pcapy.findalldevs()

        for device in devices:
            print device

        print
        print "Usage: ./%s deviceName", sys.argv[0]
        exit()

    dev = sys.argv[1]

    cap = pcapy.open_live(dev, 65536, 1, 0)

    print "Listening on %s: net=%s, mask=%s, linktype=%d" % (dev, cap.getnet(), cap.getmask(), cap.datalink())

    
    while(1):
        # updateRemainBuffer()
        header,packet = cap.next()
        if header is not None:
            packet_size = header.getlen()
            try:
                packet_encoded = pickle.dumps((get_flow(packet),packet_size))
                packetsock.send(packet_encoded)
            except Exception as e:
                pass
Ejemplo n.º 30
0
def getInterface():

    #Get list of all network interfaces available for listening on
    interfaces = findalldevs()

    if len(interfaces) < 1:
        print "\nThere are no network interfaces available, "
        + "or you do not have the correct permissions to view them.\n"

    #If a single interface has been found...
    if len(interfaces) == 1:
        interface = interfaces[0]
    else:
        print "Network interfaces:\n"
        for i in range(len(interfaces)):
            print "---%i - %s\n" % (i + 1, interfaces[i])

        while True:
            input = raw_input(
                "Select an interface to scan, or press 0 to quit: ")
            try:
                i = int(input)
                if i == 0:
                    interface = None
                    break
                interface = interfaces[i - 1]
                break
            except (SyntaxError, ValueError):
                pass
    return interface
Ejemplo n.º 31
0
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)
Ejemplo n.º 32
0
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 = "".join(list(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 True:
        (header, packet) = cap.next()
        packet = parse_packet(packet)
        if packet is not None:
            print(packet)
Ejemplo n.º 33
0
def main(argv):
    try:
        signal.signal(signal.SIGINT, signal_handler)
        ifaces = pcapy.findalldevs()
        try:
            opts, args = getopt.getopt(argv, "hi:", ["iface="])
            for opt, arg in opts:
                if opt == '-h':
                    print 'Usage:', sys.argv[0], '-i <interface>'
                elif opt in ("-i", "--iface"):
                    iface = arg
                    if iface in ifaces:
                        monitor_traffic(iface)
                    else:
                        print 'Invalid capture devie !\n'
            if len(opts) == 0:
                i = 0
                print 'Available interfaces:\n'
                for iface in ifaces:
                    print i, ':', iface
                    i += 1
                iDev = int(raw_input('Select 0..{}:\t'.format(len(ifaces) -
                                                              1)))
                if iDev >= 0 and iDev < len(ifaces):
                    print "Selected:", ifaces[iDev]
                    monitor_traffic(ifaces[iDev])
                else:
                    print 'Invalid capture device !\n'
        except getopt.GetoptError:
            print 'Usage:', sys.argv[0], '-i <interface>'
    except KeyboardInterrupt:
        sys.exit(0)
Ejemplo n.º 34
0
def main(args):
    try:
        os.remove("out.au")
    except OSError:
        pass
    try:
        if args.interface:
            dev = args.interface
        else:
            #ask user to enter device name to sniff
            print("Available devices are :")
            for d in pcapy.findalldevs():
                print(d)
            dev = input("Enter device name to sniff : ")
            try:
                os.system(monitor_enable.format(dev))
            except OSError as error:
                print("OS error: {}".format(error))
        capture = pcapy.open_live(dev, 65536, True, 0)
        if args.time:
            timeout = args.time
        else:
            timeout = 30
        timeout_start = time.time()
        while time.time() < timeout_start + timeout:
            (header, packet) = capture.next()
            print(
                '%s: captured %d bytes, truncated to %d bytes' %
                (datetime.datetime.now(), header.getlen(), header.getcaplen()))
            parse_packet(packet)
        convert_au()
    except (KeyboardInterrupt):
        sys.exit()
    finally:
        os.system(monitor_disable.format(dev))
Ejemplo n.º 35
0
def main(argv):
    devices = pcapy.findalldevs()
    # print(devices)
    # print("Available devices are: ")
    # for d in devices:
    # print(d)

    # dev = input("Enter device name to sniff: ")
    dev = 'tap0'
    # print("Sniffing device " + dev)
    """
    open device
    # Arguments here are:
    #   device
    #   snaplen (maximum number of bytes to capture _per_packet_)
    #   promiscuous mode (1 for true)
    #   timeout (in milliseconds)
    """
    f = open('/home/brian/Desktop/test.txt', 'w')
    f.write(str(datetime.datetime.now()))
    f.close()
    cap = pcapy.open_live(dev, 65536, 1, 0)
    # Start sniffing packets
    while 1:
        (header, packet) = cap.next()
        parse_packet(packet)
Ejemplo n.º 36
0
def create_usage():
    message = """USAGE: network_monitor.py
    <-d|--device DEVICE #>    device to sniff on (see list below)
    [-f|--filter PCAP FILTER] BPF filter string
    [-P|--log_path PATH]      log directory to store pcaps to
    [-l|--log_level LEVEL]    log level (default 1), increase for more verbosity
    [--port PORT]             TCP port to bind this agent to

Network Device List:
"""
    for index, pcapy_device in enumerate(pcapy.findalldevs()):
        IFS.append(pcapy_device)
        # if we are on windows, try and resolve the device UUID into an IP address.
        if sys.platform.startswith("win"):
            import _winreg

            try:
                # extract the device UUID and open the TCP/IP parameters key for it.
                pcapy_device    = pcapy_device[pcapy_device.index("{"):pcapy_device.index("}") + 1]
                subkey = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\%s" % pcapy_device
                key    = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey)

                # if there is a DHCP address snag that, otherwise fall back to the IP address.
                try:
                    ip = _winreg.QueryValueEx(key, "DhcpIPAddress")[0]
                except:
                    ip = _winreg.QueryValueEx(key, "IPAddress")[0][0]

                pcapy_device = pcapy_device + "\t" + ip
            except:
                pass

        message += "    [%d] %s\n" % (index, pcapy_device)
    return message
Ejemplo n.º 37
0
def sendReply(nonce):
    #build ethernet frame
    eth = ImpactPacket.Ethernet()
    eth.set_ether_type(0x88b5)
    eth.set_ether_shost(ETH_MY_MAC)
    eth.set_ether_dhost(ETH_MY_MAC)

    #build ip packet
    ip = ImpactPacket.IP()
    ip.set_ip_v(4)
    ip.set_ip_len(32)
    ip.set_ip_src("127.0.0.1")
    ip.set_ip_dst("127.0.0.1")

    #build UDP packet
    udp = ImpactPacket.UDP()
    udp.set_uh_sport(62001)
    udp.set_uh_dport(62000)
    udp.set_uh_ulen(12)
    payload = nonce
    udp.contains(ImpactPacket.Data(payload))

    ip.contains(udp)
    eth.contains(ip)

    device = findalldevs()[0]

    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x88b5))
    s.bind(('lo', 0))

    s.send(eth.get_packet())
    print "Sent: " + nonce
    signal.alarm(0)  #disable the alarm
Ejemplo n.º 38
0
def getInterface():
    # Grab a list of interfaces that pcap is able to listen on.
    # The current user will be able to listen from all returned interfaces,
    # using open_live to open them.
    ifs = findalldevs()

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

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

    # 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(input('Please select an interface: '))

    return ifs[idx]
Ejemplo n.º 39
0
	def __init__(self, cf, eventQueue):
		Thread.__init__(self)
		self.minPackCount=cf.getint("SlackPhone", "minpacketcount")
		self.wirelessinterface = cf.get("SlackPhone", "wlaninterface")
		self.broadcast=netinfo.get_broadcast(self.wirelessinterface)
		self.gateway=netinfo.get_routes(self.wirelessinterface)[0]["gateway"]
		self.device = cf.get("SlackPhone", "inetdevice")
		self.startDev = cf.get("SlackPhone", "startdevice")
		self.devices = pcapy.findalldevs()
		self.valid_packet = globals()[ "valid_%s_packet"%cf.get("SlackPhone", "phonetype")]
		logging.info( self.devices)
		try:
			self.filter = cf.get("SlackPhone", "tcpfilter")
		except:
			self.filter = None
		try:
			phonemap = cf.get("SlackPhone", "phonemap")
		except:
			phonemap = None

		try:
			self.phonemap = json.loads( phonemap )
		except Exception, e:
			logging.exception(e)
			self.phonemap = {}
Ejemplo n.º 40
0
def network_capture(pcap_file, dumper, interface):
    mac_addresses = []
    counter = 0
    ipcounter = 0
    tcpcounter = 0
    udpcounter = 0
    devcounter = 0
    # list all devices
    devices = pcapy.findalldevs()
    logging.info('Read the following devices: %s', devices)

    # list avialable network interfaced
    logging.info('Following devices are available: %s', devices)

    logging.info('Sniffing on following device: %s', interface)

    cap = pcapy.open_live(interface, 65536, 1, 0)

    logging.info('Starting sniffing.. Stopping with ctrl+c')
    # time.sleep(5)

    # start sniffing packets for the count of capturing
    #f = open('capture.pcap', 'w')
    dumper = cap.dump_open("capture.pcap")

    while True:
        try:
            (header, packet) = cap.next()
            dumper.dump(header, packet)
        except KeyboardInterrupt:
            break  # stop listening on the interface
Ejemplo n.º 41
0
def start(interface):
    """Start Interface Capture"""
    if interface in pcapy.findalldevs():
        CaptureContext.Start(interface)
        return StandardResponse(True, '%s started.' % interface)
    else:
        return StandardResponse(False, '%s not found.' % interface)
Ejemplo n.º 42
0
def Select_Capture_Devices(Capture_Device):
    Devices = pcapy.findalldevs()

    if Capture_Device not in Devices:
        logWrite('Capture Device Name Not Recongnized. Please Try Again')
        Capture_Device = None

    return Capture_Device
Ejemplo n.º 43
0
 def getNetworkDevices(self):
     interfaces = []
     # list of interfaces
     try:
         interfaces = pcapy.findalldevs()
     except:
         logging.warn("You don't have enough permissions to open any network interface on this system. Please look at the README.rst file for more information.")
     return interfaces
Ejemplo n.º 44
0
def select_device():
    devices = pcapy.findalldevs()
    for i, dev in enumerate(devices):
        print("%d. %s" % (i, dev))
    print('Enter interface number:', end=' ')
    num = int(input())
    assert num in range(len(devices)), "Incorrect interface number"
    return devices[num]
Ejemplo n.º 45
0
def get_interface():
    inter = findalldevs()
    i = 0
    for eth in inter:
        print " %d - %s" % (i, inter[i])
        i += 1
    value = input(" Select interface: ")
    return inter[value]
Ejemplo n.º 46
0
def get_interface():
    inter = findalldevs()
    i=0
    for eth in inter:
        print " %d - %s" %(i,inter[i])
        i+=1
    value=input(" Select interface: ")
    return inter[value]
Ejemplo n.º 47
0
def main(argv):
  #list all devices
  devs = pcapy.findalldevs()
  #print "Devices List"
  #for i in devs:
    #print "<%s>Dev:%s,Network:%s" %(devs.index(i),i,pcapy.open_live(i,0,0,0).getnet())
  idx = 0 #raw_input("Your choice : ")
  dev = devs[int(idx)]
  xls_name="Mesg.xls"	
  '''
  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)
  cap.setfilter("tcp port 80")
  print "Listening on %s" %dev
  http_pattern=re.compile('HTTP/1.1')
  #page_pattern=re.compile(r'<html xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:msgs="ovow_webconsole" xmlns:userdate="ovow_webconsole_date">.*?</html>',re.S)
  page_pattern=re.compile(r'<html xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:user="******" xmlns:userdate="ovow_webconsole_date">.*?</html>',re.S)
  #start sniffing packets
  html_count=0
  html_dic={}
  mesg_dic={}
  mesg=[]
  mesg_writed=[]
  write_mesg_to_xls(mesg_writed,mesg_dic,xls_name)
  mesg_writed=init(xls_name)
  while(1) :
    (header, packet) = cap.next()
    #print ('%s: captured %d bytes, truncated to %d bytes' %(datetime.datetime.now(), header.getlen(), header.getcaplen()))
    http_packet=parse_packet(packet)
    if http_packet:
      if re.search(http_pattern,http_packet):
        if html_count !=0:
          html=re.findall(page_pattern,html_dic[html_count])
          html_dic={}
          if html:
            mesg_all=collect_mesg_from_html(html)
            if mesg_all:
              mesg=choose_data_in_mesglist(mesg_all)
              time=mesg[2]
              if time not in mesg_dic.keys():
                mesg_dic[time]=[]
                for mesg_data in mesg:
                  mesg_dic[time].append(mesg_data)
                #print mesg_dic
                #print
                write_mesg_to_xls(mesg_writed,mesg_dic,xls_name)
                mesg_writed.append(time)
        html_count +=1
      if html_dic.has_key(html_count):
        html_dic[html_count] +=http_packet
      else:
        html_dic[html_count]=http_packet
Ejemplo n.º 48
0
def devs():
    """Muestra las interfaces de red disponibles."""

    try:
        print "Interfaces de red disponibles:"
        for d in pcapy.findalldevs():
            print "\t" + d
    except pcapy.PcapError:
        print "Error: No pudo accederse a los dispositivos. (¿Se cuenta con los privilegios necesarios?)"
Ejemplo n.º 49
0
 def __init__(self):
     QtCore.QThread.__init__(self)
     self.devices = pcapy.findalldevs()
     self.dev=str(self.devices[0])
     #~ self.dev='ppp0' 
     self.packets=[]
     #~ print 'capt started'
     self.stopSig=1
     self.devChanged=0
Ejemplo n.º 50
0
def get_int():
    devs = pcapy.findalldevs()
    i = 0
    for eth in devs:
        print " %d - %s" % (i, devs[i])
        i += 1
    sel = input(" Select interface: ")
    dev = devs[sel]
    return dev
Ejemplo n.º 51
0
    def set_interface(self, interface=None):
        from pcapy import findalldevs

        # Get the list of interfaces we can listen on
        ifs = findalldevs()

        # No interfaces found
        if len(ifs) == 0:
            raise RuntimeError, "Error: no available network interfaces, or you don't have enough permissions on this system."

        # Multiple interfaces found
        else:
            if interface not in ifs and interface != None:
                # A single interface was found
                print "The specified interface doesnt match the available interface please choose one from the available ones"
                print "Available network interfaces:"
                for i in xrange(len(ifs)):
                    print "\t%i - %s" % (i + 1, ifs[i])
                print
                while True:
                    choice = raw_input("Choose an interface [0 to quit]: ")
                    try:
                        i = int(choice)
                        if i == 0:
                            interface = None
                            break
                        interface = ifs[i - 1]
                        break
                    except Exception:
                        pass
                # Return the selected interface
                self.CONFIG_DICT["DEV"] = interface
                print "Interface set %s" % (self.CONFIG_DICT["DEV"])
            elif interface != None and interface in ifs:
                # Return the set interface
                self.CONFIG_DICT["DEV"] = interface
                print "Interface set %s" % (self.CONFIG_DICT["DEV"])
            else:
                print "Available network interfaces:"
                for i in xrange(len(ifs)):
                    print "\t%i - %s" % (i + 1, ifs[i])
                print
                while True:
                    choice = raw_input("Choose an interface [0 to quit]: ")
                    try:
                        i = int(choice)
                        if i == 0:
                            interface = None
                            break
                        interface = ifs[i - 1]
                        break
                    except Exception:
                        pass
                # Return the selected interface
                self.CONFIG_DICT["DEV"] = interface
                print "Interface set %s" % (self.CONFIG_DICT["DEV"])
Ejemplo n.º 52
0
    def canvas_detect(self):
        self.lilnew1.delete(0, END)
        holddevices=pcapy.findalldevs()
	for devices in holddevices:
            if devices=="any":
                self.lilnew1.insert(0, )    
	    elif devices=="lo": 
		self.lilnew1.insert(0, )      
            else:
                self.lilnew1.insert(0, devices)
Ejemplo n.º 53
0
def get_device():
    devices=findalldevs()
    i=0
    for i in xrange(len(devices)):
         print ("%i - %s" %(i+1, devices[i]))
         i=i+1
    num=raw_input("input device number : ")
    number=int(num)
    dev=devices[number]
    return dev
Ejemplo n.º 54
0
  def __init__(self,args):
    if len(args) < 2:
      print "\t[*] Please specify an adapter collect the WOL passwords from. Eg eth1"
      sys.exit(2)
    print "\n\t[*] WOL-E " + version + " [*]\n\t[*] Wake on LAN Explorer - WOL Packet Sniffer."
    print "\t[*] WOL packet sniffing has started [*]"
    
    # list all the network devices
    pcapy.findalldevs()

    pc = pcapy.open_live(args, 1024, False, 100)
    pc.setfilter('udp')
      
    # callback for received packets
    def recv_pkts(hdr, data):
      
        packet = str(EthDecoder().decode(data))

        writef("output.txt",packet) 
        lineList = readf('output.txt')
        bcastframe = str(lineList[-7])
        if len(packet) in range(509,514) and 'ffff' in bcastframe:
          lastline1 = str(lineList[-1])
          lastline = lastline1[0:14].replace(' ', '')
          print "\t[*] Detected WOL Client power on: " + lastline + ". Saving to WOLClients.txt"
          writea("WOLClients.txt", lastline + " has been powed on using WOL\n")

        elif len(packet) > 514 and 'ffff' in bcastframe:
          packet = str(packet)
          password = packet[-7:]
          lastline = str(lineList[-1])
	  lastline = lastline[0:14].replace(' ', '')
          passofwol = hex(ord(password[0])).replace('0x', '') + ":" + hex(ord(password[1])).replace('0x', '') + ":" + hex(ord(password[2])).replace('0x', '') + ":" + hex(ord(password[3])).replace('0x', '') + ":" + hex(ord(password[4])).replace('0x', '') + ":" + hex(ord(password[5])).replace('0x', '')
	  print "\t[*] Detected WOL Client power on: " + lastline[0:2] + ":" + lastline[2:4] + ":" + lastline[4:6] + ":" + lastline[6:8] + ":" + lastline[8:10] + ":" + lastline[10:12]
	  print "\t[*] Password in Hex is: " + str(passofwol)
          writea("WOLClients.txt", str(lastline) + " has been powed on with a password of: " + str(passofwol) + "\n")
          
        else:
          pass 
     
    packet_limit = -1
    pc.loop(packet_limit, recv_pkts)
Ejemplo n.º 55
0
def get_ifs():
    """
    Get a list of network interfaces on the system.

    :rtype : list[str]
    :return: List of network interfaces.
    """
    ifs = []
    for index, pcapy_device in enumerate(pcapy.findalldevs()):
        ifs.append(pcapy_device)
    return ifs
Ejemplo n.º 56
0
def getInterfaces():
    # Grab a list of interfaces that pcap is able to listen on.
    # The current user will be able to listen from all returned interfaces,
    # using open_live to open them.
    ifs = findalldevs()

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

    return ifs
Ejemplo n.º 57
0
def main():
 
  
  print "Server.... Port: 62001"
  print "--------------------------------------------"
  p=open_live(findalldevs()[0],46,False,100)
  print "Listening...."
  
  p.setfilter("udp")
  p.setfilter("src port 62000")
  
  ethDecoded = p.loop(1,EthDecoder1)
Ejemplo n.º 58
0
Archivo: sni.py Proyecto: nbabook/uDPI
def pick_device():
    #list all devices
    devices = pcapy.findalldevs()

    print "Available devices are :"
    for d in devices :
        print d

    dev = raw_input("Enter device name to sniff : ")

    print "Sniffing device chosen: " + dev
    return dev
Ejemplo n.º 59
0
        def getInterface(expression):
            ifs = findalldevs()
            if 0 == len(ifs):
                print "You don't have enough permissions to open any interface on this system."
                sys.exit(1)

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

            input = int(expression)  # turns into an integer for the function to accept
            return ifs[input]  # returns the inputted interface