示例#1
0
def main():
	lst=[]
	i=0
	while True:
		#print(len(cap))
		header, payload= cap.next()
		dest_mac, src_mac, eth_proto, data= ethrnet_frame(payload)
		#print('\nEthernet Frame:')
		a=('Desitantion: {}, Source:{}, Protocol:{}'.format(dest_mac,src_mac,eth_proto))
		p1 = manuf.MacParser(update=True)
		if src_mac== 'F6:5C:89:8C:45:64':
			src_val= 'Local'
		else:
			src_val=p1.get_manuf(src_mac)
		p2 = manuf.MacParser(update=True)
		if dest_mac== 'F6:5C:89:8C:45:64':
			dst_val= 'Local'
		else:
			dst_val=p2.get_manuf(dest_mac)
		#print(src_val)
		#print(dst_val)
		i=i+1
		if (i==7):
			print('ALERT!!!!')
		#if src_val==None or dst_val== None:
		#	print(a)
		else:
			print('.')
		lst.append(a)
def getOUIDB():
    ouidb = None
    
    if hasOUILookup:
        if  os.path.isfile('manuf'):
            # We have the file but let's not update it every time we run the app.
            # every 90 days should be plenty
            last_modified_date = datetime.datetime.fromtimestamp(os.path.getmtime('manuf'))
            now = datetime.datetime.now()
            age = now - last_modified_date
            
            if age.days > 90:
                updateflag = True
            else:
                updateflag = False
        else:
            # We don't have the file, let's get it
            updateflag = True
            
        try:
            ouidb = manuf.MacParser(update=updateflag)
        except:
            if updateflag:
                print("WARNING: Unable to update mac address vendor database.  Continuing with old database.")

            try:
                ouidb = manuf.MacParser(update=False)
            except:
                    print("WARNING: Unable to open the mac address vendor database.  Disabling lookup.")
                    ouidb = None
    else:
        ouidb = None
        
    return ouidb
示例#3
0
def get_interface_manufacturer(mac):
    try:
        p = manuf.MacParser()
    except FileNotFoundError:
        p = manuf.MacParser(update=True)

    return p.get_manuf(mac)
示例#4
0
def show_vendors():
	other = 0.032  # percentage threshold of being put under 'Others'

	sizes = {}
	vendors = {}
	total = 0

	data = csv.reader(open(file_path), delimiter='	')
	for row in data:
		MAC_scr = row[1][0:8]
		if MAC_scr in sizes:
			sizes[MAC_scr] += 1
		else:
			sizes[MAC_scr] = 1
		total += 1

	p = manuf.MacParser(update=True)
	for key, value in sizes.items():
		vendor = p.get_manuf(key + ':00:00:00')
		if vendor in vendors:
			vendors[vendor] += value
		else:
			vendors[vendor] = value

	vendors2 = {"other": 0}
	for key, value in vendors.items():

		if value < total * other:
			vendors2["other"] += value
		else:
			vendors2[key] = value

	plt.pie(vendors2.values(), labels=vendors2.keys(), autopct='%1.1f%%', shadow=True, startangle=140)
	plt.show()
def macaddressconverterprobe():
    for i in range(50):
        p = manuf.MacParser(update=True)
        mycursor.execute(
            """SELECT wlansa from dwccincomingprobe WHERE wlansaconverted IS NULL OR wlansaconverted = '' limit 1;"""
        )
        mactochange = mycursor.fetchone()

        print "The probe mac that will be changed", mactochange
        if mactochange is None:
            print "all probe MAC matched to vendors"
            return
        else:
            #This below will remove the punctuation for the VAR
            mactochange = ''.join(c for c in mactochange
                                  if c not in string.punctuation)
            changedmac = p.get_manuf(mactochange)
            changedmacstr = str(changedmac)
            mactochangestr = str(mactochange)
            #This below will write the mac vendor back to the database
            mycursor.execute(
                "UPDATE dwccincomingprobe SET wlansaconverted = " +
                ` changedmacstr ` + " WHERE wlansa  = " + ` mactochangestr ` +
                "   ;")
#			macaddressconverterap()
    print "finished a round up to 50 probe mac"
def create_webapp(database_loc, log_file="-", verbose=False):
    setup_logging(log_file, verbose)

    parser = manuf.MacParser(update=True)
    bottle.TEMPLATE_PATH.append(VIEWS_DIR)

    def pretty_print_mac_info(mac):
        info = parser.get_all(mac)
        if info.manuf is None:
            return "Vendor: ???"
        elif info.comment is None:
            return "Vendor: {0}".format(info.manuf)
        else:
            return "Vendor: {0} ({1})".format(info.manuf, info.comment)

    app = bottle.Bottle()
    db_conn = create_connection(database_loc)
    write_schema(db_conn)
    views = NodeViews(app,
                      db_conn,
                      mac_decoder=pretty_print_mac_info,
                      webserver_data_generator=webserver_info_hof())
    views.attach()
    api = NodeAPI(app, db_conn)
    api.attach()
    return app
示例#7
0
    def create_device_list(self):
        device_list_unfiltered = []
        print("Please wait while we generate the device list.")
        mac_parser = manuf.MacParser(update=True)

        for pkt in self.cap:
            for device in device_list_unfiltered:
                if device.MAC == pkt.eth.src:
                    try:
                        if device.IP == "" and pkt.ip.src != "0.0.0.0" and ipaddress.ip_address(
                                pkt.ip.src).is_private:
                            device.IP = pkt.ip.src
                    except AttributeError:
                        pass
                    break
            else:
                manufacturer = str(mac_parser.get_manuf(pkt.eth.src))
                if manufacturer != "None":
                    new_device = Device()
                    new_device.MAC = pkt.eth.src
                    new_device.Manufacturer = manufacturer
                    try:
                        if pkt.ip.src != "0.0.0.0" and ipaddress.ip_address(
                                pkt.ip.src).is_private:
                            new_device.IP = pkt.ip.src
                        else:
                            raise AttributeError
                    except AttributeError:
                        new_device.IP = ""
                    device_list_unfiltered.append(new_device)

            for device in device_list_unfiltered:
                if device.MAC == pkt.eth.dst:
                    try:
                        if device.IP == "" and pkt.ip.dst != "0.0.0.0" and ipaddress.ip_address(
                                pkt.ip.dst).is_private:
                            device.IP = pkt.ip.dst
                    except AttributeError:
                        pass
                    break
            else:
                manufacturer = str(mac_parser.get_manuf(pkt.eth.dst))
                if manufacturer != "None":
                    new_device = Device()
                    new_device.MAC = pkt.eth.dst
                    new_device.Manufacturer = manufacturer
                    try:
                        if pkt.ip.dst != "0.0.0.0" and ipaddress.ip_address(
                                pkt.ip.dst).is_private:
                            new_device.IP = pkt.ip.dst
                        else:
                            raise AttributeError
                    except AttributeError:
                        new_device.IP = ""
                    device_list_unfiltered.append(new_device)

        for device in device_list_unfiltered:
            if device.IP != "":
                self.__device_list.append(device)
示例#8
0
def get_client_details(mac_address, arp_table=None):
    arp_table = arp_table if arp_table is not None else get_arp_table()
    client_details = {
        'mac_address': mac_address,
        'ip_address': arp_table[mac_address],
        'manufacturer': manuf.MacParser().get_manuf(mac_address),
    }

    return client_details
示例#9
0
def mac_to_vendor(mac):
    """

    Args:
        mac ():

    Returns:

    """
    p = manuf.MacParser(update=False)
    return p.get_manuf_long(mac)
示例#10
0
 def __init__(self, MAC, latitude,
              longitude):  #Creates a new device instance
     self.manuf = manuf.MacParser()
     self.MAC = MAC
     self.firstSeen = datetime.datetime.utcnow()
     self.lastSeen = self.firstSeen
     self.seenCount = 1
     self.ESSIDs = set()
     self.manufacturer = self.manuf.get_manuf_long(MAC)
     self.latitude = latitude
     self.longitude = longitude
示例#11
0
 def proc(p):
     if ( p.haslayer(Dot11ProbeReq) ):
             mac=re.sub('','',p.addr2)
             ssid=p[Dot11Elt].info
             ssid=ssid.decode('utf-8','ignore')
             v = manuf.MacParser(update=True)
             ven = v.get_manuf(p.addr2)
             if ssid == "":
                 ssid="gen-probe no SSID"
                 print >> f, strftime("%m/%d/%Y %H:%M:%S - ") + "[%s] - [%s] looking for --> [%s]" %(mac,ven,ssid)
                 print strftime("%m/%d/%Y %H:%M:%S - ") + "[%s] - [%s] looking for --> [%s]" %(mac,ven,ssid)
示例#12
0
def find(time_range, hostname_must_contains=[], vendors=[]):

    events = msiempy.event.EventManager(
        fields=["HostID", "UserIDSrc", "SrcIP", "SrcMac", "DSIDSigID"],
        time_range=time_range,
        filters=[
            msiempy.event.FieldFilter("Alert.DSIDSigID",
                                      [DHCP_RENEW, RADIUS_START])
        ],
        limit=500,
    )

    print("Loading data...")
    events.load_data(slots=10, workers=5, max_query_depth=2)
    print("{} events have been loaded from the SIEM".format(len(events)))

    if len(vendors) > 0:
        print("Filtering vendors...")
        mac = manuf.MacParser(update=True)
        vendor_filtered_events = list()

        for event in events:

            device_vendor = mac.get_manuf(event["Alert.SrcMac"])
            if device_vendor == None:
                continue

            for vendor in vendors:
                if vendor.lower() in device_vendor.lower():
                    vendor_filtered_events.append(event)
                    break

        events = vendor_filtered_events
    print("{} events matches the vendor(s)".format(len(events)))

    print("Aggregating events and devices...")
    devices = aggregate_list_based_on_SrcMac(events)
    print("{} unique devices in total".format(len(devices)))

    # Apply host filters
    host_filtered_devices = list()
    for dev in devices:
        if len(hostname_must_contains) == 0 or any([
                match.lower() in dev.get("host").lower()
                for match in hostname_must_contains
        ]):
            host_filtered_devices.append(dev)
    if len(devices) > len(host_filtered_devices):
        devices = host_filtered_devices
        print("{} devices matches hostname filter(s)".format(len(devices)))

    return msiempy.NitroList(alist=devices)
示例#13
0
def get_mac_info(mac):
    data = None
    try:
        query = manuf.MacParser(update=True)
        data = query.get_manuf_long(mac)

    except:
        abort(400, 'Record not found')

    if not data:
        abort(404, "Not found")

    return render_template('api/mac.html', data=data)
示例#14
0
def getManuf(mac):
    try:
        from manuf import manuf
        parser = manuf.MacParser(manuf_name='manuf/manuf')
        print('\n')
        m = parser.get_all(mac)
        if m.manuf:
            manufacture = '{} {}'.format(
                m.manuf, '(' + m.comment + ')' if m.comment else '')
        else:
            manufacture = '-'
        return manufacture
    except:
        return '-'
示例#15
0
def run_detection():
    while True:

        full_results = [
            re.findall('^[\w\?\.]+|(?<=\s)\([\d\.]+\)|(?<=at\s)[\w\:]+', i)
            for i in os.popen('arp -a')
        ]
        final_results = [
            dict(zip(['IP', 'LAN_IP', 'MAC_ADDRESS'], i)) for i in full_results
        ]
        final_results = [{
            **i,
            **{
                'LAN_IP': i['LAN_IP'][1:-1]
            }
        } for i in final_results]

        mac = [('MAC_ADDRESS' in final_results[i])
               for i in range(len(final_results))]

        local = [
            final_results[i]['LAN_IP'][:3] == '192'
            for i in range(len(final_results))
        ]

        addr = [
            final_results[i]['MAC_ADDRESS'] for i in range(len(final_results))
            if mac[i] & local[i]
        ]

        manu = []
        for i in addr:
            p = manuf.MacParser(update=True)
            tup = p.get_manuf(i)
            manu.append(tup)

        device_list = []
        for n in manu:
            if n == None:
                continue
            if n == 'Apple':
                d = {'name': 'iPhone X', 'traffic': '10'}
                device_list.append(d)
            if n == 'WyzeLabs':
                d = {'name': 'WyzeCam', 'traffic': '10'}
                device_list.append(d)
        json_file['device_list'] = device_list

        print(manu)
