forked from milo2012/metasploitHelper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
msfHelper.py
executable file
·2281 lines (2147 loc) · 82 KB
/
msfHelper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen
import string
import random
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import sqlite3
import datetime
from time import gmtime, strftime
import os, optparse, sys, subprocess
try:
import msfrpc
except:
print "Please install msfrpc from https://github.com/SpiderLabs/msfrpc/tree/master/python-msfrpc"
print "\n"
print "cd /tmp && git clone https://github.com/SpiderLabs/msfrpc"
print "cd msfrpc && cd python-msfrpc && python setup.py install"
print "pip install msgpack-python"
print "\n"
sys.exit()
from time import sleep
import time
import random
try:
from tabulate import tabulate
except:
print "Please run 'pip install tabulate'"
try:
from termcolor import colored, cprint
except:
print "Please run 'pip install termcolor'"
import socket
import itertools
import os
from sys import platform
try:
from bs4 import BeautifulSoup
except:
print "Please run 'pip install beautifulsoup4'"
from urlparse import urlparse
from xml.etree import ElementTree
try:
from libnmap.parser import NmapParser
except:
print "Please run 'pip install python-libnmap'"
import platform
import re
import argparse
import sys
try:
import requests
except:
print "Please run 'pip install requests'"
import multiprocessing
from itertools import islice
multiprocessing.allow_connection_pickling()
import commands
import optparse
import socket
import fcntl
import struct
greatthanPorts=0
mypassword=""
portsInput=""
intelligentMode=False
scanAll=False
numOfThreads=10
chunkSize=50
manualStart=False
verbose=False
blankDB=False
bold=True
internetUp=False
showOnly=False
portInfo=False
quickMode=False
msfIP="127.0.0.1"
msfPort=55552
execMethod="all"
nmapFilename=""
#Dependencies
#git clone https://github.com/SpiderLabs/msfrpc
#cd python-msfrpc && python setup.py install
#pip install tabulate termcolor python-libnmap
#Useful VM for testing: https://github.com/rapid7/metasploitable3/wiki/Vulnerabilities
autoExpListExp=[]
autoExpListAux=[]
manualExpList=[]
allPortList=[]
allPortModuleList=[]
allPathList=[]
allPathModuleList=[]
uniqueSvcNameList=[]
uniqueSvcBannerList=[]
portsList=[]
httpsList=[]
httpList=[]
osList=[]
runManualList=[]
workingExploitList=[]
targetList=[]
catchDupSessionList=[]
tmpTargetURIList=[]
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
requests.packages.urllib3.disable_warnings()
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += ':RC4-SHA'
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.2; rv:30.0) Gecko/20150101 Firefox/32.0",
"Connection": "keep-alive"}
msfPath="/usr/share/metasploit-framework"
class colors:
def __init__(self):
self.green = "\033[92m"
self.blue = "\033[94m"
self.bold = "\033[1m"
self.yellow = "\033[93m"
self.red = "\033[91m"
self.end = "\033[0m"
color = colors()
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open("logfile.log","w")
def write(self, message):
self.terminal.write(message)
#message=message.encode('ascii','replace')
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger()
def generatePassword():
chars = string.letters + string.digits
pwdSize = 20
return ''.join((random.choice(chars)) for x in range(pwdSize))
def get_ip_address():
cmd="ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\\2/p'"
results=runCommand(cmd)
resultList=results.split("\n")
return resultList[0]
#s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#return socket.inet_ntoa(fcntl.ioctl(
# s.fileno(),
# 0x8915, # SIOCGIFADDR
# struct.pack('256s', ifname[:15])
#)[20:24])
def escape_ansi(line):
ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]')
return ansi_escape.sub('', line)
def parseNmap(filename):
tmphttpList=[]
tmphttpsList=[]
tmpportsList=[]
tmpOSList=[]
with open (filename, 'rt') as file:
tree=ElementTree.parse(file)
rep = NmapParser.parse_fromfile(filename)
for _host in rep.hosts:
ip = (_host.address)
for osmatch in _host.os.osmatches:
os = osmatch.name
accuracy = osmatch.accuracy
if "linux" in os.lower() or "unix" in os.lower():
if [ip,"linux"] not in tmpOSList:
tmpOSList.append([ip,"linux"])
if [ip,"unix"] not in tmpOSList:
tmpOSList.append([ip,"unix"])
if "windows" in os.lower():
tmpOSList.append([ip,"windows"])
if "apple" in os.lower() or "apple os x" in os.lower():
tmpOSList.append([ip,"osx"])
if "solaris" in os.lower():
tmpOSList.append([ip,"solaris"])
for services in _host.services:
if services.state=="open":
try:
if len((services.banner).split(" ")[1])>2:
serviceBanner=((services.banner).split(" ")[1]).lower()
if [ip,services.port,serviceBanner] not in uniqueSvcBannerList:
uniqueSvcBannerList.append([ip,services.port,serviceBanner])
except IndexError as e:
pass
tmpportsList.append([str(ip),str(services.port),services.protocol,services.service])
if services.service!="http":
if services.service not in uniqueSvcNameList and "?" not in str(services.service):
uniqueSvcNameList.append([ip,services.port,services.service])
else:
if services.tunnel=="ssl":
tmphttpsList.append([str(ip),str(services.port),services.protocol,services.service])
else:
tmphttpList.append([str(ip),str(services.port),services.protocol,services.service])
return tmpportsList,tmphttpsList,tmphttpList,tmpOSList
def checkInternetAccess():
try:
t = requests.get('http://detectportal.firefox.com/success.txt')
return t.text.strip('\n') == 'success'
except:
pass
return False
def extractPortInfo(x):
response=""
portNo=x[0]
protocol=x[1]
port=""
portDesc=""
portName=""
conn=""
if not os.path.exists("portDB.sqlite"):
conn = sqlite3.connect("portDB.sqlite")
conn.text_factory = str
try:
conn.execute('''CREATE TABLE db
(portNo TEXT NOT NULL,
portType TEXT NOT NULL,
portDescription TEXT UNIQUE NOT NULL);''')
except Exception as e:
pass
else:
conn = sqlite3.connect("portDB.sqlite")
conn.text_factory = str
url="http://webcache.googleusercontent.com/search?q=cache:http://www.speedguide.net/port.php?port="+str(portNo)
cur=conn.execute("SELECT portNo, portType, portDescription from db WHERE portNo=?",(str(portNo)+"/"+str(protocol),))
row = cur.fetchone()
if row!=None:
port=row[0]
portName=row[1]
portDesc=row[2]
else:
if internetUp==True:
r = requests.get(url, headers=headers, verify=False, timeout=15,allow_redirects=False)
soup = BeautifulSoup(r.content,'lxml')
try:
table = soup.find("table", {"class": "port"})
rows = table.find_all('tr')
bold=True
found=False
for tr in rows:
cols = tr.find_all('td')
if found==False:
try:
if protocol in cols[1].text.strip():
port=str(portNo)+"/"+protocol
portName=cols[2].text.strip()
portDesc=cols[3].text.split("\n")[0]
conn.execute("INSERT INTO db (portNo, portType, portDescription) VALUES (?,?,?)" , (port,portName,portDesc));
conn.commit()
found=True
except:
pass
except:
pass
time.sleep(3)
conn.close()
return [port,portName,portDesc]
def setColor(message, bold=False, color=None, onColor=None):
retVal = colored(message, color=color, on_color=onColor, attrs=("bold",))
return retVal
def chunk(it, size):
it = iter(it)
return iter(lambda: tuple(islice(it, size)), ())
def testURL(url1):
resLen=0
pageSize=0
title=''
try:
#print url1
r = requests.get(url1, headers=headers, verify=False, timeout=5,allow_redirects=False)
url1=url1.strip()
#print url1+"\t"+str(r.status_code)
#html = BeautifulSoup(r.text,'html.parser')
if r.status_code==200 or r.status_code==401:
html = BeautifulSoup(r.text,'lxml')
title = html.title.string
pageSize = len(r.text)
return [url1,str(r.status_code),pageSize,str(title)[0:19]]
except requests.exceptions.ConnectionError as e:
pass
except requests.exceptions.ReadTimeout as e:
pass
except Exception as e:
pass
def testMultiURL(url,pathList):
global chunkSize
pathList.append("/fakeURL1")
pathList.append("/fakeURL2")
pathList.append("/fakeURL3")
tmpResultList2=[]
tmpUrlList=[]
#if len(pathList)>50:
# chunkSize=10
splitUrlList=list(chunk(pathList, chunkSize))
count=1
#print "Total Chunks: "+str(len(splitUrlList))
for chunkList in splitUrlList:
tmpResultList=[]
tmpResultList1=[]
tmpUrlList=[]
#print "Chunk #"+str(count)
for y in chunkList:
tmpUrlList.append(url+y)
p = multiprocessing.Pool(numOfThreads)
tmpResultList = p.map(testURL,tmpUrlList)
tmpResultList = [x for x in tmpResultList if not x is None]
for x in tmpResultList:
if x not in tmpResultList1:
tmpResultList1.append(x)
p.close()
p.join()
p.terminate()
lastDomain=None
tmpList=[]
tmpPageTitleList=[]
for x in tmpResultList1:
url1=x[0]
parsed_uri = urlparse(url1)
domain = '{uri.netloc}'.format(uri=parsed_uri)
statusCode=x[1]
pageSize=x[2]
pageTitle=x[3]
itemCount=0
tmpPageTitleList.append(pageTitle)
if len(tmpResultList1)==len(set(tmpPageTitleList)):
for x in tmpResultList1:
tmpResultList2.append(x[0])
else:
for x in tmpResultList1:
if (tmpPageTitleList).count(x[3])<2:
tmpResultList2.append(x[0])
tmpResultList=[]
tmpResultList1=[]
count+=1
return tmpResultList2
def isOpen(ip,port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, int(port)))
s.shutdown(2)
return True
except:
return False
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
def runCommand(fullCmd):
try:
return commands.getoutput(fullCmd)
except:
return "Error executing command %s" %(fullCmd)
def extractParam(uri,filename):
with open(filename) as f:
lines = f.read().splitlines()
moduleName = filename.replace(msfPath,"")
startFound=False
pathList=[]
tempStrList=[];
finalList=[]
optionList=[]
found=False
foundName=False
moduleTitle=""
for line in lines:
if "'Name'" in line:
if foundName==False:
line1 = line.split("=>")
if len(line1)>1:
moduleTitle=(line1[1])[2:-2]
moduleTitle=moduleTitle.replace(","," ")
if "register_options" in line:
startFound=True
if "self.class" in line and found==False:
found1=False
for y in optionList:
if found1==True:
y = y.strip()
if "#" not in y:
tempStrList.append(y)
if ".new" in y:
if found1==True:
tempStrList=[]
found1=False
if "[" in y and "]" in y:
y = y.strip()
finalList.append(y)
else:
y = y.strip()
if "#" not in y:
tempStrList.append(y)
found1=True
startFound=False
found=True
if startFound==True:
optionList.append(line)
result1=""
for y in tempStrList:
try:
m = re.search('"(.+?)"',y)
temp1 = str(m.group(1)).replace(",","")
y = y.replace(m.group(1),temp1)
result1 += y
except AttributeError:
result1 += y
continue
if len(str(result1))>0:
result1 = result1.replace(" ","")
finalList.append(result1)
tempStr1=""
for g in finalList:
if "false" not in g.lower() and "rhost" not in g.lower():
parameterList = g.partition('[')[-1].rpartition(']')[0]
parNameTemp =( g.split(",")[0]).partition("'")[-1].rpartition("'")[0]
result = (parameterList.split(",")[-1]).strip()
if result=='""' or result=="''":
tempStr1+= parNameTemp
tempStr1+= "+"
moduleName = moduleName.replace(".rb","")
if len(tempStr1)>0:
if tempStr1[-1]==",":
results = uri+","+moduleName+",["+tempStr1[0:(len(tempStr1)-1)]+"],"+moduleTitle
return results
else:
results = uri+","+moduleName+",["+tempStr1[0:(len(tempStr1)-1)]+"],"+moduleTitle
return results
else:
results = uri+","+moduleName+",[],"+moduleTitle
return results
def retrieveModuleDetails(input):
global tmpTargetURIList
category=input[0][0]
module=input[0][1]
uriPath=''
moduleDescription=''
moduleOptions=''
complete=False
maxTries = 3
currentTries=0
while complete==False and currentTries<maxTries:
try:
import msfrpc
msfrpc = reload(msfrpc)
opts={}
opts['host']='127.0.0.1'
opts['port']=msfPort
opts['uri']='/api/'
opts['ssl']=False
client = msfrpc.Msfrpc(opts)
client.login('msf', mypassword)
moduleDescription=(client.call('module.info',[category,module])['description']).strip()
import msfrpc
opts={}
opts['host']='127.0.0.1'
opts['port']=msfPort
opts['uri']='/api/'
opts['ssl']=False
msfrpc = reload(msfrpc)
client = msfrpc.Msfrpc(opts)
client.login('msf', mypassword)
moduleOptions=client.call('module.options',[category,module])
complete=True
except Exception as e:
currentTries+=1
continue
moduleName=module
if filterModuleName(moduleName)==True:
print "[*] Fetching module details: "+category+"/"+module
if 'TARGETURI' in str(moduleOptions).upper():
for key, value in moduleOptions.iteritems():
if key=='TARGETURI':
try:
uriPath=value['default']
tmpTargetURIList.append([uriPath,category,moduleName])
except KeyError:
uriPath=''
tmpTargetURIList.append([uriPath,category,moduleName])
if filterModuleName(moduleName)==True:
portNo=None
targetSingle=True
if 'RPORT' in str(moduleOptions):
for key, value in moduleOptions.iteritems():
if key=='RPORT':
try:
portNo=value['default']
except KeyError:
portNo=None
else:
if 'RPORTS' in str(moduleOptions):
for key, value in moduleOptions.iteritems():
if key=='RPORTS':
try:
portNo=value['default']
except KeyError:
portNo=80
else:
if "/http/" in moduleName:
portNo=80
if 'RHOSTS' in str(moduleOptions):
targetSingle=False
else:
if 'RHOST' in str(moduleOptions):
targetSingle=True
if portNo!=None:
tmpOptionList=[]
moduleOptions=client.call('module.options',[category,moduleName])
for key, value in moduleOptions.iteritems():
if key!='RHOST' and key!='RHOSTS':
if value['required']==True:
try:
if value['default']=='':
tmpOptionList.append(key)
except:
tmpOptionList.append(key)
if len(tmpOptionList)>0:
optionStr=''
count=0
totalCount=len(tmpOptionList)
for x in tmpOptionList:
x=x.strip()
optionStr+=x
if totalCount>1:
if count<totalCount-1:
optionStr+="|"
count+=1
return [portNo,category,moduleName,optionStr,uriPath,moduleDescription]
else:
return [portNo,category,moduleName,'',uriPath,moduleDescription]
def searchModule(x):
foundList=[]
searchKeyword1=''
searchKeyword=x
if searchKeyword!="unknown":
if "-" in searchKeyword:
searchKeyword1=searchKeyword.split("-")[0]
else:
searchKeyword1=searchKeyword
keywordBlacklist=[]
keywordBlacklist.append("http")
if searchKeyword1 not in keywordBlacklist:
for y in allPortModuleList:
portNo=y[0]
moduleType=y[1]
moduleName=y[2]
moduleParameters=y[3]
moduleDescription=y[4]
if "/"+searchKeyword1.lower()+"/" in moduleName.lower() and searchKeyword1.lower() not in keywordBlacklist:
if filterModuleName(moduleName)==True:
if [moduleType,moduleName,portNo,searchKeyword1,moduleParameters,moduleDescription] not in foundList:
foundList.append([moduleType,moduleName,portNo,searchKeyword1,moduleParameters,moduleDescription])
if "_"+searchKeyword1.lower()+"_" in moduleName.lower() and searchKeyword1.lower() not in keywordBlacklist:
if filterModuleName(moduleName)==True:
if [moduleType,moduleName,portNo,searchKeyword1,moduleParameters,moduleDescription] not in foundList:
foundList.append([moduleType,moduleName,portNo,searchKeyword1,moduleParameters,moduleDescription])
#if searchKeyword1.lower() in moduleDescription.lower() and searchKeyword1 not in keywordBlacklist:
# if [moduleType,moduleName,portNo,searchKeyword1,moduleParameters,moduleDescription] not in foundList:
# foundList.append([moduleType,moduleName,portNo,searchKeyword1,moduleParameters,moduleDescription])
return searchKeyword1,foundList
def pullMSF():
ip=msfIP
port=msfPort
if manualStart==True:
print "[*] Please run 'msfconsole' and then type 'msgrpc load Pass=xxx'"
testConnection=False
while testConnection==False:
try:
opts={}
opts['host']='127.0.0.1'
opts['port']=msfPort
opts['uri']='/api/'
opts['ssl']=False
client = msfrpc.Msfrpc(opts)
client.login('msf', mypassword)
testConnection=True
except Exception as e:
if 'Connection refused' in str(e):
time.sleep(1)
if 'Authentication failed' in str(e):
print "[!] Incorrect password"
sys.exit()
tmpModuleList=[]
opts={}
opts['host']='127.0.0.1'
opts['port']=msfPort
opts['uri']='/api/'
opts['ssl']=False
client = msfrpc.Msfrpc(opts)
if client.login('msf', mypassword)==False:
print "[!] Unable to connect to msfrpcd"
sys.exit()
aux_list=client.call('module.auxiliary', [])['modules']
for x in aux_list:
tmpModuleList.append(['auxiliary',x])
time.sleep(1)
exp_list=client.call('module.exploits', [])['modules']
for x in exp_list:
tmpModuleList.append(['exploit',x])
print "\n[*] Loaded "+str(len(tmpModuleList))+" modules from Metasploit"
del client
return tmpModuleList
def startMSF():
print "[*] Launching Metasploit msfrpcd"
count=0
cmd=msfPath+"/msfrpcd -p "+str(msfPort+count)+" -U msf -P "+mypassword+" -a "+msfIP+" -u /api/ -S"
os.system(cmd)
#while count<numOfThreads:
# cmd=msfPath+"/msfrpcd -p "+str(msfPort+count)+" -U msf -P "+mypassword+" -a "+msfIP+" -u /api/ -S"
# subprocess.call(cmd, stdout=subprocess.PIPE, shell=True)
# count+=1
def killMSF():
#cmd="pkill -x msfrpcd"
cmd="pkill -f msfrpcd"
os.system(cmd)
def updateMSF():
cmd = msfPath+"/msfupdate"
os.system(cmd)
def lookupPortDB(inputPortNo,portProtocol):
tmpResultList=[]
for x in allPortModuleList:
portNo=x[0]
moduleType=x[1]
moduleName=x[2]
moduleParameters=x[3]
moduleDescription=x[4]
if str(portNo)==str(inputPortNo):
tmpResultList.append([portNo,moduleType,moduleName,moduleParameters,moduleDescription])
return tmpResultList
def test_port(ip, port):
try:
s = socket.socket()
s.settimeout(2)
s.connect((str(ip), int(port)))
s.close
screenLock.acquire()
print ip
screenLock.release()
return True
except:
return False
def start_thread(ip, port):
t = threading.Thread(target=test_port, args=(ip, port))
t.start()
def scanSubnet(ipRange):
screenLock = threading.Semaphore(value=1)
for n in range(0,256):
ip = ip_prefix + "." + str(n)
start_thread(ip, port)
def searchAndExtractPaths():
tmpResultList=[]
tmpFileList=[]
for root, directories, filenames in os.walk(msfPath):
for filename in filenames:
tmpFileList.append(os.path.join(root,filename))
for filename in tmpFileList:
text_file = open(filename, "r")
lines = text_file.readlines()
for x in lines:
if "'uri' => '" in x:
x=x.strip()
x=(x.split("'uri' => '")[1]).strip()
x=x.replace('"','')
x=x.replace("'",'')
x=x.strip()
if x.endswith(","):
x=x[0:len(x)-1]
tmpFilename=x
tmpPath=tmpFilename
if '")' in tmpPath:
tmpPath=tmpPath.split('")')[0]
if [filename,tmpPath] not in tmpResultList:
tmpResultList.append([filename,tmpPath])
if "'uri' => normalize_uri(uri," in x:
x=x.strip()
x=(x.split("normalize_uri(uri,")[1]).strip()
tmpList=x.split(",")
tmpList1=[]
for y in tmpList:
if "payload_name" not in y:
y=y.replace('"','')
y=y.replace("'",'')
y=y.strip()
if y.endswith(")"):
y=y[0:len(y)-1]
tmpList1.append(y)
tmpFilename="/"+"/".join(tmpList1)
tmpFilename=tmpFilename.replace("//","/")
if tmpFilename.endswith("/"):
tmpFilename=tmpFilename[0:len(tmpFilename)-1]
tmpPath=tmpFilename
if '")' in tmpPath:
tmpPath=tmpPath.split('")')[0]
if [filename,tmpPath] not in tmpResultList:
tmpResultList.append([filename,tmpPath])
elif "'uri' => normalize_uri(" in x:
x=x.strip()
x=x.strip()
x=(x.split("'uri' => normalize_uri(")[1]).strip()
tmpList=x.split(",")
tmpList1=[]
for y in tmpList:
y=y.strip()
if (y.startswith('"') or y.startswith("'")) and not "#" in y:
y=y[1:len(y)-1]
tmpList1.append(y)
tmpFilename="/".join(tmpList1)
if tmpFilename.endswith("'"):
tmpFilename=tmpFilename[0:len(tmpFilename)-1]
if tmpFilename.endswith('"'):
tmpFilename=tmpFilename[0:len(tmpFilename)-1]
if not tmpFilename.startswith("/"):
tmpFilename="/"+tmpFilename
tmpPath=tmpFilename.replace("//","/")
if '")' in tmpPath:
tmpPath=tmpPath.split('")')[0]
if [filename,tmpPath] not in tmpResultList:
tmpResultList.append([filename,tmpPath])
return tmpResultList
def updateDB(tmpModuleList):
print "[*] Updating msfHelper.db"
#Update Database
tmpPathList=[]
p = multiprocessing.Pool(numOfThreads)
#tmpResultList=[]
tmpResultList = p.map(retrieveModuleDetails,itertools.izip(tmpModuleList))
p.close()
p.terminate()
tmpOutputPathList=[]
f1 = open('pathList.txt','w')
f = open('portList.csv','w')
conn = sqlite3.connect(os.getcwd()+"/msfHelper.db")
conn.text_factory = str
print "[*] Writing to msfHelper.db"
for x in tmpResultList:
if x!=None:
portNo=x[0]
moduleType=x[1]
moduleName=x[2]
moduleParameters=x[3]
uriPath=x[4]
moduleDescription=x[5]
moduleDescription=moduleDescription.replace("\n"," ")
if uriPath not in tmpPathList:
tmpPathList.append(uriPath)
if uriPath!=None and len(uriPath)>1 and uriPath.startswith("/"):
if uriPath.endswith("/"):
uriPath=uriPath[0:len(uriPath)-1]
if uriPath not in tmpOutputPathList:
f1.write(uriPath+"\n")
tmpOutputPathList.append(uriPath)
f.write(str(portNo)+","+moduleType+","+moduleName+","+moduleParameters+"\n")
print "x: "+moduleType+" "+moduleName
try:
conn.execute("INSERT INTO portList (portNo,moduleType,moduleName,moduleParameters,moduleDescription) VALUES (?,?,?,?,?)" , (portNo,moduleType,moduleName,moduleParameters,moduleDescription,));
conn.commit()
except sqlite3.IntegrityError:
continue
if len(uriPath)>0:
try:
print "[*] Adding: "+moduleName
conn.execute("INSERT INTO pathList (uriPath,moduleType,moduleName,moduleParameters,moduleDescription) VALUES (?,?,?,?,?)" , (uriPath,moduleType,moduleName,moduleParameters,moduleDescription,));
conn.commit()
except sqlite3.IntegrityError:
continue
tmpPathList=searchAndExtractPaths()
for x in tmpPathList:
x[0]=x[0].replace(msfPath,"")
x[0]=x[0].replace("/modules/","")
tmpPath=x[1]
x1=x[0].split("/")
tmpModuleType=x1[0]
tmpModuleName=x[0].replace(x1[0],"")
tmpModuleName=tmpModuleName[1:len(tmpModuleName)-3]
tmpModuleDescription=""
if len(tmpPath)>0:
try:
print "[*] Adding: "+tmpModuleName
conn.execute("INSERT INTO pathList (uriPath,moduleType,moduleName,moduleParameters,moduleDescription) VALUES (?,?,?,?,?)" , (tmpPath,tmpModuleType,tmpModuleName,"",tmpModuleDescription,));
if len(x[1])>1:
f1.write(x[1]+"\n")
conn.commit()
except sqlite3.IntegrityError:
continue
f.close()
f1.close()
conn.close()
def diff(list1, list2):
c = set(list1).union(set(list2))
d = set(list1).intersection(set(list2))
return list(c - d)
def runExploitDBModules():
vulnURLList=[]
if execMethod=="all" or execMethod=="exploitdb":
exploitDBList=readExploitDB()
tmpPathList=[]
for x in exploitDBList:
filename=x[0]
pathName=x[1]
url=x[2]
category=x[3]
if pathName not in tmpPathList:
tmpPathList.append(pathName)
if len(httpList)>0:
tmpHttpList=[]
for x in httpList:
url="http://"+x[0]+":"+x[1]
if url not in tmpHttpList:
tmpHttpList.append(url)
for host in tmpHttpList:
tmpResultList=testMultiURL(host,tmpPathList)
for x in tmpResultList:
if x not in vulnURLList:
if "index.php" not in x:
vulnURLList.append(x)
if len(httpsList)>0:
tmpHttpsList=[]
for x in httpsList:
url="https://"+x[0]+":"+x[1]
if url not in tmpHttpsList:
tmpHttpsList.append(url)
for host in tmpHttpsList:
tmpResultList=testMultiURL(host,tmpPathList)
for x in tmpResultList:
if "index.php" not in x:
vulnURLList.append(x)
tmpPathResultList=[]
if len(vulnURLList)<1:
print "No results found"
print "\n"
else:
message="\n[*] Found the below URLs on the web servers"
print(setColor(message, bold, color="red"))
for x in vulnURLList:
print x
for x in vulnURLList:
for y in exploitDBList:
path = urlparse(x).path
if path==y[1] and path!="/":
tmpPathResultList.append([x,y[0],y[3]])
if len(tmpPathResultList)>1:
tmpList1=[]
message="\n[*] Found the below possible Exploit-DB entries"
print(setColor(message, bold, color="red"))
for x in tmpPathResultList:
x[1]=x[1].replace("/pentest/","")
if [x[1],"["+x[2]+"]"] not in tmpList1:
tmpList1.append([x[1],"["+x[2]+"]"])
tmpList1.sort()
print tabulate(tmpList1)
tmpList1=[]
exploitDBList=[]
return ""
def runWebBasedModules():
if execMethod=="all" or execMethod=="web":
vulnURLList=[]
message="\n**** Finding MSF Modules - Bruteforcing URI Paths ****"
print(setColor(message, bold, color="red"))
if len(httpList)>0:
tmpHttpList=[]
for x in httpList:
url="http://"+x[0]+":"+x[1]
if url not in tmpHttpList:
tmpHttpList.append(url)
for host in tmpHttpList:
tmpResultList=testMultiURL(host,allPathList)
for x in tmpResultList:
if x not in vulnURLList:
if "index.php" not in x[0]:
vulnURLList.append(x[0])
if len(httpsList)>0:
tmpHttpsList=[]
for x in httpsList:
url="https://"+x[0]+":"+x[1]
if url not in tmpHttpsList:
tmpHttpsList.append(url)
for host in tmpHttpsList:
tmpResultList=testMultiURL(host,allPathList)
for x in tmpResultList:
if "index.php" not in x[0]:
vulnURLList.append(x[0])
tmpPathResultList=[]
if len(vulnURLList)<1:
print "No results found"
print "\n"
for x in vulnURLList:
for y in allPathModuleList:
path = urlparse(x).path
if path==y[0] and path!="/":
tmpPathResultList.append([x,y[1]+"/"+y[2]])
if len(tmpPathResultList)>1:
for x in tmpPathResultList:
print x
#Temp holder for running metasploit modules against the root of web servers
defaultPathModuleList=[]
for x in allPathModuleList:
uriPath=x[0]
moduleType=x[1]
moduleName=x[2]
moduleParameters=x[3]
if uriPath=="/":
defaultPathModuleList.append([uriPath,moduleType+"/"+moduleName,moduleParameters])
if len(tmpPathResultList)>0:
#Run all modules against web servers which uripath matches against the list
print "\n**** Test Results from Metasploit Modules ****"
print "Please wait ..."
#message="\n[*] Launching compatible Metasploit modules"
#print(setColor(message, bold, color="red"))
tmpPathResultList1=[]
maxCount=numOfThreads
startCount=0
for x in tmpPathResultList:
parsed_uri = urlparse(x[0])
host = parsed_uri.netloc
moduleName=x[1]
tmpPathResultList1.append([host,moduleName,startCount])
if startCount==maxCount-1:
startCount=0
else:
startCount+=1
runMsfExploitsAndDisplayreport(tmpPathResultList1)
#Run all modules against http and https servers matching uriPath=/
if len(httpList)>0:
tmpPathResultList1=[]
tmpPathResultList2=[]
for x in defaultPathModuleList:
for y in httpList:
host=y[0]+":"+y[1]
moduleName=x[1]
moduleParameters=x[2]
if len(moduleParameters)>0:
tmpPathResultList2.append([host,moduleName])
else:
tmpPathResultList1.append([host,moduleName])
if len(httpsList)>0:
tmpPathResultList1=[]
tmpPathResultList2=[]
maxCount=numOfThreads
startCount=0
for x in defaultPathModuleList:
for y in httpList: