-
Notifications
You must be signed in to change notification settings - Fork 68
/
BurpSmartBuster.py
1872 lines (1474 loc) · 70.2 KB
/
BurpSmartBuster.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
# -*- coding: utf-8 -*-
'''
Created on 2015-02-22
BurpSmartBuster
@author: @pathetiq
@thanks: Abhineet & @theguly
@version: 0.3
@summary: This is a Burp Suite extension which discover content with a smart touch. A bit like “DirBuster” and “Burp Discover Content”,
but smarter and being integrated into Burp Suite this plugin looks at words in pages, the domain name, the current directories and filename
to help you find hidden files, directories and information you usually don't with a static dictionary file that brute force its way on the web server.
@bug: URL with variable, no file, no extension or weird variable separate by ; :, etc. breaks the directories/files listing
@todo: technology detection and scanning, community files, add 404 detection in output, threads speeds and adjustments
@todo: Add results to an issue. add tested files somewhere, add found file to sitemap.
'''
import os
os.environ["NLTK_DATA"] = os.path.join(os.getcwd(), "nltk_data")
#sys imports
import sys
#Find the jython path where our prerequisites packages are installed
import site
for site in site.getsitepackages():
sys.path.append(site)
#Examples of paths if needed
#sys.path.append("/home/USERNAME/.local/lib/python2.7/site-packages/")
#sys.path.append("/usr/local/lib/python2.7/site-packages")
##sys.path.append("/usr/lib/python2.7/dist-packages/")
#sys.path.append("/home/USERNAME/Documents/Apps/TextBlob")
#sys.path.append("/home/USERNAME/Documents/Apps/nltk")
#burp imports
from burp import IBurpExtender
from burp import IScanIssue
from burp import IScannerCheck
from burp import IScannerInsertionPoint
from burp import IHttpListener
from burp import IBurpExtenderCallbacks
#UI Import
from burp import IContextMenuFactory
from java.util import List, ArrayList
from burp import ITab
from javax.swing import JPanel, JLabel, JMenuItem, JTextField, JList, DefaultListModel, JButton, JFileChooser
from javax.swing import JScrollPane, ListSelectionModel, GroupLayout, ButtonGroup, JRadioButton
from java.awt import Dimension
from java.awt import Toolkit
from java.awt.datatransfer import StringSelection
#utils imports
from array import array
from java.io import PrintWriter
from java.net import URL
import os
import ConfigParser
import json
import logging
from tld import get_tld
import hashlib
import random
#spidering
from bs4 import BeautifulSoup
import Queue
#Parse HTML comments
from bs4 import Comment
import re
from urlparse import urlparse
#requester
import requests
import csv
from collections import deque
import threading
#text tokenization & natural language lib
locals()
#TODO: REVALIDATE the following : file /usr/local/lib/python2.7/dist-packages/nltk/internals.py line 902 has been change to remove os.getgroups() to compile in Burp...Jhython?
#http://textminingonline.com/getting-started-with-textblob
from textblob import TextBlob
'''----------------------------------------------------------------------------------------------------------------------------------------
BurpSmartBuster Logging object and config
----------------------------------------------------------------------------------------------------------------------------------------'''
class Logger():
LOG_FILENAME = 'BSB.log'
DEFAULT_LEVEL = logging.DEBUG
def __init__(self,name=LOG_FILENAME,level=DEFAULT_LEVEL):
#define configs
self._default_level=level
self._name = name
print "Log file is: " + name
logging.basicConfig(filename=self._name+".log",
level=self._default_level,
format="%(asctime)s - [%(levelname)s] [%(threadName)s] (%(funcName)s:%(lineno)d) %(message)s",
)
self._logger = logging.getLogger(name)
return
def getLogger(self):
return self._logger
'''----------------------------------------------------------------------------------------------------------------------------------------
BurpSmartBuster main class (BurpExtender)
----------------------------------------------------------------------------------------------------------------------------------------'''
class BurpExtender(IBurpExtender, IScanIssue, IScannerCheck, IScannerInsertionPoint,IHttpListener, IBurpExtenderCallbacks, IContextMenuFactory, ITab):
# definitions
EXTENSION_NAME = "BurpSmartBuster"
AUTHOR = "@pathetiq"
def registerExtenderCallbacks(self, callbacks):
# keep a reference to our callbacks object
self._callbacks = callbacks
# obtain an extension helpers object
self._helpers = callbacks.getHelpers()
# define stdout writer
self._stdout = PrintWriter(callbacks.getStdout(), True)
print(self.EXTENSION_NAME + ' by ' + self.AUTHOR)
print('================================')
print('This extension will create new requests for ALL "in scope" HTTP request made through Burp. Make sure to filter scope items')
print('For help or any information see the github page or contact the author on twitter.')
print('Note: The Spider currently only supports English, see author github page for new language installation instructions')
# set our extension name
callbacks.setExtensionName(self.EXTENSION_NAME)
callbacks.registerScannerCheck(self)
callbacks.registerHttpListener(self)
callbacks.registerContextMenuFactory(self)
#Initialize tab details
#fields of options setBounds(x,y,width,heigth)
self.verboseLabel = JLabel("Verbose")
self.verboseLabel.setBounds(10,10,130,30)
self.yesVerboseButton = JRadioButton("Yes")
self.yesVerboseButton.setSelected(True)
self.yesVerboseButton.setBounds(10,40,50,30)
self.noVerboseButton = JRadioButton("No")
self.noVerboseButton.setBounds(70,40,50,30)
self.buttonGroup = ButtonGroup()
self.buttonGroup.add(self.yesVerboseButton)
self.buttonGroup.add(self.noVerboseButton)
self.spiderPagesLabel = JLabel("Spider: Nbr of pages")
self.spiderPagesLabel.setBounds(10,70,200,30)
self.spiderPagesTextField = JTextField(300)
self.spiderPagesTextField.setText("5")
self.spiderPagesTextField.setBounds(10,100,300,30)
self.spiderPagesTextField.setPreferredSize( Dimension( 250, 20 ) )
self.spiderRecPagesLabel = JLabel("Recursive: Nbr of pages")
self.spiderRecPagesLabel.setBounds(10,130,250,30)
self.spiderRecPagesTextField = JTextField(300)
self.spiderRecPagesTextField.setText("3")
self.spiderRecPagesTextField.setBounds(10,160,300,30)
self.spiderRecPagesTextField.setPreferredSize( Dimension( 250, 20 ) )
self.fileTypeLabel = JLabel("Ignore Filetypes")
self.fileTypeLabel.setBounds(10,190,130,30)
self.fileTypeTextField = JTextField(300)
self.fileTypeTextField.setText("gif,jpg,png,css,js,ico,woff")
self.fileTypeTextField.setBounds(10,220,300,30)
self.fileTypeTextField.setPreferredSize( Dimension( 250, 20 ) )
self.inScopeLabel = JLabel("Scan in-scope URLs only?")
self.inScopeLabel.setBounds(10,250,200 ,30)
self.yesInScopeButton = JRadioButton("Yes")
self.yesInScopeButton.setBounds(10,280,50,30)
self.yesInScopeButton.setSelected(True)
self.noInScopeButton = JRadioButton("No")
self.noInScopeButton.setBounds(70,280,50,30)
self.buttonGroup1 = ButtonGroup()
self.buttonGroup1.add(self.yesInScopeButton)
self.buttonGroup1.add(self.noInScopeButton)
self.refreshConfigButton = JButton("Update Configuration", actionPerformed=self.updateConfig)
self.refreshConfigButton.setBounds(10,310,200,30)
#Jlist to contain the results
self.list = JList([])
self.list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
self.list.setLayoutOrientation(JList.VERTICAL)
self.list.setVisibleRowCount(-1)
self.listScroller = JScrollPane(self.list,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
self.listScroller.setBounds(510,40,500,500)
#self.listScroller.setPreferredSize(Dimension(400, 500))
self.urlFoundLabel = JLabel("URLs Found")
self.urlFoundLabel.setBounds(510,10,130,30)
self.listScroller.setPreferredSize(Dimension(500, 100))
self.listScroller.setViewportView(self.list)
self.clearListButton = JButton("Clear list", actionPerformed=self.clearList)
self.clearListButton.setBounds(350,40,150,30)
self.copyListButton = JButton("Copy Selected", actionPerformed=self.copyList)
self.copyListButton.setBounds(350,70,150,30)
self.deleteListButton = JButton("Delete Selected", actionPerformed=self.deleteSelected)
self.deleteListButton.setBounds(350,100,150,30)
self.exportListButton = JButton("Export list", actionPerformed=self.exportList)
self.exportListButton.setBounds(350,130,150,30)
#main panel
self.mainpanel = JPanel()
self.mainpanel.setLayout(None)
self.mainpanel.add(self.verboseLabel)
self.mainpanel.add(self.yesVerboseButton)
self.mainpanel.add(self.noVerboseButton)
self.mainpanel.add(self.spiderPagesLabel)
self.mainpanel.add(self.spiderPagesTextField)
self.mainpanel.add(self.spiderRecPagesLabel)
self.mainpanel.add(self.spiderRecPagesTextField)
self.mainpanel.add(self.fileTypeLabel)
self.mainpanel.add(self.fileTypeTextField)
self.mainpanel.add(self.inScopeLabel)
self.mainpanel.add(self.yesInScopeButton)
self.mainpanel.add(self.noInScopeButton)
self.mainpanel.add(self.refreshConfigButton)
self.mainpanel.add(self.urlFoundLabel)
self.mainpanel.add(self.listScroller)
self.mainpanel.add(self.clearListButton)
self.mainpanel.add(self.copyListButton)
self.mainpanel.add(self.deleteListButton)
self.mainpanel.add(self.exportListButton)
callbacks.customizeUiComponent(self.mainpanel)
callbacks.addSuiteTab(self)
#set default config file name and values
#only smart is use, keeping other for future development
self._configSmart_Local = False
self._configSmart_Smart = True
self._configSmart_File = False
self._configSmart_Spider = False
self._trailingSlash = True
#To be fetch from the UI settings
self._configSpider_NumberOfPages = 5
self._verbose = False
self._ignoreFileType = ["gif","jpg","png","css","js","ico","woff"]
#keeping to use it
self._configInScope_only = True
self._configSpider_NumberOfPages = 5
#Get a logger object for logging into file
loggerTemp = Logger(self.EXTENSION_NAME,logging.DEBUG)
self._logger= loggerTemp.getLogger()
#get the config file, will overwrite default config if the ini file is different
#self.getSmartConfiguration()
#get config from the UI
self.updateConfig("")
#words gather on the page from the spidering
self._words = {}
self._mergedWords = {}
#robots.txt list
self._robots = {}
self._robotsScanned = {}
#sitemap.xml list
self._sitemap = {}
#url in comments
self._urlsInComment = {}
#domain names to query current url/path/files for hidden items
self._smartDomain = {}
#sitemap and robots scanned once
self._siteRobotScanned = {}
#Load our BSB json data
self._jsonFile = "data.json"
jsonfile = open(self._jsonFile)
self._parsed_json = json.load(jsonfile)
jsonfile.close()
#define the request object to use each time we need to call a URL
self._requestor = Requestor(self._logger,self)
#Variable to define if unique data has already been grabbed
self._smartRequestData = {}
self._smartRequestPath = {}
self._smartRequestFiles = {}
#number of time the spider have run
self._spiderRan = {} #Array of domain. If domain exist. Spider did ran!
return
'''
Graphic Functions
'''
def createMenuItems(self, contextMenuInvocation):
self._contextMenuData = contextMenuInvocation.getSelectedMessages()
menu_list = ArrayList()
menu_list.add(JMenuItem("Send to BurpSmartBuster",actionPerformed=self.menuItemClicked))
return menu_list
def menuItemClicked(self, event):
data = self.getURLdata(self._contextMenuData[0],True)
self._logger.info("SMARTREQUEST FOR: "+data.getUrl().toString())
self._logger.debug("Executing: smartRequest() from menuItemClicked")
thread = threading.Thread(
target=self.smartRequest,
name="Thread-smartRequest",
args=[data],)
thread.start()
# Implement ITab
def getTabCaption(self):
return self.EXTENSION_NAME
# Return our panel and button we setup. Components of our extension's tab
def getUiComponent(self):
return self.mainpanel
'''------------------------------------------------
Extension Unloaded
------------------------------------------------'''
def extensionUnloaded(self):
self._logger.info("Extension was unloaded")
return
'''------------------------------------------------
VERBOSE FUNCTION
Display each tested URL
------------------------------------------------'''
def verbose(self,text):
#Is verbose on or off from config file?
if self._verbose == True:
print "[VERBOSE]: "+text
return
'''------------------------------------------------
GRAPHICAL FUNCTIONS for BUTTONS
------------------------------------------------'''
def getRecursiveConfig(self):
return int(self.spiderRecPagesTextField.getText())
#refresh the config from the UI
def updateConfig(self,meh):
self._configSpider_NumberOfPages = int(self.spiderPagesTextField.getText())
if self.yesVerboseButton.isSelected():
self._verbose = True
else:
self._verbose = False
if self.yesInScopeButton.isSelected():
self._configInScope_only = True
else:
self._configInScope_only = False
fileType = []
fileTypeStr = self.fileTypeTextField.getText()
self._ignoreFileType = self.fileTypeTextField.getText().split(",")
self._logger.info("Config changed: " + "spiderNbrPages=" + str(self._configSpider_NumberOfPages) + ", Verbose is:" + str(self._verbose) + ", InScope is:" + str(self._configInScope_only) + ", fileTypeIgnored: " + str(self._ignoreFileType))
print "Now using config: " + "spiderNbrPages=" + str(self._configSpider_NumberOfPages) + ", Verbose is:" + str(self._verbose) + ", InScope is:" + str(self._configInScope_only) + ", fileTypeIgnored: " + str(self._ignoreFileType)
return
#add a URL to the list
def addURL(self,url):
list = self.getListData()
list.append(url)
self.list.setListData(list)
return
#return the who list
def getListData(self):
list = []
for i in range(0, self.list.getModel().getSize()):
list.append(self.list.getModel().getElementAt(i))
return list
#Clear the list
def clearList(self,meh):
self.list.setListData([])
return
#Copy to clipboard
def copyList(self,meh):
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
list = self.getListData()
selected = self.list.getSelectedIndices().tolist()
copied = ""
urls = ""
for i in selected:
url = str(list[i]).split(',')[0]
urls = urls+str(url)+"\n"
clipboard.setContents(StringSelection(urls), None)
return
#Delete selected item from the list
def deleteSelected(self,meh):
x = self.list.getSelectedIndices().tolist()
list = self.getListData()
for i in reversed(x):
del list[i]
self.list.setListData(list)
return
#TODO: save as the list
def exportList(self,meh):
fd = JFileChooser()
dialog = fd.showDialog(self.mainpanel, "Save List As")
dataList = self.getListData()
urls = ""
if dialog == JFileChooser.APPROVE_OPTION:
file = fd.getSelectedFile()
path = file.getCanonicalPath()
try:
with open(path, 'w') as exportFile:
for item in dataList:
url = str(item).split(',')[0]
exportFile.write(url+"\n")
except IOError as e:
print "Error exporting list: " + str(e)
self._logger.debug("Error exporting list to: " + path + ", Error: " + str(e))
return
'''------------------------------------------------------------------------------------------------
MAIN FUNCTION / WHERE EVERYTHING STARTS
For every request which isn't created from the Extender(this might have to be change)
The request is analyse and related to the config options new request are create to test if
specific files/paths/directories exists.
------------------------------------------------------------------------------------------------'''
def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): #IHttpRequestResponse message info
#TODO: not from repeater and intruder --> set in ini file too! --> and toolFlag != self._callbacks.TOOL_EXTENDER
#This is required to not LOOP Forever as our plugin generate requests!
if toolFlag == self._callbacks.TOOL_PROXY and toolFlag != self._callbacks.TOOL_EXTENDER and toolFlag != self._callbacks.TOOL_SCANNER:
#Get an Urldata object to use later
data = self.getURLdata(messageInfo,messageIsRequest)
#VERIFICATION: if URL is in scope we do scan
if not self._callbacks.isInScope(data.getUrl()):
#self._callbacks.includeInScope(url)
self._logger.info("URL not in scope: " + data.getUrl().toString())
return
if messageIsRequest:
self._logger.debug("Entering: processHttpMessage() REQUEST")
self._logger.debug("Request from domain: "+data.getDomain())
#REJECT specific extension on request
if data.getFileExt() in self._ignoreFileType:
self._logger.info("FILETYPE IGNORED: " + data.getUrl().toString())
return
###############################################
# Decide which mode to use based on ini config
###############################################
#from browsed file only
if self._configSmart_Smart:
self._logger.info("SMARTREQUEST FOR: "+data.getUrl().toString())
self._logger.debug("Executing: smartRequest()")
thread = threading.Thread(
target=self.smartRequest,
name="Thread-smartRequest",
args=[data],
)
thread.start()
thread.join()
#wordlist adjust with the domain name
elif self._configSmart_Local:
self._logger.debug("Executing: localRequest()")
self.localRequest(data)
#your own wordlist, no smart here
elif self._configSmart_File:
self._logger.debug("Executing: fileRequest()")
self.fileRequest(data)
#spidered items only. Like smart but it browse for you.
elif self._configSmart_Spider:
self._logger.debug("Executing: spiderRequest()")
self.spiderRequest(data)
else: #if response
self._logger.debug("Entering: processHttpMessage() RESPONSE")
###############################################
# Decide which mode to use based on ini config
###############################################
#VERIFICATION: if URL is in scope we do scan
#if not self._callbacks.isInScope(data.getUrl()):
# #self._callbacks.includeInScope(url)
# self._logger.info("URL %s not in scope: " % data.getUrl())
# return
#from browsed file only
#TODO: sniff JS and CSS file for URLS
#if self._configSmart_Smart:
self._logger.debug("Executing: getUrlInComments()")
thread = threading.Thread(
target=self.getUrlInComments,
name="Thread-getUrlInComments",
args=[data],
)
thread.start()
thread.join()
return
'''----------------------------------------------------------------------------------------------------------
BurpSmartBuster main class (BurpExtender)
Only spidering to gather the more page and test those
----------------------------------------------------------------------------------------------------------'''
def spiderRequest(self, data):
return
'''----------------------------------------------------------------------------------------------------------
Use BSB files on all visited page
----------------------------------------------------------------------------------------------------------'''
def localRequest(self, data):
return
'''----------------------------------------------------------------------------------------------------------
Use user supply file on all visited page
----------------------------------------------------------------------------------------------------------'''
def fileRequest(self, data):
return
'''----------------------------------------------------------------------------------------------------------
Use the logic, based on the BSB files and data from the website
This is where all the magic happens.
We want to :
- Call some file extension for the file we browsed to
-TODO: Get a huge list
- Extension
- User file, windows, linux, osx
- Call some path when browsing a new path (even when it is a file)
- default path list
- Call some files when browsing a new path
- user files windows, osx, linux
- backup list
- autosave list
- svn, git list
- CMS
- Web server, etc.
- Get robots.txt and sitemap data
- Brute force up to 2 or 3 letters of files names and path on all found path which is not cms/git/etc.
- Future version: Parse HTML comments for path
- If they exist, we add them to XXX?
- If new path exists, let's go recursive (new class?)
- If file exists: add to sitemap + verbose + log
@param data: UrlData object containing all information about the URL
----------------------------------------------------------------------------------------------------------'''
def smartRequest(self,data):
#Current request variables
domain = data.getDomain()
url = data.getUrl()
##################### FETCH DATA ###############################
# Gather smart data once before sending requests
################################################################
self._logger.debug("Has the Data been gathered for? : "+ str(url))
if domain not in self._smartRequestData:
try:
self._smartRequestData[domain] = True
self._logger.debug("no")
self._logger.info("Fetching data for: "+ domain)
print "getting data for:" + str(url)
self.getSmartData(data)
except Exception as e:
print "exception:"+ e
self._smartRequestData[domain] = False
return False
else:
self._logger.debug("yes")
# Execution of request with the received data:
# - spider
# - sitemap
# - robots
# - current directories
# - commentsInUrl
# json data:
# - extension files
# - common basic cms files
# - common server files
# - common user files
# - common test files
# - common repositories files
# -
# -
'''
For the current directories (path)
- Test a path/file for a category of path/files
- If a tested path/files exist (200/401/403/500) scan other files + - add to sitemap and LOG + add issues?
- If not skip it
- go 3 deep max and retest all
TODO future version:
Pseudo algo:
Si le present url est un fichier:
- Si c'Est un fichier php... tester phps extension.
- si c'Est un fichier asmx, tester les wsdl
Si c'Est un path:
- si ca inclus un path dans sharepoint, tester les sharepoints
- si ca inclus un fichier de wordpress ou drupal, tester quelques fichiers cms
- Si on trouve un répertoire de type X, effectuer une recherche sur les fichiers de type X dans le repertoire trouvé
'''
#Current request data
baseUrl = data.getBaseUrl()
path = data.getPath()
filename = data.getFilename()
extension = data.getFileExt()
print "CURRENT FILE: " + baseUrl + "," + filename + "," + extension
#data.json sections: extensions, fileprefix, filesuffix, files, directories
#test local file
#if current url is a file: test extentions + intelligent details
#AND we test current file with prefix and suffix
#testing directories
#if current URL have some directories test them out
#Test them with FILES and DIRECTORIES. Including the current directory (last in path)
#with the smart data test robots path and files
#test N url from sitemap
#in current paths test files and path using domainname and domain without the tld
#with filename generated + extensions and path/filenamegenerated
'''
print "EXTENSIONS"
for extension in self._parsed_json["extensions"]:
print extension["name"]
print "SUFFIX PREFIX"
for prefix in self._parsed_json["fileprefix"]:
print prefix["name"]
for suffix in self._parsed_json["filesuffix"]:
print suffix["name"]
print "FILES"
for files in self._parsed_json["files"]:
print files["name"]
'''
print "DIRECTORIES"
#Directories data information
directories = data.getDirectories()
directory = "/"
slash = "" #force slash or not var
#get options foir trailing slash. By default it's ON
if self._trailingSlash:
slash = "/"
##################### EXECUTE DATA.json REQUESTS ###################
# Build Request to be execute based on our data.json
# and getSmartData results
################################################################
#TODO: important put tested directories and files in a dictionnary or array
#TODO: important put tested directories and files in a dictionnary or array
#TODO: important put tested directories and files in a dictionnary or array
#TODO: important put tested directories and files in a dictionnary or arrayà
########################
# Technology scanner
########################
'''
- do a request to root dir
- get response (check for redirect)
- check headers
- check file extensions
- depending on results scan X files.
- Set current domain technologyVar to X
'''
################
#Scan the root directory!
################
print "DIR: "+str(directories)
if not directories:
directories = ["/"]
# response will be dealed in requestor
for dir in directories:
print "TESTING: " + dir
if dir == "/":
directory = "/"
else:
directory = directory+dir+"/" #test all directories: / /a/ /a/b/ /a/b/c/ ...
#call our directories inside all request directires
for dir2 in self._parsed_json["directories"]:
self.verbose("RequestDir for: "+baseUrl+directory+dir2["name"]+slash)
self._requestor.addRequest(baseUrl+directory+dir2["name"]+slash,data)
# call directories based on domain information: url/a/b/c/smartDomain , url/a/b/smartDomain/, etc.
#print "SMARTDOMAIN"+self._smartDomain
for dir2 in self._smartDomain[domain]:
self.verbose("RequestSmartDomain for: " + baseUrl + directory + dir2)
self._requestor.addRequest(baseUrl + directory + dir2,data)
#in each directory call smartDomain.extensions
for ext in self._parsed_json["extensions"]:
self.verbose("RequestSmartDomain.ext for: " + baseUrl + directory + dir2 + ext["name"])
self._requestor.addRequest(baseUrl + directory + dir2 + ext["name"],data)
#call our files in all directories
#print "parsed json"+self._parsed_json["files"]
for files in self._parsed_json["files"]:
self.verbose("RequestFile for: "+baseUrl+directory+files["name"])
self._requestor.addRequest(baseUrl+directory+files["name"],data)
################
#If URL is a file, let's try to add some extension to the file
################
if extension:
#replace current file extension for our extension
tempFilenameUrl = baseUrl+directory+filename
tempFilenameUrl1 = baseUrl+directory+filename+"."+extension
for ext in self._parsed_json["extensions"]:
self.verbose("RequestExt for: "+ tempFilenameUrl+ext["name"])
self.verbose("RequestFileExt for: "+ tempFilenameUrl1+ext["name"])
self._requestor.addRequest(tempFilenameUrl+ext["name"],data)
self._requestor.addRequest(tempFilenameUrl1+ext["name"],data)
#add a prefix to current file
tempFilenameUrl = baseUrl+directory
for prefix in self._parsed_json["fileprefix"]:
tempFilenameUrl1 = tempFilenameUrl+prefix["name"]+filename+"."+extension
self.verbose("RequestPrefix for: "+tempFilenameUrl1)
self._requestor.addRequest(tempFilenameUrl1,data)
#add suffix to current file
tempFilenameUrl = baseUrl+directory
for suffix in self._parsed_json["filesuffix"]:
tempFilenameUrl1 = tempFilenameUrl+filename+suffix["name"]+"."+extension
self.verbose("RequestSuffix for: "+tempFilenameUrl1)
self._requestor.addRequest(tempFilenameUrl1,data)
#make sure we have some data
#print "DATA RECEIVED"
#print self._words[domain]
#print self._mergedWords ##need to call the emrge function if needed
#print self._robots[domain]
#print str(len(self._sitemap[domain]))
#print str(self._urlsInComment[domain])
##################### EXECUTE SMART REQUESTS ###################
# Build Request to be execute based on our data.json
# and getSmartData results
################################################################
#list of smart directories
smartDirectories = {}
#list of smart files (add our extension to it)
smartfiles = {}
################
#Request N pages from sitemap
################
if domain not in self._siteRobotScanned: #Do it once
self._siteRobotScanned[domain] = True #done for this domain
tmpSiteMap = []
for i in range(0,self._configSpider_NumberOfPages): #get N number of pages from ini config
tmpSiteMap.append(self._sitemap[domain][i])
#Requests files and directories from robots.txt
tmpRobots = []
for line in self._robots[domain]:
#in case robots.txt use ending wildcard we remove it
if line.endswith("*"):
line = line[:-1]
#TODO: Test if directory or file is not 404 ??
tmpRobots.append(baseUrl+line)
################
# requests all value for N sitemap url
################
for link in tmpSiteMap:
if link.endswith("/"): #scan directories and files
for dir2 in self._parsed_json["directories"]:
self.verbose("RequestSiteMap dir/file for: " + link + dir2["name"] + slash)
self._requestor.addRequest(link + dir2["name"] + slash,data)
for files in self._parsed_json["files"]:
self.verbose("RequestSiteMap dir/file for: " + link + files["name"])
self._requestor.addRequest(link + files["name"],data)
else: #scan extensions and suffix/prefix
# call our files in all directories
for ext in self._parsed_json["extensions"]:
self.verbose("RequestSitemap file/ext/ext for: " + link + ext["name"])
self._requestor.addRequest(link + ext["name"],data)
#Get the file extension of the current sitemap url to replace the extension
tmpUrl = urlparse(link)
if len(tmpUrl.path.split(".")[-1:]) > 1:
newUrl = ".".join(tmpUrl.path.split(".")[:-1])+ext["name"]
self.verbose("RequestSiteMap file/ext for: " + newUrl)
self._requestor.addRequest(newUrl,data)
################
#requests all values for robots path
################
for link in tmpRobots:
tmpUrl = baseUrl + link
if link.endswith("/"): # scan directories and files
for dir2 in self._parsed_json["directories"]:
self.verbose("RequestRobots dir/file for: " + tmpUrl + dir2["name"] + slash)
self._requestor.addRequest(tmpUrl + dir2["name"] + slash,data)
for files in self._parsed_json["files"]:
self.verbose("RequestRobots dir/file for: " + tmpUrl + files["name"])
self._requestor.addRequest(tmpUrl + files["name"],data)
else:
for ext in self._parsed_json["extensions"]:
self.verbose("RequestRobots file/ext/ext for: " + tmpUrl + ext["name"])
self._requestor.addRequest(tmpUrl + ext["name"],data)
#Get the file extension of the current sitemap url to replace the extension
tmpUrl1 = urlparse(link)
if len(tmpUrl1.path.split(".")[-1:]) > 1:
newUrl = ".".join(tmpUrl1.path.split(".")[:-1])+ext["name"]
self.verbose("RequestRobots file/ext for: " + newUrl)
self._requestor.addRequest(newUrl,data)
#TODO : path and words/merge words
################
#Request from words
################
#print self._words
#TODO: loop over: sitemap (done), robots (done), words/mergedwords(fixed for textblob required), bruteforce(later) Maybe comments data?
# - add the data to our stack to request and parse by the Requestor object
# - Get current query path and files & Filter out static object from the request (images,etc.)
#filter out: gif,jpg,png,css,ico
print "Done. Waiting for more URL...!"
'''----------------------------------------------------------------------------------------------------------
Get the data for smartRequest(), it will fills our list of words which will be our smart logic data to create
multiple new HTTP requests. This data should be gather once.
----------------------------------------------------------------------------------------------------------'''
#TODO: split some of this works in different functions
def getSmartData(self, data):
################################################################
# Get the url and its data to create the new smart requests
################################################################
urlString = str(data.getUrl()) #cast to cast to stop the TYPEerror on URL()
domain = data.getDomain()
netloc = data.getNetloc()
directories = data.getDirectories()
lastDirectory = data.getLastDirectory()
params = data.getParams()
fileExt = data.getFileExt()
completeUrl = data.getCompleteURL()
baseUrl = data.getBaseUrl()
#Java URL to be used with Burp API
url = URL(urlString)
self._logger.debug("Current URLString: "+urlString)
######################### SPIDER EXECUTION #####################
# Get some words from the web page: do it once!
# Note: This step could be threaded using Queue.Queue but there is
# little advantage as we need to wait to get all the value anyway
################################################################
self._logger.debug("Has the Spider ran for? : "+ domain)
if domain not in self._spiderRan: #doing it once
self._spiderRan[domain] = True
self._logger.debug("No")
#self._mergedWords[domain] = {}
#self._words[domain] = {}
#Start URL, number of page to spider through, request class object to use
spider = Spider(data, self._configSpider_NumberOfPages, self._requestor,self._logger)
spider.runSpidering()
#Get words from the spidering
self._words[domain] = spider.getWords()
#Get merged words
#spider.mergeWords()
#self._mergedWords[domain] = spider.getMergedWords()
self._logger.debug("Length of Words: "+ str(len(self._words[domain])))
#self._logger.debug("Length of MergedWords: "+ str(len(self._mergedWords[domain])))
self._logger.info("SPIDER DONE")
else:
self._logger.debug("Yes")
################################################################
# Get robots.txt (once)
# Retrieve unique path and files from the robots.txt
################################################################
if domain not in self._robots: #do it once
print " robot "
#get the file
queueRobot = Queue.Queue(1)
self._logger.info("robot")
thread = threading.Thread(
target=self._requestor.runRequest,
name="Thread-Robots",
args=[baseUrl+"/robots.txt", queueRobot],
)
thread.start()
thread.join()
response = queueRobot.get()
#Parse the file for disallow lines
robotList = []
for item in response.content.split('\n'):
if item:
i = item.split(':')
if i[0].lower() == "disallow" and i[1] not in robotList:
robotList.append(i[1])
#add to domain list