示例#16
0
文件: yapns.py 项目: pprobst/yapns
def updateClientsFile(f, tempfile, clients):
    print("Updating clients.csv...")

    fields = ['IP', 'COUNT', 'STATUS', 'MAC', 'VENDOR', 'TIMESTAMP']
    reader = csv.DictReader(f, fieldnames=fields)
    writer = csv.DictWriter(tempfile, fieldnames=fields)
    header = next(reader)  # = fields
    writer.writerow(header)

    row_list = list(reader)
    ip_mac_list = []
    for row in row_list:
        info = {'ip': row['IP'], 'mac': row['MAC']}
        ip_mac_list.append(info)

    updated_rows = []
    parser = manuf.MacParser(update=False)

    for client in clients:
        # New clients.
        if client not in ip_mac_list:
            row = {
                'IP': client['ip'],
                'COUNT': 1,
                'STATUS': "ACTIVE",
                'MAC': client['mac'],
                'VENDOR': getVendor(client['mac'], parser),
                'TIMESTAMP': str(datetime.now())[:16]
            }
            updated_rows.append(row)
        # Updates old clients (COUNT++).
        else:
            idx = ip_mac_list.index(client)
            old_count = int(row_list[idx]['COUNT'])
            row_list[idx]['COUNT'] = old_count + 1

    # Old but inactive clients.
    for idx, old_client in enumerate(ip_mac_list):
        if not any(client == old_client for client in clients):
            row_list[idx]['STATUS'] = "INACTIVE"
        else:
            row_list[idx]['STATUS'] = "ACTIVE"

    updated_rows += row_list

    for row in updated_rows:
        writer.writerow(row)
示例#17
0
def main():
    # sniff on specified channel
    cmd = f'iw dev {args.interface} set channel {args.channel}'
    try:
        subprocess.check_call(cmd.split(' '))
    except subprocess.CalledProcessError as c:
        print(
            f'Error: failed to switch to channel {args.channel} for interface {args.interface}',
            file=sys.stderr)
        sys.exit(-1)

    update_vdb = False
    global vendor_db
    if not os.path.isfile(MANUF_FILE):
        update_vdb = True
    if update_vdb:
        print('Updating and loading manuf file')
    else:
        print('Loading manuf file')
    vendor_db = manuf.MacParser(manuf_name='./manuf', update=update_vdb)

    # use a detached thread to process the queue and exit faster packet callback
    pq = threading.Thread(target=process_queue, args=(queue, args))
    pq.start()

    print(
        f':: Started listening to probe requests on channel {args.channel} on interface {args.interface}'
    )
    print('Hit CTRL-C to exit')
    try:
        sniff(iface=args.interface,
              prn=build_packet_cb(config.IGNORED),
              store=0,
              filter='wlan type mgt subtype probe-req',
              stop_filter=check_event)
    except Scapy_Exception as se:
        print(f'Error: {se}', file=sys.stderr)
        sys.exit(-1)
    except OSError as o:
        print(f"Error: {args.interface} interface not found", file=sys.stderr)
        sys.exit(-1)
    finally:
        event.set()
        pq.join()
示例#18
0
    def run(self, args, cmd):
        self.cmd = cmd

        if args.mac_vendor_lookup:
            self.mac_parser = manuf.MacParser(update=True)

        driver = Graph(args.uri)

        tx = driver.begin()
        self._create_bss_nodes(tx)
        tx.commit()

        tx = driver.begin()
        if args.aggregate_probes:
            self._create_client_aggregated_nodes(tx, args.skip_empty_clients)
        else:
            self._create_client_nodes(tx, args.skip_empty_clients)
        tx.commit()

        cmd.pfeedback("[i] Neo4j dump completed.")
def fetchMacVendor(mac):
    # This function looks up the vendor of a mac address.
    # Returns None if unable to find it
    try:
        from manuf import manuf
    except ImportError:
        raise Exception('''manuf dependency not installed. \
This can be installed by running "pip install manuf"''')
    import os

    if not isValidMacAddress(mac):
        return 'Not a valid mac address'

    if not isMacInCorrectFormat(mac, "00:00:00:00:00:00"):
        mac = change_mac_address_format(mac, "00:00:00:00:00:00")

    p = manuf.MacParser(update=True)
    vendor = p.get_all(mac).manuf
    # delete the downloaded database to cleanup after ourselves
    os.unlink('manuf')
    return vendor
