Exemplo n.º 1
0
def main():

	parser = argparse.ArgumentParser(description=DESCRIPTION)
	parser.add_argument('-i', '--interface', help="capture interface")
	parser.add_argument('-t', '--time', default='iso', help="output time format (unix, iso)")
	parser.add_argument('-o', '--output', default='probemon.log', help="logging output location")
	parser.add_argument('-b', '--max-bytes', default=5000000, help="maximum log size in bytes before rotating")
	parser.add_argument('-c', '--max-backups', default=99999, help="maximum number of log files to keep")
	parser.add_argument('-d', '--delimiter', default='\t', help="output field delimiter")
	parser.add_argument('-D', '--debug', action='store_true', help="enable debug output")
	args = parser.parse_args()

	if not args.interface:
		print "error: capture interface not given, try --help"
		sys.exit(-1)
	
	DEBUG = args.debug

	clear = lambda: os.system('cls' if os.name=='nt' else 'clear')
	clear()

	# setup our rotating logger
	logger = logging.getLogger(NAME)
	logger.setLevel(logging.INFO)
	handler = RotatingFileHandler(args.output, maxBytes=args.max_bytes, backupCount=args.max_backups)
	logger.addHandler(handler)
	logger.addHandler(logging.StreamHandler(sys.stdout))
	built_packet_cb = build_packet_callback(args.time, logger, 
		args.delimiter, {}, manuf.MacParser())
	print '\n' + "Time" + '\t\t' + "MAC Addr" + '\t\t' + "Vendor" + '\t\t\t' + "Network" +'\t\t' + "RSSID" + '\t' + "#Data" + '\n'

	sniff(iface=args.interface, prn=built_packet_cb, store=0)
Exemplo n.º 2
0
 def oui(self, frame):
     result = False
     p = manuf.MacParser()
     test = p.get_all(frame.lower())
     if test.manuf is not None:
         print "Real OUI Code"
         result = True
     return result
Exemplo n.º 3
0
 def oui(self, frame):
     result = False
     p = manuf.MacParser()
     test = p.get_all(frame.lower())
     if test.manuf is not None:
         print colored("Real Manufacture OUI Code", "yellow")
         result = True
     return result
Exemplo n.º 4
0
        def PacketHandler(frame):
            if not self.BSSID == frame.addr2:
                print "Same SSID with Different BSSID address"
                p = manuf.MacParser()
                test = p.get_all(frame.addr2)
                if test.manuf is not None:
                    print "real OUI Code"

            if frame.haslayer(
                    Dot11) and frame.type == 0 and frame.subtype == 8:
                try:
                    if frame.info == self.SSID or self.BSSID == frame.addr2:
                        try:

                            print frame.SC
                            self.seq1 = frame.SC
                            self.seq_list.append(frame.SC)
                            self.counter += 1

                            if self.counter == 10:
                                val = self.checkmylist(self.seq_list)
                                self.seq_list = []
                                print "--------------- ", val
                                self.counter = 0

                            ##sig_str = -(256-ord(frame.notdecoded[1]))
                            ##resets when the seqeunece numbers restart at 0 from (65536)
                            ##stops anomolooous detection of Evil Twin
                            #print frame.SC
                            #frame_seq = frame.SC * frame.SC
                            #if frame_seq == 0:
                            #    self.seq2 = 0
                            #    self.seq1 = 0
                            #
                            #    #, " RSSI ", self.parsePacket(frame)#sig_str
                            #if  self.test == 1:
                            #    self.seq1 = frame_seq
                            #
                            #
                            #if  self.test == 2:
                            #    self.seq2 = frame_seq
                            #    self.test = 1
                            #    print "Difference ", ((self.seq2 - self.seq1))
                            #    self.diff = ((self.seq2 - self.seq1))
                            #
                            #self.test = 2
                            #
                            #
                            #if  self.diff > (self.seq2- self.seq1) and self.test == 2:
                            #    print "possible ROUGE AP With Alternbate Sequence Numbers"
                            #    sys.exit()

                            self.accessPointsSQ.append(frame.SC)
                        except Exception, e:
                            print "error", e
                except:
                    pass
Exemplo n.º 5
0
def printBlacklist(wd):
    blacklist = readBlacklist(wd)
    p = manuf.MacParser()
    tableOutput = PrettyTable(
        ['Vendor', 'MAC Address', 'Date Added', 'Comment'])
    for macAddress, dateAdded in blacklist.items():
        tableOutput.add_row([
            p.get_manuf(str(macAddress)), macAddress, dateAdded,
            p.get_comment(str(macAddress))
        ])
    print tableOutput
