Example #1
0
def monkeyForm(request):
    if request.method == 'POST':
        form = addMonkey(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            options = {}
            options['CLI'] = 'false'
            options['eraseMonkeyData'] = 'false'
            try:
                dbInfo = monkeyDBInfo.objects.get()
                options['dbip'] = dbInfo.IP
                options['dbname'] = dbInfo.Name
                db = openMDB(options['dbip'], options['dbname'])
                if db is not None:
                    smclient.loadMonkeys(options, db, {0: int(cd['iq'])},
                                         {0: int(cd['type'])}, {0: cd['loc']},
                                         {0: cd['ip']}, {0: cd['minbytes']},
                                         {0: cd['maxbytes']})
            except monkeyDBInfo.DoesNotExist:
                #error
                print 'monkey db info does not exist'
        return HttpResponseRedirect('/monkeys')
    else:
        if (request.GET.get('btnStart')):
            options = getDBOptions()
            db = openMDB(options['dbip'], options['dbname'])
            options['runTime'] = request.GET.get('duration')
            if db is not None:
                smclient.startMonkeysParam(options, db)
        form = addMonkey()
    return render(request, 'monkeys.html', {'form': form})
Example #2
0
def monkeyForm(request):
	if request.method =='POST':
		form = addMonkey(request.POST)
		if form.is_valid():
			cd=form.cleaned_data
			options={}
			options['CLI']='false'
			options['eraseMonkeyData']='false'
			try:
				dbInfo=monkeyDBInfo.objects.get()
				options['dbip']=dbInfo.IP
				options['dbname']=dbInfo.Name
				db=openMDB(options['dbip'],options['dbname'])
				if db is not None:
					smclient.loadMonkeys(options,db,{0:int(cd['iq'])},{0:int(cd['type'])},{0:cd['loc']},{0:cd['ip']},{0:cd['minbytes']},{0:cd['maxbytes']})
			except monkeyDBInfo.DoesNotExist:
				#error
				print 'monkey db info does not exist'
		return HttpResponseRedirect('/monkeys')
	else:
		if(request.GET.get('btnStart')):
			options=getDBOptions()
			db=openMDB(options['dbip'],options['dbname'])
			options['runTime']=request.GET.get('duration')
			if db is not None:
				smclient.startMonkeysParam(options,db)
		form=addMonkey()
	return render(request,'monkeys.html',{'form':form})
Example #3
0
def fuzzPorts(runTime, dbIp, dbName, monkeyIq, monkeyLoc, minData, maxData,
              monkeyId):
    timeout = time.time() + 60 * runTime

    while True:
        hostList = {}  #reinit each time through
        time.sleep(1)

        if time.time() > timeout:
            break

        db = openMDB(dbIp, dbName)
        if db is None:
            print 'Could not connect to DB'

        hosts = db.hosts

        if hosts.find({'location': monkeyLoc}).count() == 0:
            print 'Fuzzy monkey is waiting for work.  Eating bananas.  Will check again in 10 seconds.'
            time.sleep(10)

        else:
            for work in hosts.find({'location': monkeyLoc}):
                #Start priority calculation
                decisionCalc = (int(monkeyIq) * int(
                    db.targets.find_one({'ip': work['ip']})['value'])) / (
                        db.actions.find({
                            'ip': work['ip']
                        }).count() + 1) + randint(1, 10)
                hostList.update({work['ip']: decisionCalc})

            target = max(hostList, key=hostList.get)
            openPorts = db.hosts.find_one({'ip': target})['ports']
            fuzzTCP = openPorts[randint(0, len(openPorts) - 1)]

            fuzzData = genFuzzData(randint(int(minData), int(maxData)))
            print 'Fuzzy monkey got work! Fuzzing ' + target + ' on port ' + str(
                fuzzTCP) + ' with ' + str(getsizeof(fuzzData) -
                                          37) + ' bytes of data!'

            start = time.ctime()

            try:
                s = socket(AF_INET, SOCK_STREAM)
                s.settimeout(10)
                s.connect((target, fuzzTCP))
                s.send(fuzzData)
                result = s.recv(100)  #Don't care what we get back.
                s.close()

            except:
                #Handle TCP resets and other aggressive network traffic semi gracefully
                pass

            end = time.ctime()
            saveResults(db, hosts, target, fuzzTCP,
                        str(getsizeof(fuzzData) - 37), start, end, monkeyId)
            print 'Fuzzy monkey need sleep.  Resting for 5 seconds.'
            time.sleep(5)
Example #4
0
def basicInfoForm(request):
    if request.method == 'POST':
        if 'submit_Monkey' in request.POST:
            form = basicInfo(request.POST, request.FILES)
        else:
            form = metasploitDBInfo(request.POST)
        if form.is_valid() and 'submit_Monkey' in request.POST:
            cd = form.cleaned_data
            options = {}
            options['dbip'] = cd['IP']
            options['dbname'] = cd['Name']
            options['eraseTargetsData'] = str(cd["targetErase"]).lower()
            options['CLI'] = 'false'
            db = openMDB(options['dbip'], options['dbname'])

            if 'file' in request.FILES and db is not None:
                smclient.loadTargetsParam(options, request.FILES['file'], db)
            form.save()
            return HttpResponseRedirect('/client')
        elif form.is_valid() and 'submit_Metasploit' in request.POST:
            cd = form.cleaned_data
            options = {}
            options['CLI'] = 'false'
            dbConfig = monkeyDBInfo.objects.get()
            options['dbip'] = dbConfig.IP
            options['dbname'] = dbConfig.Name
            options['eraseSploitData'] = str(cd['metErase']).lower()
            smclient.dbLoadModules(options, cd['IP'], cd['username'],
                                   cd['password'], cd['Name'])
            form.save()
            return HttpResponseRedirect('/client')
        else:
            print form.errors
            return HttpResponseRedirect('/client?e=1')

        #dostuff


#insert redirect
#return HttpResponseRedirect('/client')
    else:

        try:
            form = basicInfo(instance=monkeyDBInfo.objects.get())
        except monkeyDBInfo.DoesNotExist:
            form = basicInfo()
        try:
            metaForm = metasploitDBInfo(instance=metasploitInfo.objects.get())
        except metasploitInfo.DoesNotExist:
            metaForm = metasploitDBInfo()
    args = {}
    args.update(csrf(request))
    args['form'] = form
    args['metaForm'] = metaForm
    if (request.GET.get('e')):
        args['error'] = request.GET.get('e')
    return render_to_response('client.html', args)
Example #5
0
def findLoginBoxes(runTime, dbIp, dbName, monkeyIq, monkeyLoc, monkeyId):
    timeout = time.time() + 60 * runTime

    while True:
        hostList = {}
        ports = []
        time.sleep(1)

        if time.time() > timeout:
            break

        db = openMDB(dbIp, dbName)
        if db is None:
            print "Could not connect to db"
        hosts = db.hosts

        if hosts.find({"location": monkeyLoc}).count() == 0:
            print "Brute monkey is waiting for work.  Eating bananas.  Will check again in 10 seconds."
            time.sleep(10)

        else:
            for work in hosts.find({"location": monkeyLoc}):

                if 21 in work["ports"] or 22 in work["ports"] or 23 in work["ports"]:
                    decisionCalc = (int(monkeyIq) * int(db.targets.find_one({"ip": work["ip"]})["value"])) / (
                        db.actions.find({"ip": work["ip"]}).count() + 1
                    ) + randint(1, 10)
                    hostList.update({work["ip"]: decisionCalc})

            if len(hostList) > 0:
                target = max(hostList, key=hostList.get)
                openPorts = db.hosts.find_one({"ip": target})["ports"]

                if 21 in openPorts:
                    ports.append(21)

                if 22 in openPorts:
                    ports.append(22)

                # if 23 in openPorts:
                #    ports.append(23)

        if len(ports) == 0:
            print "Brute monkey is waiting for something to brute force.  Eating bananas.  Will check again in 10 seconds."
            time.sleep(10)

        else:
            print "Brute monkey got work! Starting credential brute forcing!"
            index = randint(0, len(ports) - 1)

            if ports[index] == 21:
                ftpBrute(target, db, hosts, monkeyId)

            elif ports[index] == 22:
                sshBrute(target, db, hosts, monkeyId)
Example #6
0
def basicInfoForm(request):
	if request.method == 'POST':
		if 'submit_Monkey' in request.POST:
			form = basicInfo(request.POST,request.FILES)
		else:
			form = metasploitDBInfo(request.POST)
		if form.is_valid() and 'submit_Monkey' in request.POST:
			cd=form.cleaned_data
			options={}
			options['dbip'] = cd['IP']
			options['dbname'] = cd['Name']
			options['eraseTargetsData']=str(cd["targetErase"]).lower()
			options['CLI']='false'
			db=openMDB(options['dbip'],options['dbname'])
			

			if 'file' in request.FILES and db is not None:
				smclient.loadTargetsParam(options,request.FILES['file'],db)
			form.save()
			return HttpResponseRedirect('/client')
		elif form.is_valid() and 'submit_Metasploit' in request.POST:
			cd=form.cleaned_data
			options={}
			options['CLI']='false'
			dbConfig=monkeyDBInfo.objects.get()
			options['dbip']=dbConfig.IP
			options['dbname']=dbConfig.Name
			options['eraseSploitData']=str(cd['metErase']).lower()
			smclient.dbLoadModules(options,cd['IP'],cd['username'],cd['password'],cd['Name'])
			form.save()
			return HttpResponseRedirect('/client')
		else:
			print form.errors
			return HttpResponseRedirect('/client?e=1')

		#dostuff
#insert redirect
		#return HttpResponseRedirect('/client')
	else:
			
		try:
			form=basicInfo(instance=monkeyDBInfo.objects.get())
		except monkeyDBInfo.DoesNotExist:
			form=basicInfo()
		try:
			metaForm=metasploitDBInfo(instance=metasploitInfo.objects.get())
		except metasploitInfo.DoesNotExist:
			metaForm=metasploitDBInfo()	
	args={}
	args.update(csrf(request))
	args['form']=form
	args['metaForm']=metaForm
	if(request.GET.get('e')):
		args['error']=request.GET.get('e')
	return render_to_response('client.html',args)
Example #7
0
def findLoginBoxes(runTime,dbIp,dbName,monkeyIq,monkeyLoc,monkeyId):
    timeout = time.time() + 60 * runTime

    while True:
        hostList = {}
        ports = []
        time.sleep(1)

        if time.time() > timeout:
            break

        db = openMDB(dbIp,dbName)
        if db is None:
            print 'Could not connect to db'
        hosts = db.hosts


        if hosts.find({'location':monkeyLoc}).count() == 0:
            print 'Brute monkey is waiting for work.  Eating bananas.  Will check again in 10 seconds.'
            time.sleep(10)

        else:
            for work in hosts.find({'location':monkeyLoc}):

                if 21 in work['ports'] or 22 in work['ports'] or 23 in work['ports']:
                    decisionCalc = ( int(monkeyIq) * int(db.targets.find_one({'ip' : work['ip']})['value']))/(db.actions.find({'ip' : work['ip'] }).count() + 1 ) + randint(1,10)
                    hostList.update( {work['ip'] : decisionCalc } )

            if len(hostList) > 0:
                    target = max(hostList,key=hostList.get)
                    openPorts = db.hosts.find_one({'ip' : target})['ports']

                    if 21 in openPorts:
                        ports.append(21)

                    if 22 in openPorts:
                        ports.append(22)

                    #if 23 in openPorts:
                    #    ports.append(23)


        if len(ports) == 0:
            print 'Brute monkey is waiting for something to brute force.  Eating bananas.  Will check again in 10 seconds.'
            time.sleep(10)

        else:
            print 'Brute monkey got work! Starting credential brute forcing!'
            index = randint(0,len(ports)-1)

            if ports[index] == 21:
                ftpBrute(target,db,hosts,monkeyId)

            elif ports[index] == 22:
                sshBrute(target,db,hosts,monkeyId)
Example #8
0
def scanHosts(runTime, dbIp, dbName, monkeyIq, monkeyLoc, monkeyId):
    timeout = time.time() + 60 * runTime

    while True:
        time.sleep(1)

        hostList = {}  # reinit each time through loop to get new hosts from other clients possibly.
        openPorts = []  # reinit each time through loop

        if time.time() > timeout:
            break

        db = openMDB(dbIp, dbName)
        if db is None:
            print "could not connect to db"

        for host in db.targets.find({"location": monkeyLoc}):
            # Start priority calculation
            decisionCalc = (int(monkeyIq) * int(host["value"])) / (
                db.actions.find({"ip": host["ip"]}).count() + 1
            ) + randint(1, 10)
            hostList.update({host["ip"]: decisionCalc})

        # Find highest decision calculation
        target = max(hostList, key=hostList.get)

        start = time.ctime()
        print "Starting port scan of " + target
        nm = nmap.PortScanner()

        if int(monkeyIq) == 0:  # Almost as smart as Gregory Evans
            nm.scan(target)

        elif int(monkeyIq) == 1:  # Level 1 monkeys aren't foiled by ICMP being blocked to the host
            nm.scan(target, arguments="-P0 -A")

        elif int(monkeyIq) == 2:  # Level 2 monkeys run full connect scans to be a bit more stealthy
            nm.scan(target, arguments="-P0 -sT -A")

        elif int(monkeyIq) == 3:  # Level 3 monkeys include decoy IPs in their scans
            nm.scan(target, arguments="-P0,-sT,-A,-D4.2.2.2,8.8.8.8,172.1.2.4,3.4.2.1")

        end = time.ctime()
        print "Scan monkey finished scan of " + target + " at " + end

        if len(nm.all_hosts()) != 0:
            for port in nm[nm.all_hosts()[0]]["tcp"].keys():
                if nm[nm.all_hosts()[0]]["tcp"][port]["state"] == "open":
                    openPorts.append(port)

            if len(openPorts) != 0:
                saveResults(nm.all_hosts()[0], openPorts, dbName, start, end, db, monkeyId, monkeyLoc)

    print "Monkey shift is over."
    return
Example #9
0
def monkeyReport():
    global options
    db = openMDB(options['dbip'], options['dbname'])
    if db is None:
        print 'Could not connect to db'
    print 'Monkeys clocking out'
    print '===================='

    validTypes = [1, 2]
    print 'Select format for output:'
    print '1-CSV'
    outType = int(raw_input('Input: '))

    if outType not in validTypes:
        raw_input('Invalid output selection.  Press enter to return.')

    else:
        savePath = raw_input('Enter file name to save: ')

        fo = open(savePath, 'wb')

        if outType == 1:  #Write CSV header row
            fo.write(
                'action,attacker,target,starttime,endtime,fuzzport,fuzzbytes,\n'
            )

        for event in db.actions.find():  # loop through events
            if outType == 1:
                if event['action'] == 'fuzz':
                    fo.write(
                        str(event['action']) + ',' +
                        str(db.monkeys.find_one({'id': event['id']})['ip']) +
                        ',' + str(event['ip']) + ',' + str(event['start']) +
                        ',' + str(event['end']) + ',' + str(event['port']) +
                        ',' + str(event['bytes']) + '\n')

                elif event['action'] != 'portscan' and event[
                        'action'] != 'fuzz':
                    fo.write(
                        str(event['action']) + ',' +
                        str(db.monkeys.find_one({'id': event['id']})['ip']) +
                        ',' + str(event['ip']) + ',' + str(event['start']) +
                        ',' + str(event['end']) + ',' + str(event['port']) +
                        ',NA\n')

                else:
                    fo.write(
                        str(event['action']) + ',' +
                        str(db.monkeys.find_one({'id': event['id']})['ip']) +
                        ',' + str(event['ip']) + ',' + str(event['start']) +
                        ',' + str(event['end']) + ',' + 'NA,NA\n')

        raw_input('\nAll done! Press enter to return to the main menu.')
        return
Example #10
0
def scanHosts(runTime,dbIp,dbName,monkeyIq,monkeyLoc,monkeyId):
    timeout = time.time() + 60 * runTime
    
    while True:
        time.sleep(1)

        hostList = {} #reinit each time through loop to get new hosts from other clients possibly.
        openPorts = [] #reinit each time through loop

        if time.time() > timeout:
            break

        db = openMDB(dbIp,dbName)
        if db is None:
            print 'could not connect to db'


        for host in db.targets.find({'location':monkeyLoc}):
            #Start priority calculation
            decisionCalc = ( int(monkeyIq) * int(host['value']) )/(db.actions.find({'ip' : host['ip'] }).count() + 1 ) + randint(1,10)
            hostList.update( {host['ip'] : decisionCalc } )

        #Find highest decision calculation
        target = max(hostList,key=hostList.get)

        start = time.ctime()
        print 'Starting port scan of ' + target
        nm = nmap.PortScanner()

        if int(monkeyIq) == 0: #Almost as smart as Gregory Evans
            nm.scan(target)

        elif int(monkeyIq) == 1: #Level 1 monkeys aren't foiled by ICMP being blocked to the host
            nm.scan(target,arguments='-P0 -A')

        elif int(monkeyIq) == 2: #Level 2 monkeys run full connect scans to be a bit more stealthy
            nm.scan(target,arguments='-P0 -sT -A')

        elif int(monkeyIq) == 3: #Level 3 monkeys include decoy IPs in their scans
            nm.scan(target,arguments='-P0,-sT,-A,-D4.2.2.2,8.8.8.8,172.1.2.4,3.4.2.1')

        end = time.ctime()
        print 'Scan monkey finished scan of ' + target +  ' at ' + end
        
        if len( nm.all_hosts() ) != 0:
            for port in nm[nm.all_hosts()[0]]['tcp'].keys():
                if nm[nm.all_hosts()[0]]['tcp'][port]['state'] == 'open':
                    openPorts.append(port)
             
            if len(openPorts) != 0:        
                saveResults(nm.all_hosts()[0],openPorts,dbName,start,end,db,monkeyId,monkeyLoc)

    print 'Monkey shift is over.'
    return
Example #11
0
def fuzzPorts(runTime,dbIp,dbName,monkeyIq,monkeyLoc,minData,maxData,monkeyId):
    timeout = time.time() + 60 * runTime

    while True:
        hostList = {} #reinit each time through
        time.sleep(1)

        
        if time.time() > timeout:
            break

        db = openMDB(dbIp,dbName)
        if db is None:
            print 'Could not connect to DB'

        hosts = db.hosts
        
        if hosts.find({'location':monkeyLoc}).count() == 0:
            print 'Fuzzy monkey is waiting for work.  Eating bananas.  Will check again in 10 seconds.'
            time.sleep(10)
        
        else:
            for work in hosts.find({'location':monkeyLoc}):
                #Start priority calculation
                decisionCalc = ( int(monkeyIq) * int(db.targets.find_one({'ip' : work['ip']})['value']))/(db.actions.find({'ip' : work['ip'] }).count() + 1 ) + randint(1,10)
                hostList.update( {work['ip'] : decisionCalc } )

            target = max(hostList,key=hostList.get)
            openPorts = db.hosts.find_one({'ip' : target})['ports']
            fuzzTCP = openPorts[randint(0,len(openPorts)-1)]
            
            fuzzData = genFuzzData(randint(int(minData),int(maxData)))
            print 'Fuzzy monkey got work! Fuzzing ' + target + ' on port ' + str(fuzzTCP) + ' with ' + str(getsizeof(fuzzData)-37) + ' bytes of data!'
            
            start = time.ctime()


            try:
                s = socket(AF_INET, SOCK_STREAM)
                s.settimeout(10)
                s.connect((target, fuzzTCP))
                s.send(fuzzData)
                result = s.recv(100) #Don't care what we get back.
                s.close()

            except:
                #Handle TCP resets and other aggressive network traffic semi gracefully
                pass

            end = time.ctime()
            saveResults(db,hosts,target,fuzzTCP,str(getsizeof(fuzzData)-37),start,end,monkeyId)
            print 'Fuzzy monkey need sleep.  Resting for 5 seconds.'
            time.sleep(5)
Example #12
0
def findWebBoxes(runTime, dbIp, dbName, monkeyIq, monkeyLoc, monkeyId):
    timeout = time.time() + 60 * runTime

    while True:
        hostList = {
        }  #reinit variables each time through to account for new scanner data
        ports = []
        time.sleep(1)

        if time.time() > timeout:
            break

        db = openMDB(dbIp, dbName)
        if db is None:
            print 'could not connect to db'

        hosts = db.hosts

        if hosts.find({'location': monkeyLoc}).count() == 0:
            print 'Web monkey is waiting for work.  Eating bananas.  Will check again in 10 seconds.'
            time.sleep(10)

        else:
            for work in hosts.find({'location': monkeyLoc}):
                if 80 in work['ports'] or 443 in work['ports']:
                    decisionCalc = (int(monkeyIq) * int(
                        db.targets.find_one({'ip': work['ip']})['value'])) / (
                            db.actions.find({
                                'ip': work['ip']
                            }).count() + 1) + randint(1, 10)
                    hostList.update({work['ip']: decisionCalc})

            if len(hostList) > 0:
                target = max(hostList, key=hostList.get)
                openPorts = db.hosts.find_one({'ip': target})['ports']

            if 80 in openPorts:
                ports.append(80)

            if 443 in openPorts:
                ports.append(443)

        if len(ports) == 0:
            print 'Web monkey is waiting for a web server.  Eating bananas.  Will check again in 10 seconds.'
            time.sleep(10)

        else:
            print 'Web monkey got work! Starting directory brute forcing!'
            index = randint(0, len(ports) - 1)
            port = ports[index]
            webBrute(target, port, db, hosts, monkeyId)
Example #13
0
def resultsForm(request):
    if request.method == 'POST':

        return HttpResponseRedirect('/results')
    else:
        options = getDBOptions()
        db = openMDB(options['dbip'], options['dbname'])
        if db is not None:
            actions = {}
            columnOrder = [
                'action', 'monkeyIP', 'targetIP', 'port', 'start', 'end',
                'bytes'
            ]
            columns = {
                'action': 'Action Taken',
                'targetIP': 'Target IP',
                'port': 'Port',
                'monkeyIP': 'Monkey IP',
                'start': 'Start Time',
                'end': 'End Time',
                'bytes': 'Bytes Sent'
            }
            count = 0
            for event in db.actions.find():
                monkey = db.monkeys.find_one({'id': event['id']})
                action = {}
                action['action'] = event['action']
                action['monkeyIP'] = str(monkey['ip'])
                action['targetIP'] = event['ip']
                action['start'] = event['start']
                action['end'] = event['end']
                if event['action'] == 'fuzz':
                    action['port'] = event['port']
                    action['bytes'] = event['bytes']
                elif event['action'] == 'portscan':
                    action['port'] = 'N/A'
                    action['bytes'] = 'N/A'
                else:
                    action['port'] = event['port']
                    action['bytes'] = 'N/A'
                actions[count] = action
                count = count + 1

            return render_to_response('results.html', {
                'actions': actions,
                'columns': columns,
                'order': columnOrder
            })
        else:
            return render_to_response('results.html')
Example #14
0
def dbLoadModules(options, msfDbIp, msfDbUser, msfDbPass, msfDbName):
    try:
        pgConn = psycopg2.connect(database=msfDbName, host=msfDbIp, user=msfDbUser, password=msfDbPass)
        cur = pgConn.cursor()
        cur.execute('SELECT file,fullname FROM module_details;')
        mongoDb = openMDB(options['dbip'],options['dbname'])
        if mongoDb is None:
            print 'I am error'
        if 'logins' in mongoDb.collection_names() or 'sploits' in mongoDb.collection_names():
            if (options['CLI'] == 'true' and raw_input('Previous exploit data found.  Erase? ').lower() == 'y') or (
                            options['CLI'] == 'false' and options['eraseSploitData'] == 'true'):
                if 'logins' in mongoDb.collection_names():
                    mongoDb['logins'].drop()

                if 'sploits' in mongoDb.collection_names():
                    mongoDb['sploits'].drop()

        print 'Opening exploits and getting default port numbers...'
        for sploit in cur:
            f = open(sploit[0], "r")
            portSearch = f.readlines()
            f.close()

            for line in portSearch:
                if "Opt::RPORT" in line:

                    try:
                        regex = '.*\((.*?)\).*'
                        matches = re.search(regex, line)

                        if matches.group(1).isdigit():
                            if 'auxiliary' in sploit[1] and 'scanner' in sploit[1] and '_login' in sploit[1]:
                                #If the logic evaluates to True, this is a login module
                                mongoDb.logins.insert({'modName': sploit[1], 'port': matches.group(1)})

                            elif 'exploit' in sploit[1]:
                                #This is an exploit module
                                mongoDb.sploits.insert({'modName': sploit[1], 'port': matches.group(1)})

                        else:
                            continue

                    except:
                        pass

    except Exception, e:
        if options['CLI'] == 'true':
            raw_input('Data not imported.  Check your MongoDB and Postgres settings. ')
        return
Example #15
0
def findWebBoxes (runTime,dbIp,dbName,monkeyIq,monkeyLoc,monkeyId):
    timeout = time.time() + 60 * runTime

    while True:
        hostList = {} #reinit variables each time through to account for new scanner data
        ports = []
        time.sleep(1)

        if time.time() > timeout:
            break

        db = openMDB(dbIp, dbName)
        if db is None:
            print 'could not connect to db'



        hosts = db.hosts

        if hosts.find({'location':monkeyLoc}).count() == 0:
            print 'Web monkey is waiting for work.  Eating bananas.  Will check again in 10 seconds.'
            time.sleep(10)

        else:
            for work in hosts.find({'location':monkeyLoc}):
                if 80 in work['ports'] or 443 in work['ports']:
                    decisionCalc = ( int(monkeyIq) * int(db.targets.find_one({'ip' : work['ip']})['value']))/(db.actions.find({'ip' : work['ip'] }).count() + 1 ) + randint(1,10)
                    hostList.update( {work['ip'] : decisionCalc } )

            if len(hostList) > 0:
                target = max(hostList,key=hostList.get)
                openPorts = db.hosts.find_one({'ip' : target})['ports']

            if 80 in openPorts:
                ports.append(80)

            if 443 in openPorts:
                ports.append(443)

        if len(ports) == 0:
            print 'Web monkey is waiting for a web server.  Eating bananas.  Will check again in 10 seconds.'
            time.sleep(10)

        else:
            print 'Web monkey got work! Starting directory brute forcing!'
            index = randint(0,len(ports)-1)
            port = ports[index]
            webBrute (target,port,db,hosts,monkeyId)
Example #16
0
def loadTargets():
    global options
    db = openMDB(options['dbip'], options['dbname'])
    if db is None:
        print 'Could not connect to DB'
    if 'targets' in db.collection_names():
        if raw_input('Remove current list of targets? ').lower() == 'y':
            db['targets'].drop()

    else:
        print 'No targets found in database.'

    fileName = raw_input('Enter path to targets file: ')

    loadTargetsParam(options, fileName, db)
    raw_input('targets loaded! press enter to return to main menu.')
    return
Example #17
0
def loadTargets():
    global options
    db = openMDB(options['dbip'],options['dbname'])
    if db is None:
        print 'Could not connect to DB'
    if 'targets' in db.collection_names():
        if raw_input('Remove current list of targets? ').lower() == 'y':
            db['targets'].drop()

    else:
        print 'No targets found in database.'

    fileName = raw_input('Enter path to targets file: ')

    loadTargetsParam(options, fileName, db)
    raw_input('targets loaded! press enter to return to main menu.')
    return
Example #18
0
def startMonkeys():
    global options
    db = openMDB(options['dbip'], options['dbname'])
    if db is None:
        print 'Could not connect to db'
    if 'actions' in db.collection_names() or 'hosts' in db.collection_names():
        if raw_input('Previous monkey attacks found.  Erase? ').lower() == 'y':
            db['actions'].drop()
            db['hosts'].drop()


    options['runTime'] = raw_input('How many minutes should the monkeys be loose? ')
    startMonkeysParam(options, db)

    print 'Fly my pretties, fly!'
    timeout = time.time() + 60 * int(options['runTime'])

    while True:
        if time.time() > timeout:
            raw_input('End of the day! Punching out. Check servers to make sure all work is done.\nPress enter to return to the main menu.')
            break
Example #19
0
def monkeyReport():
    global options
    db = openMDB(options['dbip'], options['dbname'])
    if db is None:
        print 'Could not connect to db'
    print 'Monkeys clocking out'
    print '===================='

    validTypes = [1, 2]
    print 'Select format for output:'
    print '1-CSV'
    outType = int(raw_input('Input: '))

    if outType not in validTypes:
        raw_input('Invalid output selection.  Press enter to return.')

    else:
        savePath = raw_input('Enter file name to save: ')


        fo = open(savePath, 'wb')

        if outType == 1:  #Write CSV header row
            fo.write('action,attacker,target,starttime,endtime,fuzzport,fuzzbytes,\n')

        for event in db.actions.find(): # loop through events
            if outType == 1:
                if event['action'] == 'fuzz':
                    fo.write(str(event['action'])+','+ str(db.monkeys.find_one({'id' : event['id']})['ip']) +','+str(event['ip'])+','+str(event['start'])+','+str(event['end'])+ ',' + str(event['port']) + ',' + str(event['bytes']) +'\n')

                elif event['action'] != 'portscan'  and event['action'] != 'fuzz':
                    fo.write(str(event['action'])+','+ str(db.monkeys.find_one({'id' : event['id']})['ip']) +','+str(event['ip'])+','+str(event['start'])+','+str(event['end'])+ ',' + str(event['port']) + ',NA\n')

                else:
                     fo.write(str(event['action'])+','+ str(db.monkeys.find_one({'id' : event['id']})['ip']) +','+str(event['ip'])+','+str(event['start'])+','+str(event['end'])+ ',' + 'NA,NA\n')

        raw_input('\nAll done! Press enter to return to the main menu.')
        return
Example #20
0
def startMonkeys():
    global options
    db = openMDB(options['dbip'], options['dbname'])
    if db is None:
        print 'Could not connect to db'
    if 'actions' in db.collection_names() or 'hosts' in db.collection_names():
        if raw_input('Previous monkey attacks found.  Erase? ').lower() == 'y':
            db['actions'].drop()
            db['hosts'].drop()

    options['runTime'] = raw_input(
        'How many minutes should the monkeys be loose? ')
    startMonkeysParam(options, db)

    print 'Fly my pretties, fly!'
    timeout = time.time() + 60 * int(options['runTime'])

    while True:
        if time.time() > timeout:
            raw_input(
                'End of the day! Punching out. Check servers to make sure all work is done.\nPress enter to return to the main menu.'
            )
            break
Example #21
0
def resultsForm(request):
	if request.method =='POST':
		
		return HttpResponseRedirect('/results')
	else:
		options=getDBOptions()
		db=openMDB(options['dbip'],options['dbname'])
		if db is not None:
			actions={}
			columnOrder=['action','monkeyIP','targetIP','port','start','end','bytes']
			columns={'action':'Action Taken','targetIP':'Target IP','port':'Port','monkeyIP':'Monkey IP','start':'Start Time','end':'End Time','bytes':'Bytes Sent'}
			count=0
                	for event in db.actions.find():
				monkey=db.monkeys.find_one({'id' : event['id']})
				action={}
				action['action']=event['action']
				action['monkeyIP']=str(monkey['ip'])
				action['targetIP']=event['ip']
				action['start']=event['start']
				action['end']=event['end']
				if event['action']=='fuzz':
					action['port']=event['port']
					action['bytes']=event['bytes']
				elif event['action']=='portscan':
					action['port']='N/A'
					action['bytes']='N/A'
				else:
					action['port']=event['port']
					action['bytes']='N/A'
				actions[count]=action
				count=count+1

	
			return render_to_response('results.html', {'actions': actions,'columns':columns,'order':columnOrder})
		else:
			return render_to_response('results.html')
Example #22
0
def makeMonkeys():
    global options
    global monkeyIds
    monkeyTypes = [
        None, 'Scan Monkey', None, 'Fuzzy Monkey', None, 'Web Monkey'
    ]
    dropSel = True
    existing = []
    print 'Monkey setup'
    print '------------'
    db = openMDB(options['dbip'], options['dbname'])
    if db is None:
        print 'Could not connect to database'
    if 'monkeys' in db.collection_names():
        if raw_input('Existing monkeys found.  Remove? ').lower() == 'y':
            count = 1

            for monkey in db.monkeys.find():
                print str(count) + '-' + str(
                    monkey['ip']) + '-' + monkeyTypes[int(monkey['type'])]
                existing.append(monkey['id'])
                count += 1

            while dropSel == True:
                dropSel = raw_input(
                    'Enter monkey to remove,e to remove all monkeys, or q to make monkeys: '
                )

                if dropSel.lower() == 'e':
                    db['monkeys'].drop()
                    print 'Monkeys removed!'

                elif dropSel.lower() == 'q':
                    dropSel = False

                else:
                    db.monkeys.remove({'id': existing[int(dropSel) - 1]})
                    dropSel = True

        else:
            #Get the IDs of the existing monkeys to avoid dupes
            for monkey in db.monkeys.find():
                monkeyIds.append(monkey['id'])

    else:
        print 'No monkeys found in database.'

    numMonkeys = int(raw_input('Enter total number of monkeys to create: '))
    validIQs = [0, 1, 2, 3]
    validTypes = [1, 2, 3, 4, 5]
    validLocs = ['i', 'e']

    monkeyIQ = {}
    monkeyType = {}
    monkeyLoc = {}
    monkeyIp = {}
    minFuzzSize = {}
    maxFuzzSize = {}

    for i in range(1, numMonkeys + 1):
        monkeyIQ[i] = None
        monkeyType[i] = None
        monkeyLoc[i] = None
        print 'Setting up monkey #' + str(i)

        while monkeyIQ[i] not in validIQs:
            print '---------------------'
            print 'Enter Monkey IQ:'
            print '0-World\'s #1 Hacker'
            print '1-CISSP'
            print '2-CEH'
            print '3-Security Weekly Listener'
            monkeyIQ[i] = int(raw_input('Input: '))

        print "\n"

        while monkeyType[i] not in validTypes:
            print 'Define Monkey Type:'
            print '1-Scanner Monkey'
            print '2-Exploit Monkey'
            print '3-Fuzzy Monkey'
            print '4-Brute Monkey'
            print '5-Web Monkey'
            monkeyType[i] = int(raw_input('Input: '))

        print "\n"

        while monkeyLoc[i] not in validLocs:
            print 'Define Monkey Location:'
            print 'i-Internal'
            print 'e-External'
            monkeyLoc[i] = raw_input('Input: ').lower()

        monkeyIp[i] = raw_input('Enter IP address of monkey server: ')

        #Deal with fuzzy monkeys who need an extra option
        if monkeyType[i] == 3:
            minFuzzSize[i] = int(
                raw_input(
                    'Enter the minimum number of bytes of fuzz data to send: ')
            )
            maxFuzzSize[i] = int(
                raw_input(
                    'Enter the maximum number of bytes of fuzz data to send: ')
            )

    loadMonkeys(options, db, monkeyIQ, monkeyType, monkeyLoc, monkeyIp,
                minFuzzSize, maxFuzzSize)
    raw_input(
        'Finished making monkeys.  Press enter to return to the main menu.')
    return
Example #23
0
def dbLoadModules(options, msfDbIp, msfDbUser, msfDbPass, msfDbName):
    try:
        pgConn = psycopg2.connect(database=msfDbName,
                                  host=msfDbIp,
                                  user=msfDbUser,
                                  password=msfDbPass)
        cur = pgConn.cursor()
        cur.execute('SELECT file,fullname FROM module_details;')
        mongoDb = openMDB(options['dbip'], options['dbname'])
        if mongoDb is None:
            print 'I am error'
        if 'logins' in mongoDb.collection_names(
        ) or 'sploits' in mongoDb.collection_names():
            if (options['CLI'] == 'true' and
                    raw_input('Previous exploit data found.  Erase? ').lower()
                    == 'y') or (options['CLI'] == 'false'
                                and options['eraseSploitData'] == 'true'):
                if 'logins' in mongoDb.collection_names():
                    mongoDb['logins'].drop()

                if 'sploits' in mongoDb.collection_names():
                    mongoDb['sploits'].drop()

        print 'Opening exploits and getting default port numbers...'
        for sploit in cur:
            f = open(sploit[0], "r")
            portSearch = f.readlines()
            f.close()

            for line in portSearch:
                if "Opt::RPORT" in line:

                    try:
                        regex = '.*\((.*?)\).*'
                        matches = re.search(regex, line)

                        if matches.group(1).isdigit():
                            if 'auxiliary' in sploit[1] and 'scanner' in sploit[
                                    1] and '_login' in sploit[1]:
                                #If the logic evaluates to True, this is a login module
                                mongoDb.logins.insert({
                                    'modName': sploit[1],
                                    'port': matches.group(1)
                                })

                            elif 'exploit' in sploit[1]:
                                #This is an exploit module
                                mongoDb.sploits.insert({
                                    'modName': sploit[1],
                                    'port': matches.group(1)
                                })

                        else:
                            continue

                    except:
                        pass

    except Exception, e:
        if options['CLI'] == 'true':
            raw_input(
                'Data not imported.  Check your MongoDB and Postgres settings. '
            )
        return
Example #24
0
def makeMonkeys():
    global options
    global monkeyIds
    monkeyTypes = [None,'Scan Monkey',None,'Fuzzy Monkey',None,'Web Monkey']
    dropSel = True
    existing = []
    print 'Monkey setup'
    print '------------'
    db = openMDB(options['dbip'],options['dbname'])
    if db is None:
        print 'Could not connect to database'
    if 'monkeys' in db.collection_names():
        if raw_input('Existing monkeys found.  Remove? ').lower() == 'y':
            count = 1

            for monkey in db.monkeys.find():
                print str(count) + '-' + str(monkey['ip']) + '-' + monkeyTypes[ int(monkey['type']) ]
                existing.append(monkey['id'])
                count += 1

            while dropSel == True:
                dropSel = raw_input('Enter monkey to remove,e to remove all monkeys, or q to make monkeys: ')

                if  dropSel.lower() == 'e':
                    db['monkeys'].drop()
                    print 'Monkeys removed!'

                elif dropSel.lower() == 'q':
                    dropSel = False

                else:
                    db.monkeys.remove({'id' : existing[int(dropSel)-1]})
                    dropSel = True


        else:
            #Get the IDs of the existing monkeys to avoid dupes
            for monkey in db.monkeys.find():
                monkeyIds.append(monkey['id'])

    else:
        print 'No monkeys found in database.'

    numMonkeys = int(raw_input('Enter total number of monkeys to create: '))
    validIQs = [0, 1, 2, 3]
    validTypes = [1, 2, 3, 4, 5]
    validLocs = ['i', 'e']

    monkeyIQ = {}
    monkeyType = {}
    monkeyLoc = {}
    monkeyIp = {}
    minFuzzSize = {}
    maxFuzzSize = {}

    for i in range(1, numMonkeys + 1):
        monkeyIQ[i] = None
        monkeyType[i] = None
        monkeyLoc[i] = None
        print 'Setting up monkey #' + str(i)

        while monkeyIQ[i] not in validIQs:
            print '---------------------'
            print 'Enter Monkey IQ:'
            print '0-World\'s #1 Hacker'
            print '1-CISSP'
            print '2-CEH'
            print '3-Security Weekly Listener'
            monkeyIQ[i] = int(raw_input('Input: '))

        print "\n"

        while monkeyType[i] not in validTypes:
            print 'Define Monkey Type:'
            print '1-Scanner Monkey'
            print '2-Exploit Monkey'
            print '3-Fuzzy Monkey'
            print '4-Brute Monkey'
            print '5-Web Monkey'
            monkeyType[i] = int(raw_input('Input: '))

        print "\n"

        while monkeyLoc[i] not in validLocs:
            print 'Define Monkey Location:'
            print 'i-Internal'
            print 'e-External'
            monkeyLoc[i] = raw_input('Input: ').lower()

        monkeyIp[i] = raw_input('Enter IP address of monkey server: ')

        #Deal with fuzzy monkeys who need an extra option
        if monkeyType[i] == 3:
            minFuzzSize[i] = int(raw_input('Enter the minimum number of bytes of fuzz data to send: '))
            maxFuzzSize[i] = int(raw_input('Enter the maximum number of bytes of fuzz data to send: '))

    loadMonkeys(options, db, monkeyIQ, monkeyType, monkeyLoc, monkeyIp, minFuzzSize, maxFuzzSize)
    raw_input('Finished making monkeys.  Press enter to return to the main menu.')
    return