示例#20
0
def get_mac_address_list(ip_address='192.168.1.1',
                         i_range=[1, 255],
                         hide_empty_macs=False,
                         hide_device_names=False) -> list:
    device_parser = manuf.MacParser(update=False)
    mac_address_list = []
    ip_parts = ip_address.split('.')
    get_device_ip()

    for iter in range(i_range[0], i_range[1]):

        current_ip = f'{ip_parts[0]}.{ip_parts[1]}.{ip_parts[2]}.{iter}'

        mac_addr = get_mac_address(ip=current_ip, network_request=True)

        mac_dict = {'ip': current_ip, 'mac': mac_addr, 'device': None}

        if mac_addr != '00:00:00:00:00:00' and mac_addr != None:
            device_name = device_parser.get_manuf_long(str(mac_addr))
            if device_name != None:
                mac_dict['device'] = "Not Available"
                mac_address_list.append(mac_dict)
            elif (hide_device_names != True):
                mac_dict['device'] = "Not available"
                mac_address_list.append(mac_dict)
        elif (hide_empty_macs != True):
            mac_dict['mac'] = "00:00:00:00:00:00"
            mac_dict['device'] = "Not available"
            mac_address_list.append(mac_dict)
        elif (current_ip == get_device_ip()):
            mac_addr = getmac.get_mac_address(
                network_request=False, interface=current_network_interface)
            device_name = device_parser.get_manuf_long(str(mac_addr))
            mac_dict[
                'ip'] = f'{ip_parts[0]}.{ip_parts[1]}.{ip_parts[2]}.{iter}'
            mac_dict['device'] = "Not available"
            mac_dict['mac'] = mac_addr
            mac_address_list.append(mac_dict)
    print('ARP table len: ', len(mac_address_list))
    return mac_address_list
示例#21
0
def macaddressconverter():
    p = manuf.MacParser(update=True)
    cursor.execute(
        """SELECT wlansa from dwccincoming WHERE wlansaconverted IS NULL OR wlansaconverted = '' limit 1;"""
    )
    mactochange = cursor.fetchone()

    print "The mac that will be changed", mactochange
    if mactochange is None:
        print "all MAC matched to vendors"
    else:
        #This below will remove the punctuation for the VAR
        mactochange = ''.join(c for c in mactochange
                              if c not in string.punctuation)
        changedmac = p.get_manuf(mactochange)
        changedmacstr = str(changedmac)
        mactochangestr = str(mactochange)
        #This below will write the mac vendor back to the database
        cursor.execute("UPDATE dwccincoming SET wlansaconverted = " +
                       ` changedmacstr ` + " WHERE wlansa  = " +
                       ` mactochangestr ` + "   ;")
        conn.commit()
        macaddressconverter()
示例#22
0
    def __init__(self):
        super().__init__()

        self.host_list = []
        self.db = QSqlDatabase.addDatabase('QSQLITE')
        if not self.db.isValid():
            print("Error: Invalid database.")

        self.db.setDatabaseName('live_hosts.db')
        if not self.db.open():
            print("Error {}".format(self.db.lastError().text()))
        self.db_table = 'live_hosts'

        self.query = QSqlQuery()
        if not self.query.exec_("DROP TABLE IF EXISTS live_hosts"):
            print(self.query.lastError().text())
        if not self.query.exec_(
                "CREATE TABLE IF NOT EXISTS live_hosts(id INTEGER PRIMARY KEY,"
                "ip_address TEXT NOT NULL UNIQUE, "
                "mac_address TEXT NOT NULL, oui TEXT, status TEXT,"
                "computer_name TEXT, user_text TEXT)"):
            print(self.query.lastError().text())

        self.table_view_model = MySqlTableModel()
        self.table_view_model.setTable(self.db_table)
        self.table_view_model.setHeaderData(1, Qt.Horizontal, "IP Address")
        self.table_view_model.setHeaderData(2, Qt.Horizontal, "MAC Address")
        self.table_view_model.setHeaderData(3, Qt.Horizontal, "Manufacturer")
        self.table_view_model.setHeaderData(4, Qt.Horizontal, "Status")
        self.table_view_model.setHeaderData(5, Qt.Horizontal, "Computer Name")
        self.table_view_model.setHeaderData(6, Qt.Horizontal, "User Text")
        self.table_view_model.select()

        self.proxy_model = CustomSortingModel()
        self.proxy_model.setSourceModel(self.table_view_model)

        self.mac_parser = manuf.MacParser(update=False)