Exemplo n.º 6
0
def startCSV(csvfile):
    p = manuf.MacParser()
    clientList = []
    clients_list = csv2blob(csvfile)
    for client in clients_list:
        if client[0] != "Station MAC":
            clientList.append([
                p.get_manuf(str(client[0])), client[0], client[3],
                p.get_comment(str(client[0])), client[2]
            ])
    return clientList
Exemplo n.º 7
0
def parse_tracker_data_block(lnk_info, trackerdatablock_off, f):
    # MachineID
    machineid_loc = trackerdatablock_off+12
    machin_id = read_null_term(f,machineid_loc)
    lnk_info['machin_id'] = machin_id
    
    # NewObjectID MAC Address
    macaddress_loc = trackerdatablock_off+54
    macaddress = read_unpack(f,macaddress_loc,6)
    macaddress = splitCount(macaddress,2)
    lnk_info['macaddress'] = macaddress
    
    # MAC vendor
    p = manuf.MacParser() 
    macvendor = p.get_comment(macaddress)
    if macvendor == None:
        macvendor = "(Unknown vendor)"
    lnk_info['macvendor'] = macvendor
    
    # Volume Droid
    volumedroid_loc = trackerdatablock_off+28
    volumedroid = read_unpack(f,volumedroid_loc,16)
    fieldslices = [reverse_hex(volumedroid[0:8]), reverse_hex(volumedroid[8:12]), reverse_hex(volumedroid[12:16]), volumedroid[16:20], volumedroid[20:32]]
    volumedroid = '-'.join(fieldslices)
    lnk_info['volumedroid'] = volumedroid
    
    # Volume Droid Birth
    volumedroid_birth_loc = trackerdatablock_off+60
    volumedroid_birth = read_unpack(f,volumedroid_loc,16)
    fieldslices = [reverse_hex(volumedroid_birth[0:8]), reverse_hex(volumedroid_birth[8:12]), reverse_hex(volumedroid_birth[12:16]), volumedroid_birth[16:20], volumedroid_birth[20:32]]
    volumedroid_birth = '-'.join(fieldslices)
    lnk_info['volumedroid_birth'] = volumedroid_birth
    
    # File Droid
    filedroid_loc = trackerdatablock_off+44
    filedroid = read_unpack(f,filedroid_loc,16)
    fieldslices = [reverse_hex(filedroid[0:8]), reverse_hex(filedroid[8:12]), reverse_hex(filedroid[12:16]), filedroid[16:20], filedroid[20:32]]
    filedroid = '-'.join(fieldslices)
    lnk_info['filedroid'] = filedroid
    
    # Creation time
    filedroid_time = ''.join(fieldslices)
    timestamp = int((filedroid_time[13:16] + filedroid_time[8:12] + filedroid_time[0:8]),16)
    creation = datetime.datetime.fromtimestamp((timestamp - 0x01b21dd213814000L)*100/1e9)
    lnk_info['creation'] = creation
    
    # File Droid Birth
    filedroid_birth_loc = trackerdatablock_off+76
    filedroid_birth = read_unpack(f,filedroid_birth_loc,16)
    fieldslices = [reverse_hex(filedroid_birth[0:8]), reverse_hex(filedroid_birth[8:12]), reverse_hex(filedroid_birth[12:16]), filedroid_birth[16:20], filedroid_birth[20:32]]
    filedroid_birth = '-'.join(fieldslices)
    lnk_info['filedroid_birth'] = filedroid_birth  
  
    return lnk_info
Exemplo n.º 8
0
accessPoints = []
macAP = []

clients = []
macClient = []
uni = 0


Numclients = 0
Numap = 0
Currentloc = 0

NAME = 'Peanuts'
DESCRIPTION = "A New Version of Snoopy-NG, a command line tool for logging 802.11 probe request frames"
whmp = manuf.MacParser()

gpsd = None #seting the global variable

# Console colors
W  = '\033[0m'  # white (normal)
R  = '\033[31m' # red
G  = '\033[32m' # green
O  = '\033[33m' # orange<
B  = '\033[34m' # blue
P  = '\033[35m' # purple
C  = '\033[36m' # cyan
GR = '\033[37m' # gray
T  = '\033[93m' # tan

class GpsPoller(threading.Thread):
Exemplo n.º 9
0
#!/usr/bin/env python

import sys
import sqlite3 as lite
import datetime
import manuf
import time
# from manuf import *
# from colr import color

con = lite.connect('../maclogger.db')
now = int(time.time())
macParser = manuf.MacParser()

