forked from sajjadium/Crawlium
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinclusion_tree.py
More file actions
executable file
·426 lines (333 loc) · 16.2 KB
/
inclusion_tree.py
File metadata and controls
executable file
·426 lines (333 loc) · 16.2 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
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
#!/usr/bin/python
import re
import sys
import json
import copy
import hashlib
import base64
import traceback
import gzip
import StringIO
import urlparse
from collections import OrderedDict
def get_scriptid_from_stack_trace(stack):
if len(stack['callFrames']) == 0:
return None
for f in stack['callFrames']:
if f['functionName'].strip() == '':
return f['scriptId']
return f['scriptId']
def handle_request_response(method, params):
requestId = params['requestId']
if method == 'Network.requestWillBeSent':
resourceUrl = params['request']['url'].strip()
parsed_url = urlparse.urlparse(resourceUrl)
if requestId not in resource_requests:
resource_requests[requestId] = []
resource_requests[requestId].append(params)
elif method == 'Network.responseReceived':
resourceType = params['type'].strip().lower()
resourceUrl = params['response']['url'].strip()
resourceMimeType = params['response']['mimeType']
frameId = params['frameId']
loaderId = params['loaderId']
if requestId not in resource_requests:
return
resource_requests[requestId].append(params)
resourceHeaders = []
if resourceType == 'other' and ('javascript' in resourceMimeType or 'ecmascript' in resourceMimeType):
resourceType = 'script'
for i in range(1, len(resource_requests[requestId])):
response = None
if 'redirectResponse' in resource_requests[requestId][i]:
response = resource_requests[requestId][i]['redirectResponse']
elif 'response' in resource_requests[requestId][i]:
response = resource_requests[requestId][i]['response']
if response is not None:
resourceHeaders.append(OrderedDict([
('timestamp', resource_requests[requestId][i - 1]['wallTime']),
('method', resource_requests[requestId][i - 1]['request']['method']),
('status', (str(response['status']) + ' ' + response['statusText']).strip()),
('url', response['url'].strip()),
('request', None),
('response', None)
]))
if resourceHeaders[-1]['method'] == 'POST':
resourceHeaders[-1]['data'] = None
if 'postData' in resource_requests[requestId][i - 1]['request']:
resourceHeaders[-1]['data'] = resource_requests[requestId][i - 1]['request']['postData']
if 'requestHeaders' in response:
resourceHeaders[-1]['request'] = {}
for name, value in response['requestHeaders'].items():
if not name.startswith(':'):
resourceHeaders[-1]['request'][name] = value
elif 'request' in resource_requests[requestId][i - 1] and \
'headers' in resource_requests[requestId][i - 1]['request']:
resourceHeaders[-1]['request'] = {}
for name, value in resource_requests[requestId][i - 1]['request']['headers'].items():
if not name.startswith(':'):
resourceHeaders[-1]['request'][name] = value
if 'headers' in response:
resourceHeaders[-1]['response'] = {}
for name, value in response['headers'].items():
if not name.startswith(':'):
resourceHeaders[-1]['response'][name] = value
if not resourceUrl.startswith('http:') and not resourceUrl.startswith('https:'):
resourceHeaders = None
initiator_script_id = None
initiator = resource_requests[requestId][0]['initiator']
if initiator['type'].strip().lower() == 'script':
initiator_script_id = get_scriptid_from_stack_trace(initiator['stack'])
inclusion_tree_node = OrderedDict([
('type', resourceType),
('url', resourceUrl),
('headers', resourceHeaders),
('children', [])
])
if resourceType == 'document':
inclusion_tree[('document', frameId, loaderId)] = inclusion_tree_node
if frameId not in frames:
frames[frameId] = {}
if initiator_script_id is not None:
frames[frameId]['initiatorScriptId'] = initiator_script_id
frames[frameId]['loaderId'] = loaderId
else:
if resourceType == 'script':
inclusion_tree[('script', frameId, resourceUrl)] = inclusion_tree_node
initiator_script_key = ('script', initiator_script_id)
if initiator_script_id is not None and initiator_script_key in inclusion_tree:
inclusion_tree[initiator_script_key]['children'].append(inclusion_tree_node)
else:
resource_doc_key = ('document', frameId, loaderId)
if resource_doc_key in inclusion_tree:
inclusion_tree[resource_doc_key]['children'].append(inclusion_tree_node)
del resource_requests[requestId]
def handle_frame(method, params):
global root_doc
if method == 'Page.frameAttached':
frameId = params['frameId']
if frameId not in frames:
frames[frameId] = {}
if 'stack' in params:
frames[frameId]['initiatorScriptId'] = get_scriptid_from_stack_trace(params['stack'])
elif method == 'Page.frameNavigated':
frameId = params['frame']['id']
parentFrameId = params['frame']['parentId'] if 'parentId' in params['frame'] else None
loaderId = params['frame']['loaderId']
url = params['frame']['url'].strip()
#if not url.strip().lower().startswith('http:') and not url.strip().lower().startswith('https:'):
# return
if frameId not in frames:
frames[frameId] = {}
frames[frameId]['parentId'] = parentFrameId
frames[frameId]['loaderId'] = loaderId
frame_key = ('document', frameId, loaderId)
if frame_key not in inclusion_tree:
inclusion_tree[frame_key] = OrderedDict([
('type', 'document'),
('url', url),
('headers', None),
('children', [])
])
frame_loaders[frameId] = loaderId
if 'initiatorScriptId' in frames[frameId]:
inclusion_tree[('script', frames[frameId]['initiatorScriptId'])]['children'].append(inclusion_tree[frame_key])
elif parentFrameId is not None:
parent_frame_key = ('document', parentFrameId, frames[parentFrameId]['loaderId'])
inclusion_tree[parent_frame_key]['children'].append(inclusion_tree[frame_key])
elif root_doc is None:
root_doc = frame_key
if 'executionContextId' in frames[frameId]:
executionContextId = frames[frameId]['executionContextId']
alt_frame_key = ('document', frameId, executionContextId)
if alt_frame_key not in inclusion_tree:
inclusion_tree[alt_frame_key] = inclusion_tree[frame_key]
elif method == 'Runtime.executionContextCreated':
frameId = params['context']['auxData']['frameId']
executionContextId = params['context']['id']
if frameId not in frames:
frames[frameId] = {}
frames[frameId]['executionContextId'] = executionContextId
if 'loaderId' in frames[frameId]:
inclusion_tree[('document', frameId, executionContextId)] = inclusion_tree[('document', frameId, frames[frameId]['loaderId'])]
def handle_script(method, params):
scriptId = params['scriptId']
frameId = params['executionContextAuxData']['frameId']
scriptUrl = params['url'].strip()
if scriptUrl.lower().startswith('extensions::') or \
scriptUrl.lower().startswith('chrome-extension://'):
return
script_key = ('script', frameId, scriptUrl)
if script_key in inclusion_tree:
inclusion_tree[('script', scriptId)] = inclusion_tree[script_key]
del inclusion_tree[script_key]
else:
inclusion_tree[('script', scriptId)] = OrderedDict([
('type', 'script'),
('url', None),
('headers', None),
('children', [])
])
if 'stack' in params:
initiatorScriptId = get_scriptid_from_stack_trace(params['stack'])
inclusion_tree[('script', initiatorScriptId)]['children'].append(inclusion_tree[('script', scriptId)])
else:
if frameId in frames and 'loaderId' in frames[frameId]:
inclusion_tree[('document', frameId, frames[frameId]['loaderId'])]['children'].append(\
inclusion_tree[('script', scriptId)])
def handle_websocket(method, websocket):
requestId = websocket['requestId']
if method == 'Network.webSocketCreated':
new_node = OrderedDict([
('type', 'websocket'),
('url', websocket['url'].strip()),
('headers', []),
('data', []),
('closeTimestamp', None)
])
if requestId not in websockets:
websockets[requestId] = {
'scriptId': None,
'wallTime': None,
'docUrl': None
}
if 'initiator' in websocket and \
'type' in websocket['initiator'] and \
websocket['initiator']['type'].strip().lower() == 'script' and \
'stack' in websocket['initiator']:
websockets[requestId]['scriptId'] = get_scriptid_from_stack_trace(websocket['initiator']['stack'])
if ('script', websockets[requestId]['scriptId']) in inclusion_tree:
inclusion_tree[('script', websockets[requestId]['scriptId'])]['children'].append(new_node)
else:
inclusion_tree[root_doc]['children'].append(new_node)
websockets[requestId]['node'] = new_node
elif method == 'Network.webSocketWillSendHandshakeRequest':
websockets[requestId]['timestamp'] = websocket['timestamp']
websockets[requestId]['wallTime'] = websocket['wallTime']
websockets[requestId]['node']['headers'].append({
'timestamp': websocket['wallTime'],
'request': websocket['request']['headers']
})
elif method == 'Network.webSocketHandshakeResponseReceived':
websockets[requestId]['node']['headers'][-1]['response'] = websocket['response']['headers']
websockets[requestId]['node']['headers'][-1]['status'] = \
(str(websocket['response']['status']) + ' ' + websocket['response']['statusText']).strip()
elif method in ['Network.webSocketFrameSent', 'Network.webSocketFrameReceived']:
websockets[requestId]['node']['data'].append({
'type': 'send' if method == 'Network.webSocketFrameSent' else 'receive',
'timestamp': websockets[requestId]['wallTime'] + websocket['timestamp'] - websockets[requestId]['timestamp']
})
websockets[requestId]['node']['data'][-1].update(websocket['response'])
elif method == 'Network.webSocketClosed':
if websockets[requestId]['wallTime']:
websockets[requestId]['node']['closeTimestamp'] = websockets[requestId]['wallTime'] + \
websocket['timestamp'] - \
websockets[requestId]['timestamp']
def handle_console(method, params):
if 'args' in params and len(params['args']) > 0 and \
'type' in params['args'][0] and params['args'][0]['type'].strip().lower() == 'string' and \
'value' in params['args'][0] and params['args'][0]['value'].strip().lower().startswith('sajjad_'):
msg_content = params['args'][0]['value'].strip()
if msg_content.startswith('sajjad_links_') or \
msg_content.startswith('sajjad_styles_') or \
msg_content.startswith('sajjad_doctype_'):
return
elif msg_content.startswith('sajjad_adblockplus_'):
message = json.loads(msg_content.replace('sajjad_adblockplus_', ''))
location = urlparse.urldefrag(message['location'].strip())[0]
if location not in roles:
roles[location] = set()
for l in message['lists']:
if l.strip().lower() in adblockplus_lists:
roles[location].add(adblockplus_lists[l.strip().lower()])
else:
roles[location].add(l)
else:
message = json.loads(params['args'][0]['value'].replace('sajjad_', ''))
message['timestamp'] = params['timestamp'] if 'timestamp' in params else None
script_id = None
if 'stackTrace' in params:
script_id = get_scriptid_from_stack_trace(params['stackTrace'])
if message['class'] in ['RTCPeerConnection', 'RTCDataChannel']:
if 'output' in message and type(message['output']) == dict and 'sajjadId' in message['output']:
del message['output']['sajjadId']
api = OrderedDict([
('type', 'webrtc'),
('timestamp', message['timestamp']),
('class', message['class']),
('method', message['method']),
('args', message['args']),
('output', message['output'])
])
if ('script', script_id) in inclusion_tree:
inclusion_tree[('script', script_id)]['children'].append(api)
def handle_cookie(method, params):
if params is not None and 'cookies' in params:
for coo in params['cookies']:
cookies.add(json.dumps(coo))
def prune_inclusion_tree(inc_tree):
if 'children' in inc_tree:
pos = 0
while pos < len(inc_tree['children']):
child = inc_tree['children'][pos]
prune_inclusion_tree(child)
if 'children' in child and len(child['children']) == 0 and child['url'] is None:
del inc_tree['children'][pos]
else:
pos += 1
def get_inclusion_tree(raw_logs):
global frames
global resource_requests
global frame_loaders
global inclusion_tree
global websockets
global root_doc
global roles
global adblockplus_lists
global cookies
pages = json.loads(raw_logs)
handlers = {
'Network.webSocketCreated': handle_websocket,
'Network.webSocketWillSendHandshakeRequest': handle_websocket,
'Network.webSocketHandshakeResponseReceived': handle_websocket,
'Network.webSocketFrameSent': handle_websocket,
'Network.webSocketFrameReceived': handle_websocket,
'Network.webSocketClosed': handle_websocket,
'Network.requestWillBeSent': handle_request_response,
'Network.responseReceived': handle_request_response,
'Page.frameNavigated': handle_frame,
'Page.frameAttached': handle_frame,
'Runtime.executionContextCreated': handle_frame,
'Debugger.scriptParsed': handle_script,
'Runtime.consoleAPICalled': handle_console,
'Network.getAllCookies': handle_cookie
}
inclusions = []
for page in pages:
resource_requests = {}
frame_loaders = {}
inclusion_tree = {}
frames = {}
websockets = {}
root_doc = None
for event in page['events']:
try:
if event['method'] in handlers:
handlers[event['method']](event['method'], event['params'])
except:
print >> sys.stderr, traceback.format_exc(), page['url'], event
if root_doc is not None:
try:
if inclusion_tree[root_doc]['url'].strip().startswith('http'):
json.dumps(inclusion_tree[root_doc])
prune_inclusion_tree(inclusion_tree[root_doc])
inclusions.append(inclusion_tree[root_doc])
except:
print >> sys.stderr, traceback.format_exc()
return inclusions
if __name__ == '__main__':
try:
inclusions = get_inclusion_tree(open(sys.argv[1], 'r').read())
print json.dumps(inclusions)
except:
print >> sys.stderr, traceback.format_exc()