示例#23
0
    def __init__(self, config=None, queue=None):
        self.log = logging.getLogger(inspect.stack()[0][1].split("/")[-1])
        self.log.debug("profiler pid: %s; parent pid: %s", os.getpid(), os.getppid())
        self.analyzed_hash = {}
        self.config = config
        if config:
            self.channel = int(config.get("GENERAL").get("channel"))
            self.ssid = config.get("GENERAL").get("ssid")
            self.files_path = config.get("GENERAL").get("files_path")
            self.pcap_analysis = config.get("GENERAL").get("pcap_analysis")
            self.ft_disabled = config.get("GENERAL").get("ft_disabled")
            self.he_disabled = config.get("GENERAL").get("he_disabled")
            self.reports_dir = os.path.join(self.files_path, "reports")
            self.clients_dir = os.path.join(self.files_path, "clients")
            self.csv_file = os.path.join(
                self.reports_dir, f"profiler-{time.strftime('%Y-%m-%d')}.csv"
            )
        self.client_profiled_count = 0
        self.lookup = manuf.MacParser(update=False)
        self.last_manuf = "N/A"

        if queue:
            while True:
                self.profile(queue)
示例#24
0
 def prepare_mac_parser(self):
     print("\033[H\033[J")
     print(crayons.white("|>>>> Loading vendors from oui.."))
     self._macparser = manuf.MacParser(update=True)
示例#25
0
from sty import fg, bg, ef, rs
import os
from manuf import manuf
import socket
import threading
import time

arp_cache = dict()
hosts = dict()
kill = False

show = [

]

macmanuf = manuf.MacParser()

def prettyprint_QoS(host):

  if len(host['signal']) > 120:
    s0 = host['signal'][-120:]  
  else: 
    s0 = host['signal']

  for s in s0[::-1]:
    qos = int(list(s.values())[0])
    if qos > -70:
      print('█', end='')
    elif qos > -80:
      print('▄', end='')
    elif qos > -90:
示例#26
0
            to_node = Node('manufacturer',
                           manuf_name=to_node_name[0],
                           manuf_comment=to_node_name[1])
    if None in [from_node, to_node]:
        raise Exception('Unknown connection type', connection)
    rel = Relationship(from_node, connection, to_node)
    graph.merge(rel)


def worker(mac_address):
    print(mac_address)
    manuf_data = mac_parser.get_all(mac_address)
    if manuf_data is None or manuf_data.manuf is None:
        return
    register_connection('ETHER/GEN/OUI/MANUFACTURED_BY', mac_address,
                        (manuf_data.manuf, manuf_data.comment))


graph = Graph(
    password='******')  # TODO: parameterize, don't hardcode password
mac_parser = manuf.MacParser(update=True)
if __name__ == '__main__':
    pool = multiprocessing.Pool(multiprocessing.cpu_count())
    manuf.MacParser(update=True)
    macs = [
        _['d.mac_address'] for _ in graph.run(
            'MATCH (d:device) WHERE NOT (d)-[:`ETHER/GEN/OUI/MANUFACTURED_BY`]-() RETURN d.mac_address'
        )
    ]
    pool.map(worker, macs)
示例#27
0
 def __init__(self, xml):
     self.netxml = xmltodict.parse(xml)
     self.networks = {}
     self.manuf = manuf.MacParser(update=True)
