- Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathSQLTruncScanner.py
More file actions
Latest commit
351 lines (301 loc) · 14.3 KB
/
Copy pathSQLTruncScanner.py
File metadata and controls
351 lines (301 loc) · 14.3 KB
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
#
# BurpSQLTruncationScanner - Scan for potential SQL truncation attack vectors.
#
# Copyright (c) 2020 Frans Hendrik Botes (InitRoot)
# Verions 0.1
#
fromburpimportIBurpExtender, IScannerCheck, IScanIssue, ITab, IBurpExtenderCallbacks, IExtensionHelpers, IContextMenuFactory, IContextMenuInvocation, IHttpRequestResponse
fromjava.ioimportPrintWriter
fromjava.netimportURL
fromjava.utilimportArrayList, List
fromjava.util.regeximportMatcher, Pattern
importbinascii
fromjavaximportswing
fromjava.awtimportFont, Color
importsys
importtime
importthreading
importbase64
importre
fromarrayimportarray
importjson
#Global Issue List
issueList=ArrayList()
classBurpExtender(IBurpExtender, IScannerCheck, IContextMenuFactory, IHttpRequestResponse, IBurpExtenderCallbacks):
defregisterExtenderCallbacks(self, callbacks):
sys.stdout=callbacks.getStdout()
self._callbacks=callbacks
self._helpers=callbacks.getHelpers()
callbacks.setExtensionName("SQLTruncScanner")
callbacks.issueAlert("SQL Truncation Scanner Enabled")
stdout=PrintWriter(callbacks.getStdout(), True)
stderr=PrintWriter(callbacks.getStderr(), True)
callbacks.registerContextMenuFactory(self)
print ("SQL Truncation Scanner loaded.")
print ("Copyright (c) 2020 Frans Hendrik Botes (InitRoot)")
self.httpTraffic=None
self.resp=None
#Set Parameters for Original Reqquest to Restruct
self.orgHost=None
self.orgPort=None
self.orgProtoChoice=None
self.orgHeaders=None
self.orgParams=None
self.orgMethod=None
self.orgURLPath=None
self.orgContType=None
self.orgBaseline=None
#Create context menu entry
defcreateMenuItems(self, invocation):
self.context=invocation
itemContext=invocation.getSelectedMessages()
ifitemContext>0:
menuList=ArrayList()
menuItem=swing.JMenuItem(
"Scan with SQLTruncScanner", None, actionPerformed=self.start_scan)
menuList.add(menuItem)
returnmenuList
returnNone
# We are ready to start a scan for the specific request
defstart_scan(self, event):
try:
#For later use lets get what user selected.
#Let's get what the user selected, only compatible with one item at a time. ADD check for multiple items and throw error
scanIssues=self._callbacks.getScanIssues(None)
httpTraffic=self.context.getSelectedMessages()
print (len(httpTraffic))
httpRequest= [item.request.tostring()
foriteminhttpTraffic]
orignalRequest=''.join(httpRequest)
#Rebuild the request and fetch response to calculate baseline value
self.buildRequest(orignalRequest, httpTraffic)
#We have the baseline, time to start fuzzing
paramFuzzer=fuzzParams(httpTraffic, self._helpers, self._callbacks)
thread=threading.Thread(target=paramFuzzer.fuzzParams(self.orgHost, self.orgPort, self.orgProtoChoice,
self.orgHeaders, self.orgParams, self.orgMethod, self.orgURLPath, self.orgContType, self.orgBaseline), args=())
thread.daemon=True
thread.start()
print (str(len(issueList)))
# issue = ScanIssue(httpTraffic[0], self._helpers)
#self._callbacks.addScanIssue(issue)
#paramFuzzer.fuzzParams(self.orgHost,self.orgPort,self.orgProtoChoice,self.orgHeaders,self.orgParams,self.orgMethod,self.orgURLPath,self.orgContType,self.orgBaseline)
exceptUnicodeEncodeError:
print("Error in URL decode.")
returnNone
defbuildRequest(self, strRequest, httpTraffMsg):
stdout=PrintWriter(self._callbacks.getStdout(), True)
strorignalRequest=strRequest
#Get data about the request that was right clicked
foriteminhttpTraffMsg:
try:
httpService=item.getHttpService()
self.httpTraffic=httpService
host=httpService.host
port=httpService.port
protocol=httpService.protocol
protoChoice=Trueifprotocol.lower() =='https'elseFalse
#Parse the text area that should contain an HTTP request.
requestInfo=self._helpers.analyzeRequest(strorignalRequest)
#Request data
headers=requestInfo.getHeaders()
bodyOffset=requestInfo.bodyOffset
body=strorignalRequest[bodyOffset:]
for (i, header) inenumerate(headers):
ifheader.lower().startswith("content-type:"):
content_type=header.split(":")[1].lower().strip()
method=headers[0].split(" ")[0]
urlpath=headers[0].split(" ")[1]
#Debugging area for output and parsing
#stdout.println(str(body))
#stdout.println(str(headers))
#stdout.println(str(method))
#stdout.println(str(content_type))
#stdout.println(str(urlpath))
#Identify and parse parameters in the request
ifmethod=="GET":
stdout.println("[!] GET REQUEST IDENTIFIED")
body=urlpath.split("?")[1]
#print(body)
params=dict(x.split('=') forxinbody.split('&'))
else:
#Add logic here for the handling parameters in body and JSON content
if"json"instr(content_type) or"JSON"instr(content_type):
stdout.println("[!] JSON REQUEST IDENTIFIED")
#print(body)
#print("[!] BODY DONE")
params=json.loads(body)
#print(body)
#print(params)
else:
stdout.println("[!] POST REQUEST IDENTIFIED")
#print(body)
params=dict(x.split('=') forxinbody.split('&'))
#print(params)
stdout.println("[!] PARAMETERS IDENTIFIED!")
stdout.println(params)
stdout.println("[!] DETERMINING BASELINE")
baselineInt=self.baseline(host, port, protoChoice, headers, params, method, urlpath, content_type)
#Assign Parameters for Fuzzing
self.orgHost=host
self.orgPort=port
self.orgProtoChoice=protoChoice
self.orgHeaders=headers
self.orgParams=params
self.orgMethod=method
self.orgURLPath=urlpath
self.orgContType=content_type
self.orgBaseline=baselineInt
exceptExceptionasex:
stdout.println("Problem parsing the request data"+"\n")
stdout.println(ex)
return
defconsolidateDuplicateIssues(self, existingIssue, newIssue):
if (existingIssue.getIssueName() ==newIssue.getIssueName()):
return-1
else:
return0
defextensionUnloaded(self):
print"SQL Truncation Scanner unloaded"
return
defpostRequest(self, headers, body, args_):
#Needed: args=[host,port,protoChoice,request]
stdout=PrintWriter(self._callbacks.getStdout(), True)
request=self._helpers.buildHttpMessage(headers, body)
args_.append(request)
t=threading.Thread(target=self.makeRequest, args=args_)
t.daemon=True
t.start()
t.join()
defmakeRequest(self, host, port, protoChoice, request):
stdout=PrintWriter(self._callbacks.getStdout(), True)
try:
self.resp=self._callbacks.makeHttpRequest(
host,
port,
protoChoice,
request
)
exceptExceptionasex:
stdout.println(ex)
defbaseline(self, host, port, protoChoice, headers, body, method, urlpath, content_type):
if"json"notincontent_type.lower():
new_body=""
new_body+='&'.join("%s=%s"% (key, str(val)) for (key, val) inbody.iteritems())
#print(new_body)
ifmethod=="GET":
url1=urlpath.split("?")[0]
url2="?"+str(new_body)
headers[0] ="GET "+str(url1) +str(url2) +" HTTP/1.1"
self.getRequest(headers, [host, port, protoChoice])
else:
self.postRequest(headers, new_body, [host, port, protoChoice])
#Here we take the lengh and status code of the body returned as a baseline
originalReq=self._helpers.analyzeRequest(self.resp)
reqResponse=self._helpers.analyzeResponse(self.resp)
reqRespTxt=self.resp.tostring()
respStatusCode=reqResponse.getStatusCode()
resbodyOffset=reqResponse.getBodyOffset()
respbodyLen=len(reqRespTxt[resbodyOffset:])
baselineData=str(respStatusCode) +str(respbodyLen)
print(baselineData)
returnbaselineData
classfuzzParams():
def__init__(self, reqres, helpers, callbacks):
self.helpers=helpers
self.reqres=reqres
self.callbacks=callbacks
defpostRequest(self, headers, body, args_):
#Needed: args=[host,port,protoChoice,request]
stdout=PrintWriter(self.callbacks.getStdout(), True)
request=self.helpers.buildHttpMessage(headers, body)
args_.append(request)
t=threading.Thread(target=self.makeRequest, args=args_)
t.daemon=True
t.start()
t.join()
defmakeRequest(self, host, port, protoChoice, request):
stdout=PrintWriter(self.callbacks.getStdout(), True)
try:
self.resp=self.callbacks.makeHttpRequest(
host,
port,
protoChoice,
request
)
exceptExceptionasex:
stdout.println(ex)
deffuzzParams(self, host, port, protoChoice, headers, body, method, urlpath, content_type, baseline):
stdout=PrintWriter(self.callbacks.getStdout(), True)
stdout.println("[!] FUZZING "+str(len(body)) +" PARAMETERS")
issueList.clear()
payloadSet= {"5": ' 00', "10": ' 00', "15": ' 00', "20": ' 00', "30": ' 00', "40": ' 00'}
#Let's loop through each parameter
forparaminbody:
stdout.println(" [-] FUZZING: "+str(param))
fuzzParameter=str(param)
forpayLSDinpayloadSet:
stdout.println(" [-] PAYLOAD: "+payLSD)
payload=payloadSet[payLSD]
bodd=body
bodd[fuzzParameter] =bodd[fuzzParameter] +payload
if"json"notincontent_type.lower():
new_body=""
new_body+='&'.join("%s=%s"% (key, str(val))
for (key, val) inbodd.iteritems())
#print(" " + new_body)
ifmethod=="GET":
url1=urlpath.split("?")[0]
url2="?"+str(new_body)
headers[0] ="GET "+str(url1) +str(url2) +" HTTP/1.1"
self.getRequest(headers, [host, port, protoChoice])
else:
self.postRequest(headers, new_body, [host, port, protoChoice])
#Here we take the lengh and status code of the body returned as a baseline
reqFuzzResponse=self.helpers.analyzeResponse(self.resp)
reqFuzzReq=self.helpers.analyzeRequest(self.resp)
reqFuzzRespTxt=self.resp.tostring()
respFuzzStatusCode=reqFuzzResponse.getStatusCode()
resFuzzbodyOffset=reqFuzzResponse.getBodyOffset()
respFuzzbodyLen=len(reqFuzzRespTxt[resFuzzbodyOffset:])
fuzzResponseData=str(respFuzzStatusCode) +str(respFuzzbodyLen)
print(" "+fuzzResponseData)
iffuzzResponseData!=baseline:
stdout.println(" [+] POSSIBLE INJECTION DETECTED")
issue=ScanIssue(
self.reqres[0], reqFuzzReq, "SQL Truncation Scanner", fuzzParameter+" | "+payLSD, "High")
self.callbacks.addScanIssue(issue)
return
## Implement the IScanIssue interface
classScanIssue(IScanIssue):
def__init__(self, httpService, httpMessages, name, detail, severity):
self._httpService=httpService
self._httpMessages=httpMessages
self._name=name
self._detail=detail+'<br/><br/><div style="font-size:8px">'\
'This issue was reported by SQL '\
'Truncation Scanner</div>'
self._severity=severity
defgetUrl(self):
returnself._httpService.getUrl()
defgetIssueName(self):
returnself._name
defgetIssueType(self):
return0x08000000# See http:#portswigger.net/burp/help/scanner_issuetypes.html
defgetSeverity(self):
returnself._severity
defgetConfidence(self):
return"Certain"
defgetIssueBackground(self):
return ("SQL Truncation can occur with mySQL databases whenever the parameter received exceeds the column length in the database. The scanner initiates a baseline scan which is then compared to a fuzzing scanner for each parameter. Each time the length of overflow is extented up until 40 characters.")
defgetRemediationBackground(self):
pass
defgetIssueDetail(self):
returnself._detail
defgetRemediationDetail(self):
pass
defgetHttpMessages(self):
#print ("................raising issue................")
rra= [self._httpService]
returnrra
defgetHttpService(self):
returnself._httpService.getHttpService()