forked from luh2/DetectDynamicJS
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDetectDynamicJS.py
More file actions
Latest commit
389 lines (338 loc) · 16.4 KB
/
Copy pathDetectDynamicJS.py
File metadata and controls
389 lines (338 loc) · 16.4 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
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
# -*- coding: utf-8 -*-
# Burp DetectDynamicJS Extension
# Copyright (c) 2015, 2016 Veit Hailperin (scip AG), 2017, 2018 Veit Hailperin
# This extension is supposed to help detecting dynamic js files, to look
# for state-dependency.
# 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/>.
try:
fromburpimportIBurpExtender
fromburpimportIScannerCheck
fromburpimportIExtensionStateListener
fromburpimportIHttpRequestResponse
fromburpimportIScanIssue
fromarrayimportarray
fromtimeimportsleep
importdifflib
exceptImportError:
print"Failed to load dependencies. This issue maybe caused by using an unstable Jython version."
VERSION='0.9'
VERSIONNAME='Buddy Holly'
classBurpExtender(IBurpExtender, IScannerCheck, IExtensionStateListener, IHttpRequestResponse):
defregisterExtenderCallbacks(self, callbacks):
print"Loading..."
self._callbacks=callbacks
self._callbacks.setExtensionName('Detect Dynamic JS')
self._callbacks.registerScannerCheck(self)
self._callbacks.registerExtensionStateListener(self)
self._helpers=callbacks.getHelpers()
# Define some constants
self.validStatusCodes= [200]
self.ifields= ['cookie', 'authorization']
self.possibleFileEndings= ["js", "jsp", "json"]
self.possibleContentTypes= [
"javascript", "ecmascript", "jscript", "json"]
self.ichars= ['{', '<']
print"Loaded Detect Dynamic JS v%s (%s)!"% (VERSION, VERSIONNAME)
return
defextensionUnloaded(self):
print"Unloaded"
return
defdoActiveScan(self, baseRequestResponse, insertionPoint):
return []
defdoPassiveScan(self, baseRequestResponse):
# WARNING: NOT REALLY A PASSIVE SCAN!
# doPassiveScan issues 1 request if simply dynamic JS
# 2 requests if generically dynamic
# 3 requests if it was a POST that works as GET
# per request scanned
# This is, because the insertionPoint idea doesn't work well
# for this test.
scan_issues= []
ifnotself.isGet(baseRequestResponse.getRequest()):
baseRequestResponse=self.switchMethod(baseRequestResponse)
if (notself.isScannableRequest(baseRequestResponse) or
notself.isScript(baseRequestResponse) or
self.isProtected(baseRequestResponse)):
returnNone
newRequestResponse=self.sendUnauthenticatedRequest(baseRequestResponse)
issue=self.compareResponses(newRequestResponse, baseRequestResponse)
ifnotissue:
returnNone
# If response is script, check if script is dynamic
ifself.isScript(newRequestResponse):
# sleep, in case this is a generically time stamped script
sleep(1)
secondRequestResponse=self.sendUnauthenticatedRequest(baseRequestResponse)
isDynamic=self.compareResponses(secondRequestResponse, newRequestResponse)
ifisDynamic:
issue=self.reportDynamicOnly(newRequestResponse, baseRequestResponse,
secondRequestResponse)
scan_issues.append(issue)
returnscan_issues
defsendUnauthenticatedRequest(self, requestResponse):
"""
Send the request without ambient authority information
requestResponse: The request to send again
returns a requestResponse
"""
newRequest=self.stripAuthenticationCharacteristics(requestResponse)
returnself._callbacks.makeHttpRequest(requestResponse.getHttpService(), newRequest)
defisGet(self, request):
"""
Check whether the request method is GET
"""
requestInfo=self._helpers.analyzeRequest(request)
returnrequestInfo.getMethod() =="GET"
defswitchMethod(self, requestResponse):
"""
Turn POST into GET
"""
newRequest=self._helpers.toggleRequestMethod(
requestResponse.getRequest())
newRequestResponse=self._callbacks.makeHttpRequest(
requestResponse.getHttpService(), newRequest)
returnnewRequestResponse
defisProtected(self, requestResponse):
"""
Checks for common protection mechanisms
"""
response=requestResponse.getResponse()
responseInfo=self._helpers.analyzeResponse(response)
body=response.tostring()[responseInfo.getBodyOffset():]
returnany([self.isThrowProtected(body), self.isCloseParenthesisProtected(body),
self.isInfiniteLoopProtected(body)])
defisThrowProtected(self, responseBody):
"""
Checks for common DWR XSSI protection method
"""
returnresponseBody.startswith("throw 'allowScriptTagRemoting is false.';")
defisCloseParenthesisProtected(self, responseBody):
"""
Checks for common Google Defense
"""
returnresponseBody.startswith(")]}'")
defisInfiniteLoopProtected(self, responseBody):
"""
Checks wether the response is protected by a while(1); statement
"""
returnresponseBody.startswith("while(1);")
defisScannableRequest(self, requestResponse):
"""
Checks whether the given request is actually of interest to this scanner
module.
requestResponse: The request to evaluate
"""
response=requestResponse.getResponse()
responseInfo=self._helpers.analyzeResponse(response)
return (self.hasValidStatusCode(responseInfo.getStatusCode()) and
self.hasAuthenticationCharacteristic(requestResponse))
defhasValidStatusCode(self, statusCode):
"""
Checks the status code of the request
"""
returnstatusCodeinself.validStatusCodes
defhasAuthenticationCharacteristic(self, requestResponse):
"""
Detects whether the request contains some kind of authentication
information.
"""
reqHeaders=self._helpers.analyzeRequest(requestResponse).getHeaders()
hfields= [h.split(':')[0] forhinreqHeaders]
returnany(hforhinself.ifieldsifhnotinstr(hfields).lower())
defstripAuthenticationCharacteristics(self, requestResponse):
"""
Strip possible ambient authority information.
"""
reqHeaders=self._helpers.analyzeRequest(requestResponse).getHeaders()
newHeaders= []
forheaderinreqHeaders:
headerName=header.split(':')[0].lower()
ifheaderNamenotinself.ifields:
newHeaders.append(header)
returnself._helpers.buildHttpMessage(newHeaders, None)
defhasBody(self, response):
"""
Checks whether the response contains a body
"""
responseInfo=self._helpers.analyzeResponse(response)
body=response[responseInfo.getBodyOffset():]
returnlen(body) >0
defhasScriptFileEnding(self, requestResponse):
"""
Checks for common script file endings
"""
url=self._helpers.analyzeRequest(requestResponse).getUrl()
fileEnding=".totallynotit"
urlSplit=str(url).split("/")
iflen(urlSplit) !=0:
fileName=urlSplit[len(urlSplit) -1]
fileNameSplit=fileName.split(".")
fileEnding=fileNameSplit[len(fileNameSplit) -1]
fileEnding=fileEnding.split("?")[0]
returnany(fileEndinfileEndingforfileEndinself.possibleFileEndings)
defhasScriptContentType(self, response):
""" Checks for common content types, that could be scripts """
responseInfo=self._helpers.analyzeResponse(response)
headers=responseInfo.getHeaders()
contentType=""
contentTypeL= [xforxinheadersif"content-type:"inx.lower()]
iflen(contentTypeL) ==1:
contentType=contentTypeL[0].lower()
returnany(contentincontentTypeforcontentinself.possibleContentTypes)
defisScript(self, requestResponse):
"""Determine if the response is a script"""
try:
response=requestResponse.getResponse()
except:
returnFalse
ifnotself.hasBody(response):
returnFalse
responseInfo=self._helpers.analyzeResponse(response)
body=response.tostring()[responseInfo.getBodyOffset():]
first_char=body[0:1]
mimeType=responseInfo.getStatedMimeType().split(';')[0]
inferredMimeType=responseInfo.getInferredMimeType().split(';')[0]
return (first_charnotinself.icharsand
("script"inmimeTypeor"script"ininferredMimeTypeor
self.hasScriptFileEnding(requestResponse) orself.hasScriptContentType(response)))
defcompareResponses(self, newRequestResponse, oldRequestResponse):
"""Compare two responses in respect to their body contents"""
result=None
nResponse=newRequestResponse.getResponse()
ifnResponseisNone:
returnresult
nResponseInfo=self._helpers.analyzeResponse(nResponse)
# Only considering non-cached HTTP responses
ifnResponseInfo.getStatusCode() ==304:
returnresult
nBodyOffset=nResponseInfo.getBodyOffset()
nBody=nResponse.tostring()[nBodyOffset:]
oResponse=oldRequestResponse.getResponse()
oResponseInfo=self._helpers.analyzeResponse(oResponse)
oBodyOffset=oResponseInfo.getBodyOffset()
oBody=oResponse.tostring()[oBodyOffset:]
ifstr(nBody) ==str(oBody):
returnresult
issuename="Dynamic JavaScript Code Detected"
issuelevel="Medium"
issuedetail="These two files contain differing contents. Check the contents of the files to ensure that they don't contain sensitive information."
issuebackground="Dynamically generated JavaScript might contain session or user relevant information. Contrary to regular content that is protected by Same-Origin Policy, scripts can be included by third parties. This can lead to leakage of user/session relevant information."
issueremediation="Applications should not store user/session relevant data in JavaScript files with known URLs. If strict separation of data and code is not possible, CSRF tokens should be used."
issueconfidence="Firm"
oOffsets=self.calculateHighlights(nBody, oBody, oBodyOffset)
nOffsets=self.calculateHighlights(oBody, nBody, nBodyOffset)
result=ScanIssue(oldRequestResponse.getHttpService(),
self._helpers.analyzeRequest(oldRequestResponse).getUrl(),
issuename, issuelevel, issuedetail, issuebackground, issueremediation, issueconfidence,
[self._callbacks.applyMarkers(oldRequestResponse, None, oOffsets),
self._callbacks.applyMarkers(newRequestResponse, None, nOffsets)])
returnresult
defreportDynamicOnly(self, firstRequestResponse, originalRequestResponse, secondRequestResponse):
"""Report Situation as Dynamic Only"""
issuename="Dynamic JavaScript Code Detected"
issuelevel="Information"
issueconfidence="Certain"
issuedetail="These files contain differing contents. Check the contents of the files to ensure that they don't contain sensitive information."
issuebackground="Dynamically generated JavaScript might contain session or user relevant information. Contrary to regular content that is protected by Same-Origin Policy, scripts can be included by third parties. This can lead to leakage of user/session relevant information."
issueremediation="Applications should not store user/session relevant data in JavaScript files with known URLs. If strict separation of data and code is not possible, CSRF tokens should be used."
nResponse=firstRequestResponse.getResponse()
nResponseInfo=self._helpers.analyzeResponse(nResponse)
nBodyOffset=nResponseInfo.getBodyOffset()
nBody=nResponse.tostring()[nBodyOffset:]
oResponse=originalRequestResponse.getResponse()
oResponseInfo=self._helpers.analyzeResponse(oResponse)
oBodyOffset=oResponseInfo.getBodyOffset()
oBody=oResponse.tostring()[oBodyOffset:]
sResponse=secondRequestResponse.getResponse()
sResponseInfo=self._helpers.analyzeResponse(sResponse)
sBodyOffset=sResponseInfo.getBodyOffset()
sBody=sResponse.tostring()[sBodyOffset:]
oOffsets=self.calculateHighlights(nBody, oBody, oBodyOffset)
nOffsets=self.calculateHighlights(oBody, nBody, nBodyOffset)
sOffsets=self.calculateHighlights(oBody, sBody, sBodyOffset)
result=ScanIssue(originalRequestResponse.getHttpService(),
self._helpers.analyzeRequest(originalRequestResponse).getUrl(),
issuename, issuelevel, issuedetail, issuebackground, issueremediation, issueconfidence,
[self._callbacks.applyMarkers(originalRequestResponse, None, oOffsets),
self._callbacks.applyMarkers(firstRequestResponse, None, nOffsets),
self._callbacks.applyMarkers(secondRequestResponse, None, sOffsets)])
returnresult
defcalculateHighlights(self, newBody, oldBody, bodyOffset):
"""find the exact points for highlighting the responses"""
s=difflib.SequenceMatcher(None, oldBody, newBody)
matching_blocks=s.get_matching_blocks()
offsets= []
poszero=0
posone=0
first=True
# can create slightly weird marks because of being as
# exact as one character. But I'd rather keep precision
forminmatching_blocks:
offset=array('i', [0, 0])
iffirst:
poszero=m.a+m.size
first=False
else:
posone=m.a
ifposone!=poszero:
offset[0] =poszero+bodyOffset
offset[1] =posone+bodyOffset
offsets.append(offset)
poszero=m.a+m.size
returnoffsets
defconsolidateDuplicateIssues(self, existingIssue, newIssue):
newRequestResponse=newIssue.getHttpMessages()[0]
newUrl=str(self._helpers.analyzeRequest(newRequestResponse).getUrl())
existingRequestResponse=existingIssue.getHttpMessages()[0]
existingUrl=str(self._helpers.analyzeRequest(
existingRequestResponse).getUrl())
if (existingIssue.getIssueName() ==newIssue.getIssueName() and
existingIssue.getIssueType() ==newIssue.getIssueType() and
existingUrl==newUrl):
return-1
else:
return0
classScanIssue(IScanIssue):
def__init__(self, httpservice, url, name, severity, detailmsg, background, remediation, confidence, requests):
self._url=url
self._httpservice=httpservice
self._name=name
self._severity=severity
self._detailmsg=detailmsg
self._issuebackground=background
self._issueremediation=remediation
self._confidence=confidence
self._httpmsgs=requests
defgetUrl(self):
returnself._url
defgetHttpMessages(self):
returnself._httpmsgs
defgetHttpService(self):
returnself._httpservice
defgetRemediationDetail(self):
returnNone
defgetIssueDetail(self):
returnself._detailmsg
defgetIssueBackground(self):
returnself._issuebackground
defgetRemediationBackground(self):
returnself._issueremediation
defgetIssueType(self):
return0
defgetIssueName(self):
returnself._name
defgetSeverity(self):
returnself._severity
defgetConfidence(self):
returnself._confidence