示例#28
0
def cpg(graph, stationDict, bssidDict):

    #Add all of the Access Points discovered
    mac = manuf.MacParser(update=MANUF_UPDATE)
    for entry in bssidDict:
        bssid = entry['BSSID']
        essid = entry['ESSID']
        speed = entry['Speed']
        channel = entry['channel']
        auth = entry['Authentication']
        cipher = entry['Cipher']
        lan = entry["LAN IP"].replace(" ", "")
        priv = entry["Privacy"]

        if lan == "0.0.0.0":
            lan = ""

        if len(essid) == 0:
            essid = bssid

        lookup = mac.get_all(bssid)
        if lookup[1] is not None:
            oui = lookup[1]
        else:
            oui = lookup[0]

        if oui is None:
            oui = "Private"

        if "WPA2" in priv:
            b = Node("WPA2",
                     name=essid,
                     bssid=bssid,
                     OUI=oui,
                     Encryption="WPA2",
                     speed=speed,
                     channel=channel,
                     auth=auth,
                     cipher=cipher,
                     lan=lan)
        elif "WPA" in priv:
            b = Node("WPA",
                     name=essid,
                     bssid=bssid,
                     OUI=oui,
                     Encryption="WPA",
                     speed=speed,
                     channel=channel,
                     auth=auth,
                     cipher=cipher,
                     lan=lan)
        elif "WEP" in priv:
            b = Node("WEP",
                     name=essid,
                     bssid=bssid,
                     OUI=oui,
                     Encryption="WEP",
                     speed=speed,
                     channel=channel,
                     auth=auth,
                     cipher=cipher,
                     lan=lan)
        elif "OPN" in priv:
            b = Node("Open",
                     name=essid,
                     bssid=bssid,
                     OUI=oui,
                     Encryption="None",
                     speed=speed,
                     channel=channel,
                     auth=auth,
                     cipher=cipher,
                     lan=lan)
        else:
            b = Node("AP",
                     name=essid,
                     bssid=bssid,
                     OUI=oui,
                     Encryption="None",
                     speed=speed,
                     channel=channel,
                     auth=auth,
                     cipher=cipher,
                     lan=lan)

        graph.create(b)
    #Parse list of clients and add probe relations
    for item in stationDict:
        essids = item['Probed ESSIDs'].split(",")
        station = item['Station MAC']
        fts = item['First time seen']
        lts = item['Last time seen']
        pwr = item['Power']
        pkts = item['# packets']
        if item['BSSID'] != "(not associated)":
            bssid = item['BSSID']
        else:
            bssid = None

        lookup = mac.get_all(station)
        if lookup[1] is not None:
            oui = lookup[1]
        else:
            oui = lookup[0]

        if oui is None:
            oui = "Private"

        s = Node("Client",
                 name=station,
                 FirstTimeSeen=fts,
                 LastTimeSeen=lts,
                 Power=pwr,
                 NumPackets=pkts,
                 Association=bssid,
                 OUI=oui)
        for essid in essids:
            for label in ["AP", "Open", "WEP", "WPA", "WPA2"]:
                existing = graph.nodes.match(label, name=essid).first()
                if existing is not None:
                    break

            if len(essid) > 0:
                if existing is not None:
                    e = existing
                else:
                    e = Node("AP", name=essid)
                se = Relationship(s, "Probes", e)
                graph.create(se)

        # AP Additions per Client
        if bssid is not None:
            # If AP already exists by name, use existing node. Else create new.
            b = None
            for label in ["AP", "Open", "WEP", "WPA", "WPA2"]:
                existing = graph.nodes.match(label, bssid=bssid).first()
                if existing is not None:
                    b = existing
                    break
                else:
                    b = Node("AP", bssid=bssid)

            probeSb = Relationship(s, "Probes", b)
            sb = Relationship(s, "AssociatedTo", b)
            graph.create(sb)
示例#29
0
from flask import Blueprint, request, Flask
from manuf import manuf
import time
import sys

bp = Blueprint("api", __name__, url_prefix="/api")
mp = manuf.MacParser(update=True)
app = Flask(__name__)


@bp.route("/<mac>", methods=[
    "GET",
])
def mac_lookup(mac):
    if request.method == "GET":
        return mp.get_all(mac)


@bp.route("/manufacturer/<mac>", methods=[
    "GET",
])
def mac_lookup_manufacturer(mac):
    if request.method == "GET":
        return mp.get_manuf(mac)


@bp.route("/comment/<mac>", methods=[
    "GET",
])
def mac_lookup_comment(mac):
    if request.method == "GET":
                       nrows=1)
     df5 = pd.read_csv(
         f'{filename}',
         names=colnames,
         skip_blank_lines=True,
         header=None,
         skipinitialspace=0,
         engine='python',
         dtype=str,
         skiprows=5,
         usecols=range(7)).dropna().drop_duplicates("Probed ESSIDs")
     df6 = pd.read_csv(
         f'{filename}', names=colnames, skiprows=14,
         usecols=range(7)).dropna().drop_duplicates("Probed ESSIDs")
     # Set to True, to refresh the MAC address DB
     p = manuf.MacParser(update=False)
 for row, series in df2.iterrows():
     print('\n' * 0)
     print("Wireless Network Name:")
     print(Fore.RED + series["ESSID"])
     print('\n' * 0)
     for row, series in df3.iterrows():
         print("Wireless Network Type:")
         print(Fore.RED + series["Privacy"])
         for row, series in df4.iterrows():
             print('\n' * 0)
             print("Wireless Network Authentication in use:")
             print(Fore.RED + series["Authentication"])
             print('\n' * 0)
             print("Clients on network and corresponding MAC Addresses:")
             print('\n' * 0)