maxAge = 10 * 6
maxDevices = 500


def getManuf(mac):
    vendor = macParser.get_all(mac)
    m = vendor.manuf
    c = vendor.comment
    if m is None:
        return "\t"

    if c is None:
        return m

    return m + " (" + c + ")"

Exemplo n.º 10
0
def main():
    global debug

    parser = argparse.ArgumentParser(description=scriptName,
                                     add_help=False,
                                     usage='{} <arguments>'.format(scriptName))
    parser.add_argument('-v',
                        '--verbose',
                        dest='debug',
                        type=str2bool,
                        nargs='?',
                        const=True,
                        default=False,
                        help="Verbose output")
    parser.add_argument(
        '-i',
        '--input',
        required=False,
        dest='input',
        metavar='<STR>',
        type=str,
        default=DEFAULT_MANUF_URL,
        help='Input file or URL',
    )
    parser.add_argument('-o',
                        '--output',
                        required=True,
                        dest='output',
                        metavar='<STR>',
                        type=str,
                        default='',
                        help='Output file')
    try:
        parser.error = parser.exit
        args = parser.parse_args()
    except SystemExit:
        parser.print_help()
        exit(2)

    debug = args.debug
    if debug:
        eprint(os.path.join(scriptPath, scriptName))
        eprint("Arguments: {}".format(sys.argv[1:]))
        eprint("Arguments: {}".format(args))
    else:
        sys.tracebacklimit = 0

    if args.input.lower().startswith('http') and not os.path.isfile(
            args.input):
        tmpf = tempfile.NamedTemporaryFile(delete=True, suffix=".txt")
        r = requests.get(args.input)
        with open(tmpf.name, 'wb') as f:
            f.write(r.content)
        args.input = tmpf.name

    companies = []

    for k, v in manuf.MacParser(manuf_name=args.input)._masks.items():
        macLow = ':'.join('{:02x}'.format(x)
                          for x in (k[1] << k[0]).to_bytes(6, byteorder='big'))
        macHigh = ':'.join(
            '{:02x}'.format(x)
            for x in ((k[1] << k[0]) | (int("ffffffffffff", 16) >> (48 - k[0]))
                      ).to_bytes(6, byteorder='big'))
        companies.append({
            'name': v.manuf_long,
            'low': macLow,
            'high': str(macHigh),
        })

    companies.sort(key=lambda x: (x['low'], x['high']))
    with open(args.output, 'w+') as outfile:
        yaml.dump(companies, outfile, allow_unicode=True)
Exemplo n.º 11
0
def print_scan(nmap_report, fileName, iPRange, hostNet):
    print("Starting Nmap {0} ( http://nmap.org ) at {1}".format(
        nmap_report.version, nmap_report.started))

    #initialize the Excel Workbook
    wb = Workbook()
    ws = wb.active
    ws.title = "Nmap Scan"
    ws['A1'] = "IP"
    ws['B1'] = "Hostname"
    ws['C1'] = "Port/Protocol/Service"
    ws['D1'] = "OS"
    ws['E1'] = "Scan Vendor"
    ws['F1'] = "MAC"
    ws['G1'] = "MAC Vendor"
    ws['H1'] = "Priority/Risk"
    ws['I1'] = "Comments"

    #highlight the top cells
    for j in range(1, 10):
        fillColor = PatternFill("solid", fgColor="2672EC")
        cellStyle = ws.cell(row=1, column=j)
        cellStyle.fill = fillColor

    #Write the IP Addresses and highlight the cells in our DHCP range
    for i in range(iPRange):
        ws.cell(row=(i + 2), column=1, value=hostNet + str(i))
        if i in range(100, 200):
            fill = PatternFill("solid", fgColor="e0a4ea")
            for j in range(2, 10):
                cellStyle = ws.cell(row=(i + 2), column=j)
                cellStyle.fill = fill

    #Walk through the hosts found
    for host in nmap_report.hosts:
        #Set the row to be in line with the Correct Address of scanned host
        for i in range(iPRange):
            if hostNet + str(i) == host.address:
                row = i + 2
                break
        #This is to filter out the IP that do not have a host
        #It should work that if there are any open ports its True and continues or if there was found a MAC address its true
        if host.get_open_ports() or host.mac != '':
            for j in range(2, 10):
                fillColor = PatternFill("solid", fgColor="FFFFFF")
                cellStyle = ws.cell(row=1, column=j)
                cellStyle.fill = fillColor

            #If the host has a hostname add it
            if len(host.hostnames):
                tmp_host = ','.join(host.hostnames)
            else:
                tmp_host = 'None set'

            #Add the hostname if one exists
            ws.cell(row=row, column=2, value=tmp_host)

            #Creates a list of the open ports and services, then converts to string to be able to track for security
            portList = []
            for serv in host.services:
                pserv = "{0:>5s}/{1:3s}/{2}".format(str(serv.port),
                                                    serv.protocol,
                                                    serv.service)
                portList.append(pserv)
            portString = ','.join(portList)
            ws.cell(row=row, column=3, value=portString)

            #Adds the OS if it was able to be found
            if len(host.os_class_probabilities()):
                os = host.os_class_probabilities()
                osEle = str(os[0])
                osList = osEle.split("\n")
                osPos = str(osList[0])
                ws.cell(row=row, column=4, value=osPos)
            else:
                ws.cell(row=row, column=4, value="Unable to detect")

            #If the vendor could be determined by the NMAP adds it
            venCheck = host.vendor
            if not venCheck:
                ws.cell(row=row, column=5, value=str(host.vendor))
            else:
                ws.cell(row=row, column=5, value="Unable to detect")

            #Uses manuf to find the Manufacturer based upon the MAC
            if host.mac != '':
                ws.cell(row=row, column=6, value=str(host.mac))
                macVen = manuf.MacParser()
                ws.cell(row=row, column=7, value=macVen.get_manuf(host.mac))
            else:
                ws.cell(row=row, column=6, value="No MAC")
                ws.cell(row=row, column=7, value="No MAC")

        #If there was no Host found on the IP, then it posts that the Address is open and highlights them
        else:
            ws.cell(row=row, column=2, value='Open Addr')
            for j in range(2, 10):
                fillColor = PatternFill("solid", fgColor="AA9CD2")
                cellStyle = ws.cell(row=1, column=j)
                cellStyle.fill = fillColor

    wb.save(fileName)
    print(nmap_report.summary)
Exemplo n.º 12
0
# Get wirelss ssid and generate a network location from it to distinguish datasets
# First 4 chars of an md5 hexdigest
my_netloc = "0000"
with open('/etc/network/interfaces') as f:
    for l in f:
        if "ssid" in l:
            my_netloc = hashlib.md5(l).hexdigest()[-4:]

# Define our sniffer function for passing to Scapy
# Pkt types below from https://pen-testing.sans.org/blog/2011/10/13/special-request-wireless-client-sniffing-with-scapy
# Further Scapy information can be gleaned from http://www.secdev.org/projects/scapy/demo.html

# Index of MACs from found devices for windowing
mac_index = {}
oui_lookup = manuf.MacParser('/opt/manuf/manuf')

# You can do an interactive session with scapy from the command line on the pi to investigate anomalous devices
# sudo scapy
# conf.oface = "wlan1mon"
# p = sniff(filter="wlan host 64-BC-0C-64-2E-45", count=1)
# p[0].show()


def packet_sniffer(pkt):
    # print(pkt.show())
    ts_now = int(time())
    log_now = False
    # Determine if pkt is of an useful type - we only collect management packets! No data or security info.
    if pkt.haslayer(Dot11):
        if pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp):
Exemplo n.º 13
0
import manuf

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from models import Probe
import config

Base = declarative_base()
engine = create_engine(config.DB_CONNECTION_STRING, echo=True)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

pp = pprint.PrettyPrinter(indent=2)
manuf_parser = manuf.MacParser()
CURRENT_TZ = timezone('Europe/Paris')


def probe_handler(probe):
    manuf_lookup = manuf_parser.get_all(probe['mac'])
    probe['vendor'] = manuf_lookup.manuf_long

    if probe['mac'] not in config.EXCLUDED_MAC and probe[
            'vendor'] not in config.EXCLUDED_VENDORS and manuf_lookup.manuf_long is not None:
        insert_probe(probe)


def capture(iface_name='en1',
            tcpdump_cmd=config.TCPDUMP_COMMAND,
            probe_handler=probe_handler):
Exemplo n.º 14
0
 def setUp(self):
     self.manuf = manuf.MacParser(manuf_name="manuf")
Exemplo n.º 15
0
import subprocess
import json
from values import config
import manuf


def full_path(path):
    path = ''.join([config.CWD, path])
    return path


oui_lookup = manuf.MacParser(manuf_name='/home/pi/conf/manuf')


def shell(command, isJson=False):
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()

    if error:
        return False

    if json:
        output = json.loads(output)

    return output


def get_manuf(mac):
    return oui_lookup.get_manuf(mac)